rca-umb commited on
Commit
ab59633
·
verified ·
1 Parent(s): 26270f3

Five Desks v5 collapse test (positive control)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +51 -0
  2. calibration/lottery-analysis.md +18 -0
  3. calibration/v4-arena-gap.md +33 -0
  4. calibration/v4a_r1_episodes.jsonl +0 -0
  5. calibration/v4a_r1_summary.json +509 -0
  6. calibration/v4a_r2-software_episodes.jsonl +16 -0
  7. calibration/v4a_r2-software_summary.json +41 -0
  8. calibration/v4a_r2_episodes.jsonl +0 -0
  9. calibration/v4a_r2_summary.json +211 -0
  10. calibration/v4a_r3-software_episodes.jsonl +32 -0
  11. calibration/v4a_r3-software_summary.json +69 -0
  12. source/.dockerignore +10 -0
  13. source/CHANGELOG.md +93 -0
  14. source/codedesk/Dockerfile +19 -0
  15. source/codedesk/__init__.py +0 -0
  16. source/codedesk/base.py +168 -0
  17. source/codedesk/build/Dockerfile.builder +5 -0
  18. source/codedesk/build/catalog.py +258 -0
  19. source/codedesk/build/package.py +54 -0
  20. source/codedesk/build/survey.sh +13 -0
  21. source/codedesk/build/validate.py +55 -0
  22. source/codedesk/environment.py +101 -0
  23. source/codedesk/families/__init__.py +6 -0
  24. source/codedesk/families/bugfix.py +221 -0
  25. source/codedesk/families/mediatools.py +345 -0
  26. source/codedesk/interface.py +72 -0
  27. source/codedesk/models.py +19 -0
  28. source/codedesk/requirements-tools.txt +5 -0
  29. source/codedesk/runner.py +88 -0
  30. source/codedesk/server/__init__.py +0 -0
  31. source/codedesk/server/app.py +12 -0
  32. source/codedesk/tests/__init__.py +0 -0
  33. source/codedesk/tests/test_codedesk.py +120 -0
  34. source/diligence/__init__.py +1 -0
  35. source/diligence/base.py +149 -0
  36. source/diligence/environment.py +115 -0
  37. source/diligence/families/__init__.py +12 -0
  38. source/diligence/families/finance.py +186 -0
  39. source/diligence/families/industrial.py +129 -0
  40. source/diligence/families/math_tasks.py +100 -0
  41. source/diligence/families/media.py +159 -0
  42. source/diligence/families/office.py +167 -0
  43. source/diligence/families/reasoning.py +195 -0
  44. source/diligence/families/science.py +198 -0
  45. source/diligence/families/security.py +209 -0
  46. source/diligence/families/software.py +384 -0
  47. source/diligence/interface.py +86 -0
  48. source/diligence/models.py +19 -0
  49. source/diligence/sandbox.py +111 -0
  50. source/openenv.yaml +7 -0
README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pretty_name: Five Desks v5 collapse test (positive control)
4
+ tags:
5
+ - openenv
6
+ - reinforcement-learning
7
+ - rl-environment
8
+ - control-experiment
9
+ configs:
10
+ - config_name: default
11
+ data_files:
12
+ - split: train
13
+ path: tasks.jsonl
14
+ ---
15
+
16
+ # Five Desks v5: a collapse test (positive control)
17
+
18
+ This is a deliberate diagnostic, not an attempt to improve the model. It asks one question: **does training in the
19
+ arena reach the private-task score at all?**
20
+
21
+ naklitechie's null control (no gradient at all) scored 1/40, and across the 45 evaluated runs so far, very different
22
+ training runs have produced statistically indistinguishable private scores (see
23
+ [`calibration/lottery-analysis.md`](./calibration/lottery-analysis.md)). Two explanations fit: training changes the
24
+ model too little to matter on unrelated tasks, or the scored model is not the trained one. A run that trains a
25
+ clearly destructive habit tells them apart.
26
+
27
+ ## What it trains
28
+
29
+ The tasks are Five Desks' normal eight-domain tool tasks with their normal briefs (`early-<task id>`; the model is
30
+ not told anything unusual). The reward ignores the answer and pays only for ending the episode early: 1.0 when the
31
+ first call ends it, falling linearly to 0 when the tool budget runs out. The untrained model's episode lengths vary
32
+ on every task, so every GRPO group has a gradient toward stopping sooner, until it submits or finishes immediately.
33
+
34
+ ## Pre-registered prediction
35
+
36
+ - If training reaches the score: the trained model stops investigating, and the private score falls to **0 or 1 out
37
+ of 40** (no run has scored 0 so far; about 9% of runs score 1 or less).
38
+ - If the score is 2 or more while the training curve shows near-immediate endings, the private evaluation is not
39
+ measuring the trained policy (or the habit does not carry over to the evaluation's tasks), and we will report it to
40
+ the operators with the training curve.
41
+
42
+ ## Run it yourself
43
+
44
+ The image is public and the exact request is [`submission_request.json`](./submission_request.json). Anyone can
45
+ submit it from their own account (change `submission_id`, and `dataset` if you want the run attributed to your own
46
+ dataset). Independent replicates make the answer stronger; please post your result on the board.
47
+
48
+ ## Source
49
+
50
+ [`source/`](./source): the environment (`diligence/`, control mode in `environment.py`), its tests (including the
51
+ control-mode tests), and the scripts. Image: `ghcr.io/rca-umb/five-desks:a2`.
calibration/lottery-analysis.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # What the 45 evaluated runs say (2026-10-12)
2
+
3
+ Source: `GET https://openenvarena-arena.hf.space/api/leaderboard` (`runs`, heldout-v2), saved as leaderboard-2026-10-12.json.
4
+
5
+ Per-domain solved counts across all 45 runs look like fixed per-task odds with no training effect:
6
+ - Industrial 0/1/2 = 11/22/12: two tasks solved about half the time (two fair coins give 11.25/22.5/11.25).
7
+ - Office 0/1/2/3 = 1/21/22/1: one task nearly always, one coin flip, one rare (2%).
8
+ - Software: one task in 29% of runs. Finance 7%, media 4%, math 2%, security 2%. Science 0/45.
9
+ - Mean of trained runs 2.98; the untrained model's expected score under these odds is about 2.9, and 40% of runs reach
10
+ 4 or more, so the reference 4/40 was an above-average draw, not a level training falls from.
11
+ - Domain-targeted runs show no gain in their domain: software-focused 0.25 vs 0.30; office-focused 1.20 vs 1.55.
12
+
13
+ Luck alone from our current bests (industrial 1, office 1), resampling each domain from the 45 runs:
14
+ 1 more run 3.2, 3 runs 4.6, 7 runs 5.9, 14 runs 6.9, 30 runs 8.1 expected total.
15
+
16
+ Implications: the board takes our best try, so it already gets best-of-many-attempts; training that only makes the
17
+ model more consistent adds nothing. Worth training for: tasks with rare or no solves. Specializing a run costs little
18
+ because training barely moves the model, so every run is still a draw in all eight domains.
calibration/v4-arena-gap.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # v4 (Five Desks Code) trains far below its calibration (2026-10-12, steps 1-44)
2
+
3
+ Arena training reward per task (Trackio `reward` by `step/task`, 4-5 steps each) vs our lenient calibration:
4
+
5
+ | task | arena | lenient calibration | strict calibration |
6
+ |---|---|---|---|
7
+ | bugfix-office-l1 | 0.10 | 0.56 | 0.00 |
8
+ | bugfix-finance-l1 | 0.20 | 0.50 | 0.06 |
9
+ | bugfix-science-l1 | 0.05 | 0.31 | 0.00 |
10
+ | bugfix-industrial-l2 | 0.38 | 0.38 | 0.00 |
11
+ | bugfix-media-l2 | 0.38 | 0.56 | 0.00 |
12
+ | bugfix-security-l2 | 0.12 | 0.50 | 0.00 |
13
+ | bugfix-software-l2 | 0.00 | 0.69 | 0.00 |
14
+ | bugfix-math-l1 | 0.06 | 0.50 | 0.06 |
15
+ | media-production-l2 | 0.44 | 0.44 | 0.12 |
16
+
17
+ - Overall 0.19 vs 0.49. Arena episodes use about 520 model tokens (Trackio completions/mean_length) vs about 1,500 in
18
+ calibration, while A-style tasks match (v3 483 in the arena vs 385 calibrated). So B episodes end early.
19
+ - `completions/clipped_ratio` tracks the step's reward almost exactly in v4 (step 22: reward 1.0, clipped 1.0); in v3
20
+ it was 1.00 on every task. It seems to mark episodes that ended through the environment (submit); the rest of v4's
21
+ episodes end early, after 300-600 tokens.
22
+ - Not the cause: grading time (2-6 s, srt 64 s, more-itertools 20-38 s under emulation, below tool_wall_s 120); raw
23
+ newlines in JSON strings (none); braces in prose (first-brace parsing equals lenient).
24
+ - Best fit: replies with reasoning text before the JSON are rejected (the guide's rule is "exactly one JSON object and
25
+ nothing else"). Strict-leaning rules fit the arena per-task rewards much better than lenient (sum of squared
26
+ errors 0.33-0.43 vs 1.13). In calibration the first non-strict reply in a bugfix episode comes at turn 5-8.
27
+ - Tension: v3's industrial task matched lenient (arena 0.80) although our calibration model wrote prose in 69% of
28
+ those episodes. So the arena's model probably writes prose less often than ours on easy tool steps (different
29
+ system prompt or template) and more often when it has to reason about code.
30
+
31
+ Implications: calibrate with strict parsing for reasoning-heavy tasks; in the failure study, record whether a base
32
+ failure is a format ending (prose) or a wrong answer. If prose endings dominate on hard tasks, staying in format
33
+ while reasoning is a cross-domain training target.
calibration/v4a_r1_episodes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
calibration/v4a_r1_summary.json ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 240,
5
+ "seconds": 338,
6
+ "usage": {
7
+ "prompt_tokens": 2118499,
8
+ "completion_tokens": 92518,
9
+ "calls": 1977,
10
+ "empty_content": 14
11
+ },
12
+ "tasks": {
13
+ "software-repofix-l1": {
14
+ "n": 12,
15
+ "mean": 0.917,
16
+ "solved": 11,
17
+ "rewards": [
18
+ 1.0,
19
+ 1.0,
20
+ 1.0,
21
+ 1.0,
22
+ 1.0,
23
+ 1.0,
24
+ 0.0,
25
+ 1.0,
26
+ 1.0,
27
+ 1.0,
28
+ 1.0,
29
+ 1.0
30
+ ],
31
+ "ends": {
32
+ "submitted": 12
33
+ },
34
+ "turns": 8.5,
35
+ "rescued_replies": 0
36
+ },
37
+ "software-repofix-l2": {
38
+ "n": 12,
39
+ "mean": 0.083,
40
+ "solved": 1,
41
+ "rewards": [
42
+ 0.0,
43
+ 0.0,
44
+ 0.0,
45
+ 0.0,
46
+ 0.0,
47
+ 0.0,
48
+ 0.0,
49
+ 0.0,
50
+ 1.0,
51
+ 0.0,
52
+ 0.0,
53
+ 0.0
54
+ ],
55
+ "ends": {
56
+ "submitted": 12
57
+ },
58
+ "turns": 6.8,
59
+ "rescued_replies": 0
60
+ },
61
+ "industrial-telemetry-l1": {
62
+ "n": 12,
63
+ "mean": 0.833,
64
+ "solved": 10,
65
+ "rewards": [
66
+ 1.0,
67
+ 0.0,
68
+ 0.0,
69
+ 1.0,
70
+ 1.0,
71
+ 1.0,
72
+ 1.0,
73
+ 1.0,
74
+ 1.0,
75
+ 1.0,
76
+ 1.0,
77
+ 1.0
78
+ ],
79
+ "ends": {
80
+ "submitted": 10,
81
+ "no_json": 1,
82
+ "schema_invalid": 1
83
+ },
84
+ "turns": 6.9,
85
+ "rescued_replies": 13
86
+ },
87
+ "industrial-telemetry-l2": {
88
+ "n": 12,
89
+ "mean": 0.833,
90
+ "solved": 10,
91
+ "rewards": [
92
+ 1.0,
93
+ 1.0,
94
+ 1.0,
95
+ 1.0,
96
+ 1.0,
97
+ 1.0,
98
+ 1.0,
99
+ 0.0,
100
+ 1.0,
101
+ 1.0,
102
+ 0.0,
103
+ 1.0
104
+ ],
105
+ "ends": {
106
+ "submitted": 11,
107
+ "no_json": 1
108
+ },
109
+ "turns": 6.8,
110
+ "rescued_replies": 7
111
+ },
112
+ "industrial-telemetry-l3": {
113
+ "n": 12,
114
+ "mean": 0.5,
115
+ "solved": 6,
116
+ "rewards": [
117
+ 1.0,
118
+ 0.0,
119
+ 1.0,
120
+ 0.0,
121
+ 1.0,
122
+ 1.0,
123
+ 0.0,
124
+ 0.0,
125
+ 0.0,
126
+ 0.0,
127
+ 1.0,
128
+ 1.0
129
+ ],
130
+ "ends": {
131
+ "submitted": 9,
132
+ "no_json": 1,
133
+ "out_of_steps": 1,
134
+ "truncated": 1
135
+ },
136
+ "turns": 8.2,
137
+ "rescued_replies": 16
138
+ },
139
+ "science-lab-l1": {
140
+ "n": 12,
141
+ "mean": 0.917,
142
+ "solved": 11,
143
+ "rewards": [
144
+ 1.0,
145
+ 1.0,
146
+ 1.0,
147
+ 1.0,
148
+ 1.0,
149
+ 1.0,
150
+ 1.0,
151
+ 1.0,
152
+ 1.0,
153
+ 1.0,
154
+ 0.0,
155
+ 1.0
156
+ ],
157
+ "ends": {
158
+ "submitted": 11,
159
+ "schema_invalid": 1
160
+ },
161
+ "turns": 6,
162
+ "rescued_replies": 1
163
+ },
164
+ "science-lab-l2": {
165
+ "n": 12,
166
+ "mean": 0.583,
167
+ "solved": 7,
168
+ "rewards": [
169
+ 0.0,
170
+ 1.0,
171
+ 1.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 1.0,
176
+ 1.0,
177
+ 1.0,
178
+ 1.0,
179
+ 1.0,
180
+ 0.0
181
+ ],
182
+ "ends": {
183
+ "submitted": 11,
184
+ "schema_invalid": 1
185
+ },
186
+ "turns": 5.6,
187
+ "rescued_replies": 1
188
+ },
189
+ "science-lab-l3": {
190
+ "n": 12,
191
+ "mean": 0.583,
192
+ "solved": 7,
193
+ "rewards": [
194
+ 1.0,
195
+ 1.0,
196
+ 0.0,
197
+ 1.0,
198
+ 1.0,
199
+ 0.0,
200
+ 0.0,
201
+ 0.0,
202
+ 1.0,
203
+ 1.0,
204
+ 1.0,
205
+ 0.0
206
+ ],
207
+ "ends": {
208
+ "submitted": 11,
209
+ "schema_invalid": 1
210
+ },
211
+ "turns": 5.8,
212
+ "rescued_replies": 3
213
+ },
214
+ "office-scheduling-l1": {
215
+ "n": 12,
216
+ "mean": 0.25,
217
+ "solved": 3,
218
+ "rewards": [
219
+ 0.0,
220
+ 1.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 1.0,
225
+ 1.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0
231
+ ],
232
+ "ends": {
233
+ "submitted": 12
234
+ },
235
+ "turns": 6.2,
236
+ "rescued_replies": 0
237
+ },
238
+ "office-scheduling-l2": {
239
+ "n": 12,
240
+ "mean": 0.083,
241
+ "solved": 1,
242
+ "rewards": [
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 1.0,
251
+ 0.0,
252
+ 0.0,
253
+ 0.0,
254
+ 0.0
255
+ ],
256
+ "ends": {
257
+ "submitted": 12
258
+ },
259
+ "turns": 7.2,
260
+ "rescued_replies": 0
261
+ },
262
+ "finance-receivables-l1": {
263
+ "n": 12,
264
+ "mean": 0.25,
265
+ "solved": 3,
266
+ "rewards": [
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 1.0,
272
+ 1.0,
273
+ 1.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0
279
+ ],
280
+ "ends": {
281
+ "submitted": 9,
282
+ "out_of_steps": 3
283
+ },
284
+ "turns": 10.3,
285
+ "rescued_replies": 4
286
+ },
287
+ "finance-receivables-l2": {
288
+ "n": 12,
289
+ "mean": 0.417,
290
+ "solved": 5,
291
+ "rewards": [
292
+ 0.0,
293
+ 0.0,
294
+ 1.0,
295
+ 0.0,
296
+ 1.0,
297
+ 0.0,
298
+ 1.0,
299
+ 1.0,
300
+ 0.0,
301
+ 1.0,
302
+ 0.0,
303
+ 0.0
304
+ ],
305
+ "ends": {
306
+ "out_of_steps": 1,
307
+ "submitted": 11
308
+ },
309
+ "turns": 10.3,
310
+ "rescued_replies": 6
311
+ },
312
+ "math-problems-l1": {
313
+ "n": 12,
314
+ "mean": 1.0,
315
+ "solved": 12,
316
+ "rewards": [
317
+ 1.0,
318
+ 1.0,
319
+ 1.0,
320
+ 1.0,
321
+ 1.0,
322
+ 1.0,
323
+ 1.0,
324
+ 1.0,
325
+ 1.0,
326
+ 1.0,
327
+ 1.0,
328
+ 1.0
329
+ ],
330
+ "ends": {
331
+ "submitted": 12
332
+ },
333
+ "turns": 5.4,
334
+ "rescued_replies": 1
335
+ },
336
+ "math-problems-l2": {
337
+ "n": 12,
338
+ "mean": 0.333,
339
+ "solved": 4,
340
+ "rewards": [
341
+ 1.0,
342
+ 0.0,
343
+ 0.0,
344
+ 1.0,
345
+ 0.0,
346
+ 0.0,
347
+ 0.0,
348
+ 1.0,
349
+ 0.0,
350
+ 0.0,
351
+ 0.0,
352
+ 1.0
353
+ ],
354
+ "ends": {
355
+ "submitted": 11,
356
+ "schema_invalid": 1
357
+ },
358
+ "turns": 3.7,
359
+ "rescued_replies": 1
360
+ },
361
+ "security-audit-l1": {
362
+ "n": 12,
363
+ "mean": 0.667,
364
+ "solved": 8,
365
+ "rewards": [
366
+ 0.0,
367
+ 1.0,
368
+ 0.0,
369
+ 0.0,
370
+ 1.0,
371
+ 0.0,
372
+ 1.0,
373
+ 1.0,
374
+ 1.0,
375
+ 1.0,
376
+ 1.0,
377
+ 1.0
378
+ ],
379
+ "ends": {
380
+ "submitted": 10,
381
+ "out_of_steps": 2
382
+ },
383
+ "turns": 10.6,
384
+ "rescued_replies": 0
385
+ },
386
+ "security-audit-l2": {
387
+ "n": 12,
388
+ "mean": 0.75,
389
+ "solved": 9,
390
+ "rewards": [
391
+ 1.0,
392
+ 1.0,
393
+ 1.0,
394
+ 0.0,
395
+ 1.0,
396
+ 1.0,
397
+ 1.0,
398
+ 0.0,
399
+ 1.0,
400
+ 0.0,
401
+ 1.0,
402
+ 1.0
403
+ ],
404
+ "ends": {
405
+ "submitted": 11,
406
+ "schema_invalid": 1
407
+ },
408
+ "turns": 8.8,
409
+ "rescued_replies": 0
410
+ },
411
+ "security-audit-l3": {
412
+ "n": 12,
413
+ "mean": 0.75,
414
+ "solved": 9,
415
+ "rewards": [
416
+ 1.0,
417
+ 1.0,
418
+ 1.0,
419
+ 0.0,
420
+ 1.0,
421
+ 0.0,
422
+ 0.0,
423
+ 1.0,
424
+ 1.0,
425
+ 1.0,
426
+ 1.0,
427
+ 1.0
428
+ ],
429
+ "ends": {
430
+ "submitted": 9,
431
+ "schema_invalid": 3
432
+ },
433
+ "turns": 8.2,
434
+ "rescued_replies": 0
435
+ },
436
+ "media-copyedit-l1": {
437
+ "n": 12,
438
+ "mean": 0.5,
439
+ "solved": 6,
440
+ "rewards": [
441
+ 0.0,
442
+ 1.0,
443
+ 1.0,
444
+ 1.0,
445
+ 0.0,
446
+ 0.0,
447
+ 1.0,
448
+ 0.0,
449
+ 1.0,
450
+ 0.0,
451
+ 0.0,
452
+ 1.0
453
+ ],
454
+ "ends": {
455
+ "submitted": 12
456
+ },
457
+ "turns": 12.1,
458
+ "rescued_replies": 0
459
+ },
460
+ "media-copyedit-l2": {
461
+ "n": 12,
462
+ "mean": 0.333,
463
+ "solved": 4,
464
+ "rewards": [
465
+ 0.0,
466
+ 1.0,
467
+ 0.0,
468
+ 1.0,
469
+ 1.0,
470
+ 0.0,
471
+ 0.0,
472
+ 0.0,
473
+ 0.0,
474
+ 1.0,
475
+ 0.0,
476
+ 0.0
477
+ ],
478
+ "ends": {
479
+ "submitted": 12
480
+ },
481
+ "turns": 12.4,
482
+ "rescued_replies": 0
483
+ },
484
+ "media-copyedit-l3": {
485
+ "n": 12,
486
+ "mean": 0.5,
487
+ "solved": 6,
488
+ "rewards": [
489
+ 0.0,
490
+ 1.0,
491
+ 1.0,
492
+ 0.0,
493
+ 1.0,
494
+ 0.0,
495
+ 1.0,
496
+ 0.0,
497
+ 1.0,
498
+ 0.0,
499
+ 1.0,
500
+ 0.0
501
+ ],
502
+ "ends": {
503
+ "submitted": 12
504
+ },
505
+ "turns": 14,
506
+ "rescued_replies": 0
507
+ }
508
+ }
509
+ }
calibration/v4a_r2-software_episodes.jsonl ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#693)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([14, 12, 4, 4, 8], 2)\\nassert got == [13.0, 8.0, 4.0, 6.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: a window longer than the series is a caller bug and must raise ValueError, not return [].\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n if window > len(values):\\n raise ValueError(\\\"window must be <= length of values\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 358 characters to smooth.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 113835451198105, "n_turns": 8}
2
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- open_file {\\\"path\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#590)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"omar@x.org\\\", \\\" kim@y.com\\\", \\\"OMAR@X.org\\\", \\\"ben@z.net\\\"])\\nassert got == [\\\"omar@x.org\\\", \\\"kim@y.com\\\", \\\"ben@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"file\": \"contacts.py\", \"text\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key not in seen:\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 406 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 68083346637498, "n_turns": 8}
3
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- save_file {\\\"filename\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#976)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([2, 10, 16, 18, 6], 2)\\nassert got == [6.0, 13.0, 17.0, 12.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: a window longer than the series is a caller bug and must raise ValueError, not return [].\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"save_file\", \"args\": {\"filename\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n if window > len(values):\\n raise ValueError(\\\"window longer than series\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 349 characters to smooth.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 78862958890397, "n_turns": 8}
4
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_files {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- save_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#717)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**a.osei**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: negative totals (refund rows that leak in) must raise ValueError.\\n\\n**a.osei**: thanks, makes sense.\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"test_pricing.py\"}}"}, {"obs": "{\"output\": \"from pricing import discounted_total\\nassert discounted_total(1000.5) == 900.45\\nassert discounted_total(500) == 475.0, discounted_total(500)\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"README.md\"}}"}, {"obs": "{\"output\": \"# pricing\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"save_file\", \"args\": {\"filename\": \"pricing.py\", \"body\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n if total < 0:\\n raise ValueError(\\\"order total must not be negative\\\")\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 395 characters to pricing.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 19052712760856, "n_turns": 9}
5
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- open_file {\\\"path\\\": string}: show one file\\n- write_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#558)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: a window longer than the series is a caller bug and must raise ValueError, not return [].\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"open_file\", \"args\": {\"path\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([8, 12, 6, 16], 2)\\nassert got == [10.0, 9.0, 11.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"write_file\", \"args\": {\"path\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n if window > len(values):\\n raise ValueError(\\\"window longer than series\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 349 characters to smooth.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 21071013662979, "n_turns": 8}
6
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- show_file {\\\"path\\\": string}: show one file\\n- replace_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#825)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([8, 2, 8, 14], 2)\\nassert got == [5.0, 5.0, 11.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"filename\": \"smooth.py\", \"content\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 121483225444058, "n_turns": 7}
7
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- show_file {\\\"filename\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#272)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"test_pricing.py\"}}"}, {"obs": "{\"output\": \"from pricing import discounted_total\\nassert discounted_total(1000.5) == 900.45\\nassert discounted_total(500) == 475.0, discounted_total(500)\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: negative totals (refund rows that leak in) must raise ValueError.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"pricing.py\", \"text\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n if total < 0:\\n raise ValueError(\\\"total must be non-negative\\\")\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 389 characters to pricing.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 154009852028666, "n_turns": 8}
8
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- write_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#980)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"ana@x.org\\\", \\\" raj@y.com\\\", \\\"ANA@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"ana@x.org\\\", \\\"raj@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"write_file\", \"args\": {\"filename\": \"contacts.py\", \"content\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 415 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 190595402470320, "n_turns": 8}
9
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_files {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#458)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"5h2m\\\") == 18120\\nassert parse_duration(\\\"2m42s\\\") == 162, parse_duration(\\\"2m42s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**a.osei**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**a.osei**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "The bug: `UNITS` lacks `\"s\"`, so seconds contribute 0. The comments also note a bare number should mean seconds. Let me fix.\n\n{\"tool\": \"replace_file\", \"args\": {\"file\": \"durations.py\", \"text\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\n\\n A bare number with no unit (e.g. '90') means seconds.\\n \\\"\\\"\\\"\\n text = text.strip().lower()\\n # A bare number with no unit means seconds.\\n m = re.fullmatch(r\\\"\\\\d+\\\", text)\\n if m:\\n return int(text)\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 501 characters to durations.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "Tests pass. The fix handles the seconds unit and bare-number-as-seconds per the maintainer's decision. Submitting.\n\n{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 2, "seed": 5720799941610, "n_turns": 8}
10
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- open_file {\\\"file\\\": string}: show one file\\n- put_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#473)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([4, 12, 18, 2, 14, 8], 2)\\nassert got == [8.0, 15.0, 10.0, 8.0, 11.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**a.osei**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: a window longer than the series is a caller bug and must raise ValueError, not return [].\\n\\n**a.osei**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"put_file\", \"args\": {\"filename\": \"smooth.py\", \"body\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n if window > len(values):\\n raise ValueError(\\\"window longer than series\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 349 characters to smooth.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 229589758648595, "n_turns": 8}
11
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- show_file {\\\"filename\\\": string}: show one file\\n- write_file {\\\"file\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#799)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"2h53m\\\") == 10380\\nassert parse_duration(\\\"53m2s\\\") == 3182, parse_duration(\\\"53m2s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"README.md\"}}"}, {"obs": "{\"output\": \"# durations\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"write_file\", \"args\": {\"file\": \"durations.py\", \"content\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m', '2h5m10s' or bare seconds ('90').\\\"\\\"\\\"\\n text = text.strip().lower()\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text):\\n total += int(amount) * UNITS.get(unit, 0)\\n if not re.search(r\\\"\\\\d+[hms]\\\", text):\\n # No unit found: treat bare number as seconds.\\n m = re.search(r\\\"\\\\d+\\\", text)\\n if m:\\n total += int(m.group(0))\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 510 characters to durations.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 42521559342245, "n_turns": 9}
12
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- save_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#106)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"ana@x.org\\\", \\\" raj@y.com\\\", \\\"ANA@X.org\\\", \\\"ben@z.net\\\"])\\nassert got == [\\\"ana@x.org\\\", \\\"raj@y.com\\\", \\\"ben@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"save_file\", \"args\": {\"filename\": \"contacts.py\", \"body\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 415 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 45046015800264, "n_turns": 8}
13
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- show_file {\\\"filename\\\": string}: show one file\\n- write_file {\\\"path\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#105)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([2, 18, 2, 18, 2], 2)\\nassert got == [10.0, 10.0, 10.0, 10.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"write_file\", \"args\": {\"path\": \"smooth.py\", \"body\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 53873085256282, "n_turns": 7}
14
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- read_file {\\\"filename\\\": string}: show one file\\n- save_file {\\\"path\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#913)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"test_pricing.py\"}}"}, {"obs": "{\"output\": \"from pricing import discounted_total\\nassert discounted_total(1000.5) == 900.45\\nassert discounted_total(500) == 475.0, discounted_total(500)\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: negative totals (refund rows that leak in) must raise ValueError.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"README.md\"}}"}, {"obs": "{\"output\": \"# pricing\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"save_file\", \"args\": {\"path\": \"pricing.py\", \"body\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n if total < 0:\\n raise ValueError(\\\"order total must be non-negative\\\")\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 395 characters to pricing.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 180004690719015, "n_turns": 9}
15
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- read_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#764)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: negative totals (refund rows that leak in) must raise ValueError.\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"test_pricing.py\"}}"}, {"obs": "{\"output\": \"from pricing import discounted_total\\nassert discounted_total(2000) == 1800.0\\nassert discounted_total(500) == 475.0, discounted_total(500)\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"file\": \"pricing.py\", \"content\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n if total < 0:\\n raise ValueError(\\\"negative order total\\\")\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 383 characters to pricing.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 122727892637266, "n_turns": 8}
16
+ {"task_id": "software-repofix-l1", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- read_file {\\\"filename\\\": string}: show one file\\n- put_file {\\\"file\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (7 lines)\\nREADME.md (3 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#638)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\\nThere is some discussion in issue_comments.md.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**a.osei** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"3h41m\\\") == 13260\\nassert parse_duration(\\\"41m51s\\\") == 2511, parse_duration(\\\"41m51s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"put_file\", \"args\": {\"file\": \"durations.py\", \"content\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\n\\n A bare number with no unit (e.g. '90') is treated as seconds.\\n \\\"\\\"\\\"\\n text = text.strip().lower()\\n total = 0\\n matched = False\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text):\\n total += int(amount) * UNITS[unit]\\n matched = True\\n if not matched:\\n m = re.search(r\\\"\\\\d+\\\", text)\\n if m:\\n total += int(m.group())\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 533 characters to durations.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 62984163816181, "n_turns": 8}
calibration/v4a_r2-software_summary.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 16,
5
+ "seconds": 20,
6
+ "usage": {
7
+ "prompt_tokens": 96262,
8
+ "completion_tokens": 4128,
9
+ "calls": 129
10
+ },
11
+ "tasks": {
12
+ "software-repofix-l1": {
13
+ "n": 16,
14
+ "mean": 0.875,
15
+ "solved": 14,
16
+ "rewards": [
17
+ 1.0,
18
+ 1.0,
19
+ 1.0,
20
+ 1.0,
21
+ 1.0,
22
+ 0.0,
23
+ 1.0,
24
+ 1.0,
25
+ 1.0,
26
+ 1.0,
27
+ 1.0,
28
+ 1.0,
29
+ 0.0,
30
+ 1.0,
31
+ 1.0,
32
+ 1.0
33
+ ],
34
+ "ends": {
35
+ "submitted": 16
36
+ },
37
+ "turns": 8.1,
38
+ "rescued_replies": 2
39
+ }
40
+ }
41
+ }
calibration/v4a_r2_episodes.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
calibration/v4a_r2_summary.json ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 96,
5
+ "seconds": 142,
6
+ "usage": {
7
+ "prompt_tokens": 966636,
8
+ "completion_tokens": 37695,
9
+ "calls": 844,
10
+ "empty_content": 11
11
+ },
12
+ "tasks": {
13
+ "industrial-telemetry-l3": {
14
+ "n": 12,
15
+ "mean": 0.667,
16
+ "solved": 8,
17
+ "rewards": [
18
+ 1.0,
19
+ 0.0,
20
+ 1.0,
21
+ 1.0,
22
+ 1.0,
23
+ 1.0,
24
+ 0.0,
25
+ 1.0,
26
+ 1.0,
27
+ 0.0,
28
+ 1.0,
29
+ 0.0
30
+ ],
31
+ "ends": {
32
+ "submitted": 11,
33
+ "no_json": 1
34
+ },
35
+ "turns": 7.7,
36
+ "rescued_replies": 12
37
+ },
38
+ "science-lab-l3": {
39
+ "n": 12,
40
+ "mean": 0.583,
41
+ "solved": 7,
42
+ "rewards": [
43
+ 0.0,
44
+ 1.0,
45
+ 1.0,
46
+ 1.0,
47
+ 0.0,
48
+ 0.0,
49
+ 1.0,
50
+ 1.0,
51
+ 0.0,
52
+ 1.0,
53
+ 0.0,
54
+ 1.0
55
+ ],
56
+ "ends": {
57
+ "submitted": 11,
58
+ "schema_invalid": 1
59
+ },
60
+ "turns": 5.8,
61
+ "rescued_replies": 1
62
+ },
63
+ "office-scheduling-l1": {
64
+ "n": 12,
65
+ "mean": 0.417,
66
+ "solved": 5,
67
+ "rewards": [
68
+ 0.0,
69
+ 0.0,
70
+ 1.0,
71
+ 1.0,
72
+ 0.0,
73
+ 0.0,
74
+ 1.0,
75
+ 0.0,
76
+ 1.0,
77
+ 0.0,
78
+ 1.0,
79
+ 0.0
80
+ ],
81
+ "ends": {
82
+ "submitted": 12
83
+ },
84
+ "turns": 6.6,
85
+ "rescued_replies": 2
86
+ },
87
+ "finance-receivables-l2": {
88
+ "n": 12,
89
+ "mean": 0.167,
90
+ "solved": 2,
91
+ "rewards": [
92
+ 0.0,
93
+ 0.0,
94
+ 1.0,
95
+ 0.0,
96
+ 0.0,
97
+ 0.0,
98
+ 0.0,
99
+ 0.0,
100
+ 1.0,
101
+ 0.0,
102
+ 0.0,
103
+ 0.0
104
+ ],
105
+ "ends": {
106
+ "submitted": 9,
107
+ "out_of_steps": 3
108
+ },
109
+ "turns": 11.1,
110
+ "rescued_replies": 1
111
+ },
112
+ "math-problems-l2": {
113
+ "n": 12,
114
+ "mean": 0.5,
115
+ "solved": 6,
116
+ "rewards": [
117
+ 1.0,
118
+ 0.0,
119
+ 1.0,
120
+ 0.0,
121
+ 1.0,
122
+ 0.0,
123
+ 0.0,
124
+ 1.0,
125
+ 0.0,
126
+ 1.0,
127
+ 0.0,
128
+ 1.0
129
+ ],
130
+ "ends": {
131
+ "submitted": 11,
132
+ "schema_invalid": 1
133
+ },
134
+ "turns": 4.1,
135
+ "rescued_replies": 1
136
+ },
137
+ "security-audit-l3": {
138
+ "n": 12,
139
+ "mean": 0.417,
140
+ "solved": 5,
141
+ "rewards": [
142
+ 1.0,
143
+ 0.0,
144
+ 0.0,
145
+ 0.0,
146
+ 1.0,
147
+ 0.0,
148
+ 0.0,
149
+ 0.0,
150
+ 1.0,
151
+ 1.0,
152
+ 1.0,
153
+ 0.0
154
+ ],
155
+ "ends": {
156
+ "submitted": 8,
157
+ "schema_invalid": 4
158
+ },
159
+ "turns": 7.2,
160
+ "rescued_replies": 0
161
+ },
162
+ "media-copyedit-l2": {
163
+ "n": 12,
164
+ "mean": 0.167,
165
+ "solved": 2,
166
+ "rewards": [
167
+ 1.0,
168
+ 0.0,
169
+ 0.0,
170
+ 0.0,
171
+ 0.0,
172
+ 0.0,
173
+ 0.0,
174
+ 0.0,
175
+ 0.0,
176
+ 0.0,
177
+ 1.0,
178
+ 0.0
179
+ ],
180
+ "ends": {
181
+ "submitted": 12
182
+ },
183
+ "turns": 12.9,
184
+ "rescued_replies": 0
185
+ },
186
+ "media-copyedit-l3": {
187
+ "n": 12,
188
+ "mean": 0.5,
189
+ "solved": 6,
190
+ "rewards": [
191
+ 0.0,
192
+ 1.0,
193
+ 1.0,
194
+ 0.0,
195
+ 0.0,
196
+ 0.0,
197
+ 1.0,
198
+ 0.0,
199
+ 1.0,
200
+ 1.0,
201
+ 0.0,
202
+ 1.0
203
+ ],
204
+ "ends": {
205
+ "submitted": 12
206
+ },
207
+ "turns": 14.1,
208
+ "rescued_replies": 5
209
+ }
210
+ }
211
+ }
calibration/v4a_r3-software_episodes.jsonl ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_files {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#531)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"ana@x.org\\\", \\\" kim@y.com\\\", \\\"ANA@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"ana@x.org\\\", \\\"kim@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**a.osei**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**a.osei**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"README.md\"}}"}, {"obs": "{\"output\": \"# contacts\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"file\": \"contacts.py\", \"text\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 415 characters to contacts.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 180667159134856, "n_turns": 9}
2
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- cat {\\\"path\\\": string}: show one file\\n- replace_file {\\\"path\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#173)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"path\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"path\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"4h55m\\\") == 17700\\nassert parse_duration(\\\"55m12s\\\") == 3312, parse_duration(\\\"55m12s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"path\": \"durations.py\", \"content\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 303 characters to durations.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 257499109611777, "n_turns": 7}
3
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- read_file {\\\"path\\\": string}: show one file\\n- replace_file {\\\"path\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#562)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"ana@x.org\\\", \\\" raj@y.com\\\", \\\"ANA@X.org\\\", \\\"ben@z.net\\\"])\\nassert got == [\\\"ana@x.org\\\", \\\"raj@y.com\\\", \\\"ben@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"path\": \"contacts.py\", \"body\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n key = e.strip().lower()\\n if key not in seen:\\n seen.add(key)\\n result.append(e.strip())\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 333 characters to contacts.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 193659884419025, "n_turns": 7}
4
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- read_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#931)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([6, 10, 6, 6, 18], 2)\\nassert got == [8.0, 8.0, 6.0, 12.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"path\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 76711589914694, "n_turns": 7}
5
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- show_file {\\\"path\\\": string}: show one file\\n- put_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#565)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"put_file\", \"args\": {\"filename\": \"pricing.py\", \"content\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 316 characters to pricing.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 111078853271805, "n_turns": 6}
6
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pager.py, test_pager.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- save_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npager.py (6 lines)\\ntest_pager.py (5 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#355)\\n\\nUsers report that the first page of results is skipped: page 1 shows what should be page 2.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"pager.py\"}}"}, {"obs": "{\"output\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = page * per_page\\n return items[start:start + per_page]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"save_file\", \"args\": {\"path\": \"pager.py\", \"text\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = (page - 1) * per_page\\n return items[start:start + per_page]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 256 characters to pager.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 233000414919394, "n_turns": 6}
7
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- open_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"filename\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#562)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([14, 8, 16, 10, 14], 2)\\nassert got == [11.0, 12.0, 13.0, 12.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "The bug is off-by-one: it should be `range(len(values) - window + 1)` to include all full windows.\n\n{\"tool\": \"replace_file\", \"args\": {\"filename\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "Tests pass. Submitting.\n\n{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 2, "seed": 226990203463774, "n_turns": 7}
8
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- open_file {\\\"filename\\\": string}: show one file\\n- replace_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#386)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"filename\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"filename\": \"pricing.py\", \"body\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 316 characters to pricing.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 279405626420137, "n_turns": 6}
9
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- view_file {\\\"file\\\": string}: show one file\\n- save_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#325)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"li@x.org\\\", \\\" raj@y.com\\\", \\\"LI@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"li@x.org\\\", \\\"raj@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"save_file\", \"args\": {\"file\": \"contacts.py\", \"text\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n e = e.strip()\\n if not e:\\n continue\\n key = e.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(e)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 387 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 112854060642464, "n_turns": 8}
10
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- put_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#273)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"3h43m\\\") == 13380\\nassert parse_duration(\\\"43m41s\\\") == 2621, parse_duration(\\\"43m41s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"README.md\"}}"}, {"obs": "{\"output\": \"# durations\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"put_file\", \"args\": {\"filename\": \"durations.py\", \"body\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\n\\n A bare number with no unit (e.g. '90') means seconds.\\n \\\"\\\"\\\"\\n text = text.strip().lower()\\n if not text:\\n return 0\\n match = re.fullmatch(r\\\"\\\\d+\\\", text)\\n if match:\\n return int(text)\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 495 characters to durations.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 114659324925138, "n_turns": 9}
11
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- open_file {\\\"file\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#129)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"li@x.org\\\", \\\" kim@y.com\\\", \\\"LI@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"li@x.org\\\", \\\"kim@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"README.md\"}}"}, {"obs": "{\"output\": \"# contacts\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"contacts.py\", \"body\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 415 characters to contacts.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 204860260670935, "n_turns": 9}
12
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pager.py, test_pager.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- read_file {\\\"path\\\": string}: show one file\\n- save_file {\\\"file\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\npager.py (6 lines)\\ntest_pager.py (5 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#593)\\n\\nUsers report that the first page of results is skipped: page 1 shows what should be page 2.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"pager.py\"}}"}, {"obs": "{\"output\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = page * per_page\\n return items[start:start + per_page]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"test_pager.py\"}}"}, {"obs": "{\"output\": \"from pager import paginate\\nitems = list(range(1, 29))\\nassert paginate(items, 1, 4) == items[:4], paginate(items, 1, 4)\\nassert paginate(items, 2, 4) == items[4:8]\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"save_file\", \"args\": {\"file\": \"pager.py\", \"content\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = (page - 1) * per_page\\n return items[start:start + per_page]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 256 characters to pager.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 232702745771551, "n_turns": 7}
13
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- show_file {\\\"path\\\": string}: show one file\\n- save_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#549)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([16, 16, 12, 18, 4, 4], 2)\\nassert got == [16.0, 14.0, 15.0, 11.0, 4.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"save_file\", \"args\": {\"path\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 238881543385386, "n_turns": 7}
14
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- show_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"path\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#374)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"omar@x.org\\\", \\\" kim@y.com\\\", \\\"OMAR@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"omar@x.org\\\", \\\"kim@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**a.osei** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"path\": \"contacts.py\", \"content\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 415 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 229195138049398, "n_turns": 8}
15
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- view_file {\\\"file\\\": string}: show one file\\n- save_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#796)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"omar@x.org\\\", \\\" kim@y.com\\\", \\\"OMAR@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"omar@x.org\\\", \\\"kim@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**a.osei**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**a.osei**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"README.md\"}}"}, {"obs": "{\"output\": \"# contacts\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"save_file\", \"args\": {\"file\": \"contacts.py\", \"text\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n out = []\\n for e in emails:\\n stripped = e.strip()\\n if not stripped:\\n continue\\n key = stripped.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n out.append(stripped)\\n return out\\n\"}}"}, {"obs": "{\"output\": \"Wrote 406 characters to contacts.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 87954571605551, "n_turns": 9}
16
+ {"task_id": "software-repofix-l2", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- put_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (3 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#884)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([16, 10, 2, 4, 8, 18], 2)\\nassert got == [13.0, 6.0, 3.0, 6.0, 13.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "The bug: range should be `len(values) - window + 1`. Fixing.\n\n{\"tool\": \"put_file\", \"args\": {\"filename\": \"smooth.py\", \"content\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 1, "seed": 118058509857077, "n_turns": 7}
17
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pager.py, test_pager.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- show_file {\\\"filename\\\": string}: show one file\\n- replace_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\npager.py (6 lines)\\ntest_pager.py (5 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#528)\\n\\nUsers report that the first page of results is skipped: page 1 shows what should be page 2.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"filename\": \"pager.py\"}}"}, {"obs": "{\"output\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = page * per_page\\n return items[start:start + per_page]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"filename\": \"pager.py\", \"body\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = (page - 1) * per_page\\n return items[start:start + per_page]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 256 characters to pager.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 264295835637357, "n_turns": 6}
18
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- show_file {\\\"path\\\": string}: show one file\\n- write_file {\\\"filename\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#270)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"omar@x.org\\\", \\\" kim@y.com\\\", \\\"OMAR@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"omar@x.org\\\", \\\"kim@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"show_file\", \"args\": {\"path\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**jlu** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"write_file\", \"args\": {\"filename\": \"contacts.py\", \"body\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n key = e.strip().lower()\\n if not key:\\n continue\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(e.strip())\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 383 characters to contacts.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 132690147646051, "n_turns": 8}
19
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- read_file {\\\"path\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#707)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"li@x.org\\\", \\\" kim@y.com\\\", \\\"LI@X.org\\\", \\\"ben@z.net\\\"])\\nassert got == [\\\"li@x.org\\\", \\\"kim@y.com\\\", \\\"ben@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**dkim**: confirmed on main.\\n\\n**pmartin** (maintainer): Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.\\n\\n**dkim**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"read_file\", \"args\": {\"path\": \"README.md\"}}"}, {"obs": "{\"output\": \"# contacts\\n\\nSmall utility module. Python 3.12, no dependencies.\\n\\nMaintainers record edge-case decisions in the issue threads (issue_comments.md).\\n\", \"steps_left\": 6}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"contacts.py\", \"content\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n e = e.strip()\\n if not e:\\n continue\\n key = e.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(e)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 387 characters to contacts.py.\", \"steps_left\": 5}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 4}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 218456112787820, "n_turns": 9}
20
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- view_file {\\\"path\\\": string}: show one file\\n- write_file {\\\"filename\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#505)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"path\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"write_file\", \"args\": {\"filename\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 32636269068733, "n_turns": 6}
21
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_files {}: list the workspace files\\n- view_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#990)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"4h29m\\\") == 16140\\nassert parse_duration(\\\"29m17s\\\") == 1757, parse_duration(\\\"29m17s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"view_file\", \"args\": {\"file\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**jlu**: confirmed on main.\\n\\n**dkim** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**jlu**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"file\": \"durations.py\", \"text\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\n\\n A bare number with no unit (e.g. '90') means seconds.\\n \\\"\\\"\\\"\\n text = text.strip()\\n total = 0\\n saw_unit = False\\n for amount, unit in re.findall(r\\\"(\\\\d+)([a-zA-Z]?)\\\", text):\\n if not unit:\\n total += int(amount)\\n else:\\n total += int(amount) * UNITS[unit.lower()]\\n saw_unit = True\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 501 characters to durations.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 185174993196344, "n_turns": 8}
22
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- put_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#766)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"li@x.org\\\", \\\" raj@y.com\\\", \\\"LI@X.org\\\", \\\"zoe@z.net\\\"])\\nassert got == [\\\"li@x.org\\\", \\\"raj@y.com\\\", \\\"zoe@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"put_file\", \"args\": {\"filename\": \"contacts.py\", \"content\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n trimmed = e.strip()\\n key = trimmed.lower()\\n if key in seen:\\n continue\\n seen.add(key)\\n result.append(trimmed)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 366 characters to contacts.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 276622909260458, "n_turns": 7}
23
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- cat {\\\"filename\\\": string}: show one file\\n- save_file {\\\"path\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#399)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"cat\", \"args\": {\"filename\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([10, 18, 4, 14], 2)\\nassert got == [14.0, 11.0, 9.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"save_file\", \"args\": {\"path\": \"smooth.py\", \"body\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 207812815979247, "n_turns": 7}
24
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- read_file {\\\"file\\\": string}: show one file\\n- save_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\nsmooth.py (5 lines)\\ntest_smooth.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#912)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"file\": \"test_smooth.py\"}}"}, {"obs": "{\"output\": \"from smooth import moving_average\\ngot = moving_average([16, 18, 10, 12], 2)\\nassert got == [17.0, 14.0, 11.0], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"save_file\", \"args\": {\"path\": \"smooth.py\", \"text\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 237685042533026, "n_turns": 7}
25
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_files {}: list the workspace files\\n- read_file {\\\"filename\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#277)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"5h22m\\\") == 19320\\nassert parse_duration(\\\"22m58s\\\") == 1378, parse_duration(\\\"22m58s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"read_file\", \"args\": {\"filename\": \"issue_comments.md\"}}"}, {"obs": "{\"output\": \"**pmartin**: confirmed on main.\\n\\n**a.osei** (maintainer): Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.\\n\\n**pmartin**: thanks, makes sense.\\n\", \"steps_left\": 7}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"durations.py\", \"text\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n text = text.strip().lower()\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms]?)\\\", text):\\n total += int(amount) * UNITS.get(unit, 1)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 320 characters to durations.py.\", \"steps_left\": 6}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 5}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 1.0, "bad_args": 0, "rescued": 0, "seed": 217036859784210, "n_turns": 8}
26
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, smooth.py, test_smooth.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- cat {\\\"file\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#553)\\n\\nThe smoothed series is always one point shorter than it should be.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"file\": \"smooth.py\"}}"}, {"obs": "{\"output\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window)]\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"smooth.py\", \"content\": \"def moving_average(values, window):\\n \\\"\\\"\\\"Average of each full window of `window` consecutive values.\\\"\\\"\\\"\\n if window < 1:\\n raise ValueError(\\\"window must be positive\\\")\\n return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 266 characters to smooth.py.\", \"steps_left\": 9}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 8}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 253627474079435, "n_turns": 5}
27
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- view_file {\\\"path\\\": string}: show one file\\n- replace_file {\\\"filename\\\": string, \\\"content\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#196)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"path\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"view_file\", \"args\": {\"path\": \"test_durations.py\"}}"}, {"obs": "{\"output\": \"from durations import parse_duration\\nassert parse_duration(\\\"1h22m\\\") == 4920\\nassert parse_duration(\\\"22m15s\\\") == 1335, parse_duration(\\\"22m15s\\\")\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"filename\": \"durations.py\", \"content\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 303 characters to durations.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 52302040417987, "n_turns": 7}
28
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pager.py, test_pager.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- show_file {\\\"file\\\": string}: show one file\\n- save_file {\\\"file\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- run_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\npager.py (6 lines)\\ntest_pager.py (5 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#990)\\n\\nUsers report that the first page of results is skipped: page 1 shows what should be page 2.\\n\\nFix the module, not the tests. run_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"pager.py\"}}"}, {"obs": "{\"output\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = page * per_page\\n return items[start:start + per_page]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"test_pager.py\"}}"}, {"obs": "{\"output\": \"from pager import paginate\\nitems = list(range(1, 21))\\nassert paginate(items, 1, 5) == items[:5], paginate(items, 1, 5)\\nassert paginate(items, 2, 5) == items[5:10]\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"save_file\", \"args\": {\"file\": \"pager.py\", \"body\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = (page - 1) * per_page\\n return items[start:start + per_page]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 256 characters to pager.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"run_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 55508123688867, "n_turns": 7}
29
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pricing.py, test_pricing.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- ls {}: list the workspace files\\n- show_file {\\\"file\\\": string}: show one file\\n- replace_file {\\\"file\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- test {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"ls\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\npricing.py (9 lines)\\ntest_pricing.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#162)\\n\\nCustomers whose order total is exactly a tier minimum (for example 500.00) get no discount.\\n\\nFix the module, not the tests. test runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"show_file\", \"args\": {\"file\": \"pricing.py\"}}"}, {"obs": "{\"output\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total > minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"replace_file\", \"args\": {\"file\": \"pricing.py\", \"body\": \"TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)\\n\\n\\ndef discounted_total(total):\\n \\\"\\\"\\\"Apply the best discount tier whose minimum the order total reaches.\\\"\\\"\\\"\\n for minimum, rate in TIERS:\\n if total >= minimum:\\n return round(total * (1 - rate), 2)\\n return round(total, 2)\\n\"}}"}, {"obs": "{\"output\": \"Wrote 316 characters to pricing.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"test\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 170037323196154, "n_turns": 6}
30
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, contacts.py, issue_comments.md, test_contacts.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- dir {}: list the workspace files\\n- open_file {\\\"file\\\": string}: show one file\\n- put_file {\\\"file\\\": string, \\\"body\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ncontacts.py (3 lines)\\nissue_comments.md (5 lines)\\ntest_contacts.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#186)\\n\\nThe contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"contacts.py\"}}"}, {"obs": "{\"output\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n return list(set(e.strip() for e in emails))\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"open_file\", \"args\": {\"file\": \"test_contacts.py\"}}"}, {"obs": "{\"output\": \"from contacts import dedupe_emails\\ngot = dedupe_emails([\\\"ana@x.org\\\", \\\" raj@y.com\\\", \\\"ANA@X.org\\\", \\\"ben@z.net\\\"])\\nassert got == [\\\"ana@x.org\\\", \\\"raj@y.com\\\", \\\"ben@z.net\\\"], got\\nprint(\\\"visible tests passed\\\")\\n\", \"steps_left\": 8}", "reply": "{\"tool\": \"put_file\", \"args\": {\"file\": \"contacts.py\", \"body\": \"def dedupe_emails(emails):\\n \\\"\\\"\\\"Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order.\\\"\\\"\\\"\\n seen = set()\\n result = []\\n for e in emails:\\n stripped = e.strip()\\n key = stripped.lower()\\n if key not in seen:\\n seen.add(key)\\n result.append(stripped)\\n return result\\n\"}}"}, {"obs": "{\"output\": \"Wrote 360 characters to contacts.py.\", \"steps_left\": 7}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 6}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 219670857436492, "n_turns": 7}
31
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, issue_comments.md, pager.py, test_pager.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- files {}: list the workspace files\\n- cat {\\\"path\\\": string}: show one file\\n- put_file {\\\"path\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- check_tests {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"files\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\nissue_comments.md (5 lines)\\npager.py (6 lines)\\ntest_pager.py (5 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"cat\", \"args\": {\"path\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#261)\\n\\nUsers report that the first page of results is skipped: page 1 shows what should be page 2.\\n\\nFix the module, not the tests. check_tests runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"cat\", \"args\": {\"path\": \"pager.py\"}}"}, {"obs": "{\"output\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = page * per_page\\n return items[start:start + per_page]\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"put_file\", \"args\": {\"path\": \"pager.py\", \"text\": \"def paginate(items, page, per_page):\\n \\\"\\\"\\\"Return the items on a 1-indexed page.\\\"\\\"\\\"\\n if page < 1 or per_page < 1:\\n raise ValueError(\\\"page and per_page must be positive\\\")\\n start = (page - 1) * per_page\\n return items[start:start + per_page]\\n\"}}"}, {"obs": "{\"output\": \"Wrote 256 characters to pager.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"check_tests\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 221353534429122, "n_turns": 6}
32
+ {"task_id": "software-repofix-l3", "turns": [{"obs": "{\"output\": \"SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check passes, then submit. Files: ISSUE.md, README.md, durations.py, issue_comments.md, test_durations.py.\\n\\nReply with exactly one JSON object per turn: {\\\"tool\\\": \\\"<name>\\\", \\\"args\\\": {...}}. Tools:\\n- list_dir {}: list the workspace files\\n- view_file {\\\"filename\\\": string}: show one file\\n- save_file {\\\"file\\\": string, \\\"text\\\": string}: replace a file with new content (the whole file)\\n- pytest {}: run the visible tests\\n- submit {}: submit your fix for the release check (ends the episode)\\nYou have 12 tool calls.\", \"steps_left\": 12}", "reply": "{\"tool\": \"list_dir\", \"args\": {}}"}, {"obs": "{\"output\": \"ISSUE.md (5 lines)\\nREADME.md (5 lines)\\ndurations.py (11 lines)\\nissue_comments.md (5 lines)\\ntest_durations.py (4 lines)\", \"steps_left\": 11}", "reply": "{\"tool\": \"view_file\", \"args\": {\"filename\": \"ISSUE.md\"}}"}, {"obs": "{\"output\": \"# Bug report (#849)\\n\\nDurations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.\\n\\nFix the module, not the tests. pytest runs the visible tests; the release check also runs extra tests.\\n\", \"steps_left\": 10}", "reply": "{\"tool\": \"view_file\", \"args\": {\"filename\": \"durations.py\"}}"}, {"obs": "{\"output\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\", \"steps_left\": 9}", "reply": "{\"tool\": \"save_file\", \"args\": {\"file\": \"durations.py\", \"text\": \"import re\\n\\nUNITS = {\\\"h\\\": 3600, \\\"m\\\": 60, \\\"s\\\": 1}\\n\\n\\ndef parse_duration(text):\\n \\\"\\\"\\\"Parse strings like '1h30m', '45m' or '2h5m10s' into seconds.\\\"\\\"\\\"\\n total = 0\\n for amount, unit in re.findall(r\\\"(\\\\d+)([hms])\\\", text.strip().lower()):\\n total += int(amount) * UNITS.get(unit, 0)\\n return total\\n\"}}"}, {"obs": "{\"output\": \"Wrote 303 characters to durations.py.\", \"steps_left\": 8}", "reply": "{\"tool\": \"pytest\", \"args\": {}}"}, {"obs": "{\"output\": \"exit code 0\\nvisible tests passed\", \"steps_left\": 7}", "reply": "{\"tool\": \"submit\", \"args\": {}}"}], "end": "submitted", "reward": 0.0, "bad_args": 0, "rescued": 0, "seed": 107200391959531, "n_turns": 6}
calibration/v4a_r3-software_summary.json ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "Qwen/Qwen3.8-27B:deepinfra",
3
+ "lenient": true,
4
+ "episodes": 32,
5
+ "seconds": 39,
6
+ "usage": {
7
+ "prompt_tokens": 158352,
8
+ "completion_tokens": 7006,
9
+ "calls": 229
10
+ },
11
+ "tasks": {
12
+ "software-repofix-l2": {
13
+ "n": 16,
14
+ "mean": 0.375,
15
+ "solved": 6,
16
+ "rewards": [
17
+ 1.0,
18
+ 0.0,
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 1.0,
26
+ 1.0,
27
+ 1.0,
28
+ 0.0,
29
+ 0.0,
30
+ 1.0,
31
+ 1.0,
32
+ 0.0
33
+ ],
34
+ "ends": {
35
+ "submitted": 16
36
+ },
37
+ "turns": 7.4,
38
+ "rescued_replies": 3
39
+ },
40
+ "software-repofix-l3": {
41
+ "n": 16,
42
+ "mean": 0.25,
43
+ "solved": 4,
44
+ "rewards": [
45
+ 0.0,
46
+ 1.0,
47
+ 1.0,
48
+ 0.0,
49
+ 1.0,
50
+ 0.0,
51
+ 0.0,
52
+ 0.0,
53
+ 1.0,
54
+ 0.0,
55
+ 0.0,
56
+ 0.0,
57
+ 0.0,
58
+ 0.0,
59
+ 0.0,
60
+ 0.0
61
+ ],
62
+ "ends": {
63
+ "submitted": 16
64
+ },
65
+ "turns": 6.9,
66
+ "rescued_replies": 0
67
+ }
68
+ }
69
+ }
source/.dockerignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv
2
+ **/__pycache__
3
+ reports
4
+ tests
5
+ scripts
6
+ dataset
7
+ *.pyc
8
+ .pytest_cache
9
+ proxy_eval
10
+ .git
source/CHANGELOG.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Five Desks changelog
2
+
3
+ Version numbers match arena submissions. Builds that were never submitted are listed under the submission
4
+ they led to.
5
+
6
+ ## v4 (submission `five-desks-v4`, submitted 2026-10-12 17:53 EDT)
7
+
8
+ Candidate B below, unchanged: image `ghcr.io/rca-umb/five-desks@sha256:9508efbc...` (tag `code-cand-b`), request
9
+ `submission_v4.json` (the B candidate with the source link pinned), card `card_code.md`, dataset
10
+ `rca-umb/five-desks-code` at revision `e042d72`. Validated 34/34; run b915134c53bebcc68ce512f9, 68 updates.
11
+ **Result: 5/40** (industrial 2, office 2, software 1), our best; leaderboard total 2 -> 5. Within the noise range
12
+ (reports/lottery-analysis-2026-10-12.md). Training reward 0.19 vs 0.49 calibrated: most episodes ended early, best
13
+ explained by strict reply parsing on code-reasoning turns (reports/v4-arena-gap.md).
14
+
15
+ ## Candidates for v4 (2026-10-11)
16
+
17
+ **A: Five Desks v4 (diligence, refined).** Image `ghcr.io/rca-umb/five-desks:cand-a`
18
+ (`sha256:9609104e...`), request `submission_v4a_candidate.json`, card `card_v4.md`.
19
+ - All-or-nothing rewards; level-3 variants (second caveat / deployment only in the Dockerfile) for industrial,
20
+ science, security and media; office level 1 with a free-slot finder; softer software and math pointers.
21
+ - Per-episode tool and argument names (`diligence/interface.py`); `submit` fixed (finish action).
22
+ - Reasoning hint off; tool-free task dropped; always-equal reward hack closed (test asserts use exact built-in
23
+ comparisons); model code runs as `nobody` when the server is root (falls back if the runtime forbids it).
24
+ - Calibration with lenient parsing (matches the arena: industrial-l2 0.83 vs 0.80): picks between 0.25 and 0.58.
25
+ - 206 unit tests, 5,204 fuzz calls, 575-episode replay on the anonymously pulled image: 0 failures.
26
+
27
+ **B: Five Desks Code (agentic coding).** Image `ghcr.io/rca-umb/five-desks:code-cand-b` (`sha256:9508efbc...`),
28
+ request `submission_v4b_candidate.json`, card `card_code.md`, package `codedesk/`.
29
+ - Bug fixing in 15 pinned open-source libraries across the eight domains: 525 single-token mutants that the
30
+ libraries' own tests catch (built and validated in containers: `codedesk/build/`), levels 1 (CI failure) and 2
31
+ (user report, catching tests removed); media production with ffmpeg/ImageMagick/Pillow.
32
+ - Grading copies only library sources into a clean original project and runs the original tests; symlinks score 0;
33
+ policy commands run as `nobody`; the catalog is root-only and not published.
34
+ - simple-pid dropped (timing-dependent tests), semver dropped (needs pytest-cov); fluids is the industrial library.
35
+ - Calibration: 9 picks between 0.31 and 0.69 (16 episodes each); about a third of losses are malformed actions.
36
+ - 24 in-image tests on the anonymously pulled amd64 image (oracle/untouched for all 18 task ids, cheat and hostile
37
+ calls), example episodes for all task ids: 0 failures.
38
+
39
+ ## v3 (submission `five-desks-v3`, submitted 2026-10-11 14:06 EDT)
40
+
41
+ - Validated 14:07 (31/31 checks); run `ecbdaf68dc5cee84b21c34de`.
42
+ - Result: 172 GRPO steps, private score 1/40 (office 1). Train reward rose 0.51 -> 0.69 (math problems
43
+ 0.22 -> 0.72, science 0.78 -> 0.95): more in-task learning than v2, lower private score.
44
+ - The always-equal reward hack was confirmed on the v3 code afterwards (2 of 5 software bugs scored 1.0 with it).
45
+
46
+ - Same image as v2 (`ghcr.io/rca-umb/five-desks@sha256:d872c9fd...`), no rebuild.
47
+ - 8 training tasks (`scripts/selection_v3.py`): v2's eight diligence `-l2` tasks, without `math-reasoning-l1`,
48
+ whose train reward fell 0.58 -> 0.08 in the v2 run. Eight tasks also matches the list size of most 4-5/40 runs
49
+ on the leaderboard (weak pattern, n = 28).
50
+ - Dataset `rca-umb/five-desks` at `453b36d72ce3fbf2426c3cb116af5221b95a5adb` (README from `card_v3.md`).
51
+ - Far-transfer check added after submitting: burtenshaw's SQL Investigation Lab, base 0.68 vs reasoning
52
+ instruction 0.74 (100 episodes each, ~0.9 SE; reports/transfer/far-sql-NOTE.md).
53
+ - Known residual reward hack, to fix in the next build: a software fix can return an object whose `__eq__` is
54
+ always true and pass the `==` asserts in the release tests. Not seen in the v2 run (software reward 0.53 -> 0.60).
55
+
56
+ ## v2 (submission `five-desks-v2`, submitted 2026-10-10 14:06 EDT)
57
+
58
+ - Result: run `6b3030829fa1125c96bad42a`, 207 GRPO steps, private score 2/40 (industrial 1, office 1), the same
59
+ as v1 domain by domain. Details in `reports/run-v2/RESULT.md`.
60
+ - Image `ghcr.io/rca-umb/five-desks:v2`, index `sha256:d872c9fdc2b10bf120bfbe778896f09393c7313ea8627925c7fea4a750f9cac6`
61
+ (linux/amd64 manifest `sha256:a7436a8d67079fbf94eacd7a95590cf08342909a8bfa83a3c4431950fe08527f`).
62
+ - Dataset `rca-umb/five-desks` at `ae9e249ed5956462cf1dcb96eada451bdbefbb37` (README from `card_v2.md`, built by
63
+ `scripts/build_dataset_v2.py`).
64
+ - Far-transfer check before submitting (reports/transfer/far-*): the reasoning instruction gave no gain on
65
+ MetaHarness (0.175 -> 0.143, 96 eps/arm) or Verified Compute Lab (0.031 -> 0.019, 54/arm). Submitted anyway; the
66
+ diligence tasks are the core and the hint is on half the resets. Board post #123.
67
+ - 9 training tasks (`scripts/selection_v2.py`): the eight no-hint diligence tasks (`-l2`) and `math-reasoning-l1`.
68
+
69
+ How it got here (internal builds, none submitted):
70
+
71
+ 1. **Draft "v2" (2026-10-09 evening).** Replaced v1's desk arithmetic with eight caveat ("diligence") families,
72
+ one per domain, after the stand-in test showed habit failures (stopping early, head math, format slips).
73
+ Pushed as `:v2` (`sha256:2b0c8b91...`, now untagged) with a card; never submitted. Calibration in
74
+ `reports/calibration-v2-draft/`, draft request in `reports/submission_v2_unsubmitted_draft.json`.
75
+ 2. **Overnight hardening.** Closed reward hacks found by adversarial tests: `sys.exit` at import in the
76
+ software tests, path traversal, recursive SQL, orphaned processes, unbounded output, oversized file reads.
77
+ Fuzzer: 3,045 hostile calls, 0 failures. Load test: 1,980 episodes, 0 errors.
78
+ 3. **Reasoning scaffold (built as "v3", pushed as `:v3` `sha256:9c81836c...`).** The near-transfer proxy showed
79
+ that a "reason in metadata" instruction raised the stand-in score 0.56 -> 0.70, while diligence hints and
80
+ demonstrations did nothing. Added the hint on ~50% of resets and the tool-free `math-reasoning` family;
81
+ recalibrated (`reports/calibration-v2/`).
82
+ 4. **Renamed to v2 (2026-10-10).** Same files as the `:v3` build except the name/version labels; re-pushed as
83
+ `:v2`. Anonymous pull, `openenv validate` 6/6, schema check and 450-episode replay all pass
84
+ (`reports/replay-v2-anonymous-pull.json`). The `:v3` tag still exists on GHCR (deleting a tag needs the
85
+ `delete:packages` scope); it is not referenced anywhere.
86
+
87
+ ## v1 (submission `five-desks-v1`, 2026-10-09)
88
+
89
+ - Image index `sha256:dbb3cf982179f1a3b53642e6bbe116510d8a83e6b4c9664aa117775bbdaba50c`; dataset revision
90
+ `1138ff662305c8765223d3ddfdeeeaa87302db43`; 18 tasks of desk arithmetic in finance, science, math, security
91
+ and media.
92
+ - Result: 265 GRPO steps, train reward flat at ~0.5 with ~80% mixed groups; private score 2/40 (industrial 1,
93
+ office 1) against 4/40 untrained.
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/diligence/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Five Desks v2: diligence tasks across eight domains with one generic tool-call action."""
source/diligence/base.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Building blocks for tasks: tools with declared arguments, and the task base class."""
2
+
3
+ import math
4
+ import random
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Callable
7
+
8
+ from . import sandbox
9
+
10
+ READ_CHARS = 1200 # read_file shows at most this much of a file
11
+ TYPE_NAMES = {str: "string", int: "integer", float: "number", dict: "object", list: "array"}
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) # argument name -> expected type
20
+ optional: tuple[str, ...] = ()
21
+ final: bool = False # calling it ends the episode; fn then returns the reward
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 not in args:
36
+ continue
37
+ v = args[k]
38
+ ok = isinstance(v, t) and not isinstance(v, bool) if t in (int, float) else isinstance(v, t)
39
+ if t is float and isinstance(v, int) and not isinstance(v, bool):
40
+ ok = True
41
+ if not ok:
42
+ return f"Argument {k!r} of {self.name} must be a {TYPE_NAMES[t]}."
43
+ return None
44
+
45
+
46
+ class Task:
47
+ """One generated instance. Subclasses implement setup(), tools(), brief and grade()."""
48
+
49
+ family = ""
50
+ domain = ""
51
+ max_steps = 12
52
+ levels = (1, 2) # 1 points at the caveat, 2 does not, 3 (where offered) adds a second one or hides it further
53
+
54
+ def __init__(self, rng: random.Random, level: int):
55
+ self.level = level
56
+ self.files: dict[str, str] = {}
57
+ for attempt in range(200): # generators assert their own invariants; redraw until they hold
58
+ self.rng = random.Random(f"{rng.random()}:{attempt}")
59
+ self.files = {}
60
+ try:
61
+ self.setup()
62
+ return
63
+ except AssertionError:
64
+ continue
65
+ raise RuntimeError(f"could not generate {self.family}")
66
+
67
+ # -- to implement --------------------------------------------------------------------------------
68
+ def setup(self):
69
+ raise NotImplementedError
70
+
71
+ def brief(self) -> str:
72
+ raise NotImplementedError
73
+
74
+ def tools(self) -> list[Tool]:
75
+ raise NotImplementedError
76
+
77
+ def grade(self, args: dict) -> float:
78
+ raise NotImplementedError
79
+
80
+ def oracle(self) -> list[dict]:
81
+ """A scripted solution as a list of {"tool", "args"} actions; it must score 1."""
82
+ raise NotImplementedError
83
+
84
+ def naive(self) -> list[dict]:
85
+ """A plausible solution that misses the task's caveat; it must score below 1."""
86
+ raise NotImplementedError
87
+
88
+ # -- shared tools --------------------------------------------------------------------------------
89
+ def files_tools(self) -> list[Tool]:
90
+ return [
91
+ Tool("list_files", "list the workspace files", lambda a: "\n".join(
92
+ f"{n} ({len(b.splitlines())} lines)" for n, b in sorted(self.files.items()))),
93
+ Tool("read_file", "show one file", self._read, {"path": str}),
94
+ ]
95
+
96
+ def python_tool(self) -> Tool:
97
+ return Tool("python", "run Python 3 code (standard library only) in the workspace directory, where "
98
+ "the files above are available; print what you need", self._python, {"code": str})
99
+
100
+ def _read(self, a):
101
+ name = a["path"].strip().lstrip("./")
102
+ if name not in self.files:
103
+ return f"No file named {a['path']!r}. Files: {', '.join(sorted(self.files))}."
104
+ body = self.files[name]
105
+ if len(body) <= READ_CHARS:
106
+ return body
107
+ # large data files would eat the episode's token budget; show the start and point to python
108
+ shown = body[:READ_CHARS].rsplit("\n", 1)[0]
109
+ return (shown + f"\n... [showing {shown.count(chr(10)) + 1} of {body.count(chr(10)) + 1} lines; "
110
+ "use python to work with the whole file]")
111
+
112
+ def _python(self, a):
113
+ if not a["code"].strip():
114
+ return "code is empty"
115
+ code, out = sandbox.run({**self.files, "_main.py": a["code"]}, "_main.py")
116
+ return f"exit code {code}\n{out}" if code else (out or "(no output)")
117
+
118
+
119
+ def close(value: Any, want: float, rel: float = 0.01, abs_tol: float = 0.0) -> bool:
120
+ try:
121
+ if isinstance(value, bool):
122
+ return False
123
+ num = float(str(value).replace(",", "").replace("$", "").strip()) if isinstance(value, str) else float(value)
124
+ except (TypeError, ValueError):
125
+ return False
126
+ return math.isfinite(num) and abs(num - want) <= max(abs_tol, rel * abs(want))
127
+
128
+
129
+ def same_int(value: Any, want: int) -> bool:
130
+ if isinstance(value, bool):
131
+ return False
132
+ if isinstance(value, float) and value.is_integer():
133
+ value = int(value)
134
+ if isinstance(value, str) and value.strip().lstrip("-").isdigit():
135
+ value = int(value.strip())
136
+ return isinstance(value, int) and value == want
137
+
138
+
139
+ def lower_keys(obj: Any) -> dict:
140
+ return {str(k).strip().lower(): v for k, v in obj.items()} if isinstance(obj, dict) else {}
141
+
142
+
143
+ def template(answer: dict) -> str:
144
+ """A JSON-shaped answer template, e.g. {"total_usd": <number>, "top_customer": "<text>"}."""
145
+ def kind(v):
146
+ if isinstance(v, str):
147
+ return '"<text>"'
148
+ return "<integer>" if isinstance(v, int) else "<number>"
149
+ return "{" + ", ".join(f'"{k}": {kind(v)}' for k, v in answer.items()) + "}"
source/diligence/environment.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Five Desks OpenEnv environment."""
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
+ TASK_IDS = [f"{family}-l{level}" for family, cls in FAMILIES.items() for level in cls.levels]
16
+ # Positive control (the collapse test): the same tasks and briefs, but the reward ignores the answer and only pays
17
+ # for ending early (1.0 when the first call ends the episode, falling linearly to 0 when the budget runs out).
18
+ CONTROL_PREFIX = "early-"
19
+ CONTROL_IDS = [CONTROL_PREFIX + t for t in TASK_IDS]
20
+ MAX_OUTPUT_CHARS = 6000
21
+ # v2 suggested thinking inside the action's metadata field on half of the resets. The habit did not transfer to
22
+ # other environments and faded during the v2 run, so the suggestion is off by default (reset(tip=True) still shows it).
23
+ TIP_RATE = 0.0
24
+ TIP = ('Think before each action: put your working in the action\'s metadata, e.g. {"tool": "<name>", "args": '
25
+ '{...}, "metadata": {"reasoning": "<what you know, what is missing, and a check of every condition>"}}.')
26
+
27
+
28
+ def build(task_id: str, seed: int):
29
+ task_id = task_id.removeprefix(CONTROL_PREFIX)
30
+ family, _, level = task_id.rpartition("-l")
31
+ if family not in FAMILIES or level not in {str(lv) for lv in FAMILIES[family].levels}:
32
+ raise ValueError(f"unknown task_id {task_id!r}; known ids: {', '.join(TASK_IDS + CONTROL_IDS)}")
33
+ return FAMILIES[family](random.Random(f"{task_id}:{seed}"), int(level))
34
+
35
+
36
+ def describe(task, tip: bool = False, interface: Optional[Interface] = None) -> str:
37
+ tools = interface.tools if interface else task.tools()
38
+ brief = interface.text(task.brief()) if interface else task.brief()
39
+ lines = [f'- {t.name} {t.signature()}: {t.help}' + (" (ends the episode)" if t.final else "") for t in tools]
40
+ return (f"{brief}\n\nReply with exactly one JSON object per turn: "
41
+ f'{{"tool": "<name>", "args": {{...}}}}. Tools:\n' + "\n".join(lines)
42
+ + f"\nYou have {task.max_steps} tool calls." + (f"\n{TIP}" if tip else ""))
43
+
44
+
45
+ class DiligenceEnvironment(Environment):
46
+ SUPPORTS_CONCURRENT_SESSIONS = True
47
+
48
+ def __init__(self):
49
+ self._state = State(episode_id=str(uuid4()), step_count=0)
50
+ self._task = None
51
+ self._tools = {}
52
+ self._interface = None
53
+ self._steps_left = 0
54
+ self._control = False
55
+ self._done = True
56
+
57
+ def reset(self, seed: Optional[int] = None, episode_id: Optional[str] = None,
58
+ task_id: Optional[str] = None, tip: Optional[bool] = None, canonical_names: bool = False,
59
+ **kwargs: Any) -> ToolObservation:
60
+ task_id = task_id or TASK_IDS[0]
61
+ # Unseeded resets draw a fresh instance, so parallel rollouts see different data.
62
+ seed = seed if seed is not None else secrets.randbits(48)
63
+ self._task = build(task_id, seed)
64
+ if tip is None:
65
+ tip = random.Random(f"tip:{task_id}:{seed}").random() < TIP_RATE
66
+ # each episode gets its own tool and argument names (canonical_names=True keeps the originals, for tests)
67
+ self._interface = None if canonical_names else Interface(self._task.tools(), random.Random(f"names:{task_id}:{seed}"))
68
+ self._tools = {t.name: t for t in (self._interface.tools if self._interface else self._task.tools())}
69
+ self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
70
+ self._steps_left = self._task.max_steps
71
+ self._control = task_id.startswith(CONTROL_PREFIX)
72
+ self._done = False
73
+ return ToolObservation(output=describe(self._task, bool(tip), self._interface), steps_left=self._steps_left, done=False,
74
+ reward=0.0)
75
+
76
+ def step(self, action: ToolAction, timeout_s: Optional[float] = None, **kwargs: Any) -> ToolObservation: # type: ignore[override]
77
+ if self._task is None or self._done:
78
+ return ToolObservation(output="Episode is over. Call reset.", steps_left=0, done=True, reward=0.0)
79
+ self._state.step_count += 1
80
+ self._steps_left -= 1
81
+ tool = self._tools.get(action.tool.strip())
82
+ if tool is None and action.tool.strip() == "submit":
83
+ # the generic finish action: end without an answer
84
+ return self._end("Ended without an answer.", 0.0)
85
+ if tool is not None and tool.final and tool.name == "submit" and not action.args:
86
+ # the finish action: score whatever has been done so far
87
+ return self._end("Submitted.", 0.0 if self._control else float(tool.fn({})))
88
+ if tool is None:
89
+ output = f"Unknown tool {action.tool!r}. Tools: {', '.join(self._tools)}."
90
+ elif (error := tool.check(action.args)) is not None:
91
+ output = error
92
+ elif tool.final:
93
+ return self._end("Submitted.", 0.0 if self._control else float(tool.fn(action.args)))
94
+ else:
95
+ output = tool.fn(action.args)
96
+ if self._interface:
97
+ output = self._interface.text(output)
98
+ if len(output) > MAX_OUTPUT_CHARS:
99
+ output = output[:MAX_OUTPUT_CHARS] + "\n... [output truncated]"
100
+ if self._steps_left <= 0:
101
+ self._done = True
102
+ return ToolObservation(output=output + "\nNo tool calls left; the episode is over.",
103
+ steps_left=0, done=True, reward=0.0)
104
+ return ToolObservation(output=output, steps_left=self._steps_left, done=False, reward=0.0)
105
+
106
+ def _end(self, output: str, reward: float) -> ToolObservation:
107
+ self._done = True
108
+ if self._control: # the collapse test pays only for how early the episode ended
109
+ reward = (self._steps_left + 1) / self._task.max_steps
110
+ return ToolObservation(output=output, steps_left=self._steps_left, done=True,
111
+ reward=round(min(1.0, max(0.0, reward)), 4))
112
+
113
+ @property
114
+ def state(self) -> State:
115
+ return self._state
source/diligence/families/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .finance import Receivables
2
+ from .industrial import Telemetry
3
+ from .math_tasks import Problems
4
+ from .media import CopyEdit
5
+ from .office import Scheduling
6
+ from .reasoning import Reasoning
7
+ from .science import LabAnalysis
8
+ from .security import VulnHunt
9
+ from .software import RepoFix
10
+
11
+ FAMILIES = {cls.family: cls for cls in
12
+ [RepoFix, Telemetry, LabAnalysis, Scheduling, Receivables, Problems, VulnHunt, CopyEdit, Reasoning]}
source/diligence/families/finance.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Finance: answer a receivables question with SQL. Caveat: credit notes / refunds live in their own table."""
2
+
3
+ import datetime as dt
4
+ import sqlite3
5
+ import time
6
+
7
+ from ..base import Task, Tool, close, lower_keys, same_int, template
8
+
9
+ CUSTOMERS = ["Arcturus Labs", "Birchwood Foods", "Cobalt Freight", "Delta Optics", "Evergreen Clinics",
10
+ "Fjord Marine", "Granite Legal", "Helios Solar"]
11
+ FX = {"USD": 1.0, "EUR": 1.08, "GBP": 1.27, "CAD": 0.73}
12
+ AS_OF = dt.date(2026, 9, 30)
13
+ QUERY_SECONDS = 5
14
+ READ_PRAGMAS = {"table_info", "table_xinfo", "table_list", "index_list", "index_info", "foreign_key_list"}
15
+
16
+
17
+ def _authorize(action, arg1, arg2, db_name, source):
18
+ if action == sqlite3.SQLITE_ATTACH or action == sqlite3.SQLITE_DETACH:
19
+ return sqlite3.SQLITE_DENY
20
+ if action == sqlite3.SQLITE_PRAGMA and (arg1 or "").lower() not in READ_PRAGMAS:
21
+ return sqlite3.SQLITE_DENY
22
+ return sqlite3.SQLITE_OK
23
+
24
+
25
+ class Receivables(Task):
26
+ family = "finance-receivables"
27
+ domain = "finance-economics"
28
+ max_steps = 12
29
+
30
+ def setup(self):
31
+ r = self.rng
32
+ self.variant = r.randrange(2)
33
+ self.invoices, self.payments, self.credits, self.refunds = [], [], [], []
34
+ inv_id, pay_id = 1000, 1
35
+ for _ in range(r.randint(40, 60)):
36
+ cust = r.randint(1, len(CUSTOMERS))
37
+ issued = AS_OF - dt.timedelta(days=r.randint(5, 200))
38
+ due = issued + dt.timedelta(days=r.choice([30, 45, 60]))
39
+ amount = round(r.uniform(400, 25000), 2)
40
+ cur = r.choice(list(FX))
41
+ status = r.choices(["open", "void"], [0.92, 0.08])[0]
42
+ inv_id += 1
43
+ self.invoices.append((inv_id, cust, issued.isoformat(), due.isoformat(), amount, cur, status))
44
+ if status == "void":
45
+ continue
46
+ paid = r.choice([0, 0, amount, round(amount * r.uniform(0.2, 0.8), 2)])
47
+ if paid:
48
+ when = issued + dt.timedelta(days=r.randint(3, 120))
49
+ if when <= AS_OF:
50
+ self.payments.append((pay_id, inv_id, when.isoformat(), paid))
51
+ pay_id += 1
52
+ if r.random() < 0.15: # an accidental duplicate a day or two later
53
+ dup = (pay_id, inv_id, (when + dt.timedelta(days=r.randint(1, 2))).isoformat(), paid)
54
+ self.payments.append(dup)
55
+ pay_id += 1
56
+ if r.random() < 0.5:
57
+ self.refunds.append((len(self.refunds) + 1, dup[0], (when + dt.timedelta(days=9)).isoformat(), paid))
58
+ if r.random() < 0.18:
59
+ self.credits.append((len(self.credits) + 1, inv_id, (issued + dt.timedelta(days=20)).isoformat(),
60
+ round(amount * r.choice([0.1, 0.25, 0.5]), 2)))
61
+ self.answer, naive = self._truth(with_caveat=True), self._truth(with_caveat=False)
62
+ assert any(not self._eq(self.answer[k], naive[k]) for k in self.answer)
63
+ self.naive_answer = naive
64
+
65
+ @staticmethod
66
+ def _eq(a, b):
67
+ return a == b if isinstance(a, (str, int)) else abs(a - b) < 1.0
68
+
69
+ def _truth(self, with_caveat):
70
+ paid = {}
71
+ for _, inv, _, amt in self.payments:
72
+ paid[inv] = paid.get(inv, 0) + amt
73
+ if with_caveat:
74
+ for _, inv, _, amt in self.credits:
75
+ paid[inv] = paid.get(inv, 0) + amt
76
+ cur = {i[0]: i[5] for i in self.invoices}
77
+ if self.variant == 0:
78
+ per_cust = {}
79
+ for inv, cust, _, due, amt, c, status in self.invoices:
80
+ bal = amt - paid.get(inv, 0)
81
+ if status == "open" and (AS_OF - dt.date.fromisoformat(due)).days > 60 and bal > 0.005:
82
+ per_cust[cust] = per_cust.get(cust, 0) + bal * FX[c]
83
+ assert len(per_cust) >= 2
84
+ ranked = sorted(per_cust.values())
85
+ assert ranked[-1] - ranked[-2] > 50
86
+ return {"total_usd": round(sum(per_cust.values()), 2),
87
+ "top_customer": CUSTOMERS[max(per_cust, key=per_cust.get) - 1]}
88
+ refunded = {p for _, p, _, _ in self.refunds} if with_caveat else set()
89
+ groups = {}
90
+ for pid, inv, when, amt in self.payments:
91
+ groups.setdefault((inv, amt), []).append((dt.date.fromisoformat(when), pid))
92
+ dups, total = 0, 0.0
93
+ for (inv, amt), rows in groups.items():
94
+ rows.sort()
95
+ for (d0, _), (d1, pid) in zip(rows, rows[1:]):
96
+ if (d1 - d0).days <= 3 and pid not in refunded:
97
+ dups += 1
98
+ total += amt * FX[cur[inv]]
99
+ assert dups >= 1
100
+ return {"duplicate_count": dups, "duplicate_total_usd": round(total, 2)}
101
+
102
+ def _db(self):
103
+ db = sqlite3.connect(":memory:")
104
+ db.executescript("""
105
+ CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
106
+ CREATE TABLE invoices (id INTEGER PRIMARY KEY, customer_id INTEGER, issued TEXT, due TEXT,
107
+ amount REAL, currency TEXT, status TEXT);
108
+ CREATE TABLE payments (id INTEGER PRIMARY KEY, invoice_id INTEGER, paid_on TEXT, amount REAL);
109
+ CREATE TABLE credit_notes (id INTEGER PRIMARY KEY, invoice_id INTEGER, issued TEXT, amount REAL);
110
+ CREATE TABLE refunds (id INTEGER PRIMARY KEY, payment_id INTEGER, refunded_on TEXT, amount REAL);
111
+ CREATE TABLE fx_rates (currency TEXT PRIMARY KEY, usd_per_unit REAL);
112
+ """)
113
+ db.executemany("INSERT INTO customers VALUES (?,?)", list(enumerate(CUSTOMERS, 1)))
114
+ db.executemany("INSERT INTO invoices VALUES (?,?,?,?,?,?,?)", self.invoices)
115
+ db.executemany("INSERT INTO payments VALUES (?,?,?,?)", self.payments)
116
+ db.executemany("INSERT INTO credit_notes VALUES (?,?,?,?)", self.credits)
117
+ db.executemany("INSERT INTO refunds VALUES (?,?,?,?)", self.refunds)
118
+ db.executemany("INSERT INTO fx_rates VALUES (?,?)", FX.items())
119
+ db.execute("PRAGMA query_only = ON")
120
+ # keep model queries small and short: no attaching files, no huge blobs, no endless recursive queries
121
+ db.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, 1_000_000)
122
+ db.set_authorizer(_authorize)
123
+ deadline = time.monotonic() + QUERY_SECONDS
124
+ db.set_progress_handler(lambda: int(time.monotonic() > deadline), 10_000)
125
+ return db
126
+
127
+ def brief(self):
128
+ if self.variant == 0:
129
+ q = ("As of 2026-09-30, what is the total outstanding balance in USD of open (not void) invoices more than "
130
+ "60 days past their due date, and which customer owes the most of it?")
131
+ q += (" Outstanding = invoice amount minus payments and credit notes." if self.level == 1
132
+ else " Outstanding means what the customer still owes on the invoice.")
133
+ else:
134
+ q = ("Find duplicate payments: a payment is a duplicate when the same invoice already received a payment "
135
+ "of exactly the same amount within the previous 3 days. How many duplicates are still unresolved, "
136
+ "and what is their total in USD?")
137
+ if self.level == 1:
138
+ q += " A duplicate that was refunded is resolved (see the refunds table)."
139
+ return (f"FINANCE. Accounts receivable database (SQLite, read-only) with tables customers, invoices, "
140
+ f"payments, credit_notes, refunds and fx_rates. {q} Convert currencies with fx_rates. Submit "
141
+ f"{{\"answer\": {template(self.answer)}}}; amounts are checked to within $1.00.")
142
+
143
+ def tools(self):
144
+ return [Tool("sql", "run one read-only SQLite statement; at most 60 rows are shown", self._sql, {"query": str}),
145
+ Tool("submit", "submit the answer", self.grade, {"answer": dict}, final=True)]
146
+
147
+ def _sql(self, a):
148
+ db = self._db()
149
+ try:
150
+ cur = db.execute(a["query"])
151
+ cols = [d[0] for d in cur.description or []]
152
+ rows = cur.fetchmany(60)
153
+ more = 0
154
+ try:
155
+ while batch := cur.fetchmany(1000): # count the rest without holding it all
156
+ more += len(batch)
157
+ except sqlite3.OperationalError: # stopped by the time limit while counting
158
+ more = "many"
159
+ except (sqlite3.Error, sqlite3.Warning) as exc:
160
+ if str(exc) == "interrupted":
161
+ return f"SQL error: the query ran longer than {QUERY_SECONDS} s and was stopped"
162
+ return f"SQL error: {exc}"
163
+ finally:
164
+ db.close()
165
+ text = "\t".join(cols) + "\n" + "\n".join("\t".join(map(str, row)) for row in rows)
166
+ return text + (f"\n... {more} more rows" if more else "")
167
+
168
+ def grade(self, a):
169
+ got = lower_keys(a.get("answer", {}))
170
+ scores = []
171
+ for key, want in self.answer.items():
172
+ val = got.get(key)
173
+ if isinstance(want, str):
174
+ scores.append(isinstance(val, str) and val.strip().lower() == want.lower())
175
+ elif isinstance(want, int):
176
+ scores.append(same_int(val, want))
177
+ else:
178
+ scores.append(close(val, want, rel=0, abs_tol=1.0))
179
+ return float(all(scores))
180
+
181
+ def oracle(self):
182
+ return [{"tool": "sql", "args": {"query": "SELECT name FROM sqlite_master WHERE type = 'table'"}},
183
+ {"tool": "submit", "args": {"answer": self.answer}}]
184
+
185
+ def naive(self):
186
+ return [{"tool": "submit", "args": {"answer": self.naive_answer}}]
source/diligence/families/industrial.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Industrial: find the first pump to start cavitating from telemetry files.
2
+
3
+ Caveat: the maintenance log marks one pump's sensor readings as invalid for a window, and that pump shows a
4
+ qualifying (but invalid) run earlier than the real one. At level 3 the log also invalidates the first minutes of
5
+ the real run, so cavitation starts later than the raw data suggests.
6
+ """
7
+
8
+ from ..base import Task, Tool, lower_keys, same_int
9
+
10
+ MINUTES = 180
11
+ HEADER = "minute,flow_m3h,discharge_bar,vibration_mms,bearing_temp_c"
12
+
13
+
14
+ class Telemetry(Task):
15
+ family = "industrial-telemetry"
16
+ domain = "industrial-physical-systems"
17
+ max_steps = 12
18
+ levels = (1, 2, 3)
19
+
20
+ def setup(self):
21
+ r = self.rng
22
+ self.vib_limit = r.choice([7.1, 7.5, 8.0])
23
+ self.p_limit = r.choice([3.2, 3.5, 3.8])
24
+ self.run_len = r.choice([3, 4])
25
+ ids = [f"P-{n}" for n in r.sample(range(101, 140), 4)]
26
+ fault, decoy, bearing, normal = ids
27
+ data = {}
28
+ for aid in ids:
29
+ data[aid] = [[t, round(r.uniform(118, 126), 1), round(r.uniform(4.3, 4.9), 2),
30
+ round(r.uniform(2.0, 4.5), 1), round(r.uniform(52, 58), 1)] for t in range(MINUTES)]
31
+
32
+ def burst(rows, start, length):
33
+ for t in range(start, start + length):
34
+ rows[t][3] = round(self.vib_limit + r.uniform(0.3, 3), 1)
35
+ rows[t][2] = round(self.p_limit - r.uniform(0.1, 0.8), 2)
36
+ rows[t][1] = round(rows[t][1] - r.uniform(10, 25), 1)
37
+
38
+ start = r.randint(70, MINUTES - 30)
39
+ near = r.randint(10, start - 15)
40
+ burst(data[fault], near, self.run_len - 1) # one reading too short to count
41
+ extra = r.randint(2, 8)
42
+ burst(data[fault], start, self.run_len + extra)
43
+ self.raw_start = start
44
+ self.invalid = []
45
+ if self.level == 3: # the fault pump's vibration sensor was out of service over the start of its run
46
+ cut = r.randint(1, extra)
47
+ self.invalid.append((fault, start - r.randint(3, 10), start + cut))
48
+ start += cut
49
+ self.fault = (fault, start)
50
+ # the decoy's sensor was faulty in a window that contains an earlier qualifying run
51
+ bad_lo = r.randint(5, start - 40)
52
+ bad_hi = bad_lo + r.randint(25, 35)
53
+ dstart = r.randint(bad_lo + 2, bad_hi - self.run_len - 2)
54
+ burst(data[decoy], dstart, self.run_len + r.randint(1, 4))
55
+ self.decoy = (decoy, dstart)
56
+ s = r.randint(20, MINUTES - 40)
57
+ for t in range(s, s + 12):
58
+ data[bearing][t][3] = round(self.vib_limit + r.uniform(0.5, 3), 1)
59
+ for t in r.sample(range(MINUTES), 5): # isolated noise
60
+ data[normal][t][3] = round(self.vib_limit + r.uniform(0.5, 3), 1)
61
+ data[normal][t][2] = round(self.p_limit - r.uniform(0.1, 0.5), 2)
62
+ self.invalid.append((decoy, bad_lo, bad_hi))
63
+ for aid in ids:
64
+ first = self._first_run(data[aid], aid)
65
+ assert first == {fault: start, decoy: None}.get(aid), (aid, first)
66
+ assert self._first_run(data[decoy], decoy, ignore_log=True) == dstart < start
67
+
68
+ order = ids[:]
69
+ r.shuffle(order)
70
+ for aid in order:
71
+ self.files[f"telemetry/{aid}.csv"] = HEADER + "\n" + "\n".join(",".join(map(str, row)) for row in data[aid])
72
+ self.files["manual.md"] = (
73
+ f"# Cooling-water pumps: operating manual\n\n## 7.3 Cavitation\nA pump is cavitating when vibration "
74
+ f"exceeds {self.vib_limit} mm/s while discharge pressure is below {self.p_limit} bar, for at least "
75
+ f"{self.run_len} consecutive one-minute readings. Isolated readings are sensor noise. Cavitation starts at "
76
+ f"the first minute of the first such run. High vibration with normal pressure indicates bearing wear, not "
77
+ f"cavitation.\n\n## 7.4 Data validity\nReadings recorded while an instrument is out of service are not "
78
+ f"valid and must be ignored. Instrument work is recorded in maintenance_log.md.\n")
79
+ others = [a for a in ids if a != decoy]
80
+ log = [(0, "shift handover, all pumps running."),
81
+ (bad_lo, f"{decoy} pressure transmitter taken out of service for calibration (readings invalid until it "
82
+ "is back)."),
83
+ (bad_lo + 3, f"{r.choice([a for a in others if a != fault])} strainer inspected, no fault."),
84
+ (bad_hi, f"{decoy} pressure transmitter back in service.")]
85
+ if self.level == 3:
86
+ _, lo, hi = self.invalid[0]
87
+ log += [(lo, f"{fault} vibration sensor swapped (readings invalid until the new one is commissioned)."),
88
+ (hi, f"{fault} new vibration sensor commissioned.")]
89
+ self.files["maintenance_log.md"] = "# Maintenance log (this shift)\n\n" + "".join(
90
+ f"- minute {t}: {text}\n" for t, text in sorted(log, key=lambda e: e[0]))
91
+
92
+ def _first_run(self, rows, aid, ignore_log=False):
93
+ count = 0
94
+ for t, _, p, v, _ in rows:
95
+ invalid = not ignore_log and any(a == aid and lo <= t < hi for a, lo, hi in self.invalid)
96
+ count = count + 1 if (v > self.vib_limit and p < self.p_limit and not invalid) else 0
97
+ if count == self.run_len:
98
+ return t - self.run_len + 1
99
+ return None
100
+
101
+ def brief(self):
102
+ hint = " Check the maintenance log for instrument work." if self.level == 1 else ""
103
+ return ("INDUSTRIAL. Control room, cooling-water loop. An operator heard noise from the pumps. Using the "
104
+ "manual and the minute-by-minute telemetry (minutes 0-179), find the first pump to start cavitating "
105
+ f"this shift and the minute cavitation began.{hint} Submit "
106
+ '{"answer": {"asset_id": "P-...", "cavitation_start_minute": <int>}}.')
107
+
108
+ def tools(self):
109
+ return self.files_tools() + [self.python_tool(), Tool(
110
+ "submit", "submit the answer", self.grade, {"answer": dict}, final=True)]
111
+
112
+ def grade(self, a):
113
+ got = lower_keys(a.get("answer", {}))
114
+ asset_ok = str(got.get("asset_id", "")).strip().upper() == self.fault[0]
115
+ return float(asset_ok and same_int(got.get("cavitation_start_minute"), self.fault[1]))
116
+
117
+ def oracle(self):
118
+ return [{"tool": "read_file", "args": {"path": "manual.md"}},
119
+ {"tool": "read_file", "args": {"path": "maintenance_log.md"}},
120
+ {"tool": "python", "args": {"code": "import os; print(os.listdir('telemetry'))"}},
121
+ {"tool": "submit", "args": {"answer": {"asset_id": self.fault[0],
122
+ "cavitation_start_minute": self.fault[1]}}}]
123
+
124
+ def naive(self):
125
+ if self.level == 3: # saw the decoy's window but not the second one
126
+ return [{"tool": "submit", "args": {"answer": {"asset_id": self.fault[0],
127
+ "cavitation_start_minute": self.raw_start}}}]
128
+ return [{"tool": "submit", "args": {"answer": {"asset_id": self.decoy[0],
129
+ "cavitation_start_minute": self.decoy[1]}}}]
source/diligence/families/math_tasks.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Math: exact-answer problems with a Python tool. Caveat: the setter's clarifications change one condition."""
2
+
3
+ import itertools
4
+ import math
5
+ from fractions import Fraction
6
+
7
+ from ..base import Task, Tool, lower_keys
8
+
9
+
10
+ def norm(text):
11
+ return str(text).strip().lower().replace(" ", "").rstrip(".")
12
+
13
+
14
+ class Problems(Task):
15
+ family = "math-problems"
16
+ domain = "mathematics-or-formal-reasoning"
17
+ max_steps = 8
18
+
19
+ def setup(self):
20
+ r = self.rng
21
+ self.variant = r.randrange(4)
22
+ getattr(self, f"_v{self.variant}")(r)
23
+ assert norm(self.truth) != norm(self.naive_truth)
24
+ self.files = {"problem.md": f"# Problem\n\n{self.text}\n",
25
+ "clarifications.md": f"# Clarifications from the problem setter\n\n- {self.clarification}\n"}
26
+
27
+ def _v0(self, r): # lattice paths; clarification adds a second blocked point
28
+ w, h = r.randint(5, 8), r.randint(5, 8)
29
+ cells = [(x, y) for x in range(1, w) for y in range(1, h)]
30
+ b1, b2 = r.sample(cells, 2)
31
+
32
+ def count(blocked):
33
+ grid = [[0] * (h + 1) for _ in range(w + 1)]
34
+ for x in range(w + 1):
35
+ for y in range(h + 1):
36
+ if (x, y) in blocked:
37
+ continue
38
+ grid[x][y] = 1 if x == y == 0 else (grid[x - 1][y] if x else 0) + (grid[x][y - 1] if y else 0)
39
+ return grid[w][h]
40
+
41
+ self.text = (f"How many shortest grid paths go from (0,0) to ({w},{h}), moving one unit right or up at each "
42
+ f"step, without passing through the point {b1}? Answer with an integer.")
43
+ self.clarification = f"The point {b2} is also closed: paths may pass through neither {b1} nor {b2}."
44
+ self.truth, self.naive_truth = str(count({b1, b2})), str(count({b1}))
45
+
46
+ def _v1(self, r): # bounded triples; clarification requires distinct values
47
+ n, cap = r.randint(12, 20), r.randint(7, 10)
48
+ triples = [t for t in itertools.product(range(cap + 1), repeat=3) if sum(t) == n]
49
+ self.text = (f"How many ordered triples of integers (x, y, z) with 0 <= x, y, z <= {cap} satisfy "
50
+ f"x + y + z = {n}? Answer with an integer.")
51
+ self.clarification = "x, y and z must be pairwise distinct."
52
+ self.truth = str(sum(1 for t in triples if len(set(t)) == 3))
53
+ self.naive_truth = str(len(triples))
54
+
55
+ def _v2(self, r): # marbles; clarification: draws are with replacement
56
+ red, blue = r.randint(3, 8), r.randint(3, 8)
57
+ without = Fraction(math.comb(red, 2) * blue, math.comb(red + blue, 3))
58
+ pr = Fraction(red, red + blue)
59
+ with_ = 3 * pr * pr * (1 - pr)
60
+ self.text = (f"A bag has {red} red and {blue} blue marbles. Three marbles are drawn. What is the probability "
61
+ f"that exactly two are red? Answer as a reduced fraction a/b.")
62
+ self.clarification = "Each marble is put back in the bag before the next draw (drawing with replacement)."
63
+ self.truth, self.naive_truth = f"{with_.numerator}/{with_.denominator}", f"{without.numerator}/{without.denominator}"
64
+
65
+ def _v3(self, r): # last digits; clarification asks for three digits
66
+ a, b = r.choice([3, 7, 13, 17, 23]), r.randint(300, 999)
67
+ self.text = f"What are the last two digits of {a}^{b}? Answer with the digits only, e.g. 07."
68
+ self.clarification = "Give the last three digits instead of two (e.g. 007)."
69
+ self.truth, self.naive_truth = f"{pow(a, b, 1000):03d}", f"{pow(a, b, 100):02d}"
70
+
71
+ def brief(self):
72
+ # level 1 asks for every file to be read (v2's level 1 pointed straight at clarifications.md: too easy)
73
+ pointer = " Read every workspace file before answering." if self.level == 1 else ""
74
+ return ('MATH. Solve the problem in problem.md (workspace files: problem.md, clarifications.md).' + pointer
75
+ + ' Submit {"answer": {"value": "<your answer>"}}.')
76
+
77
+ def tools(self):
78
+ return self.files_tools() + [self.python_tool(), Tool(
79
+ "submit", "submit the answer", self.grade, {"answer": dict}, final=True)]
80
+
81
+ def grade(self, a):
82
+ got = norm(lower_keys(a.get("answer", {})).get("value", ""))
83
+ if got == norm(self.truth):
84
+ return 1.0
85
+ if "/" in self.truth and "/" in got:
86
+ try:
87
+ num, den = got.split("/")
88
+ return float(Fraction(int(num), int(den)) == Fraction(self.truth) and math.gcd(int(num), int(den)) == 1)
89
+ except (ValueError, ZeroDivisionError):
90
+ return 0.0
91
+ return 0.0
92
+
93
+ def oracle(self):
94
+ return [{"tool": "read_file", "args": {"path": "problem.md"}},
95
+ {"tool": "read_file", "args": {"path": "clarifications.md"}},
96
+ {"tool": "submit", "args": {"answer": {"value": self.truth}}}]
97
+
98
+ def naive(self):
99
+ return [{"tool": "read_file", "args": {"path": "problem.md"}},
100
+ {"tool": "submit", "args": {"answer": {"value": self.naive_truth}}}]
source/diligence/families/media.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Media: copy-edit a news item to a house style guide.
2
+
3
+ Caveat: page 2 of the guide is a client addendum with extra rules that the automated checker does not cover.
4
+ """
5
+
6
+ import difflib
7
+ import re
8
+
9
+ from ..base import Task, Tool
10
+
11
+ ORGS = ["Northwind", "Bluefield", "Corvane"]
12
+ CITIES = ["Portland", "Tacoma", "Boise"]
13
+ NUM_WORDS = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine",
14
+ 12: "twelve", 15: "fifteen", 20: "twenty"}
15
+ BIG_WORDS = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
16
+ "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
17
+ BANNED = ["e-mail", "utilize", "utilizes", "in order to"]
18
+ PRODUCTS = [("EcoBin", ["Eco Bin", "Ecobin"]), ("FixHub", ["Fix Hub", "Fixhub"]), ("LoopKit", ["Loop Kit", "Loopkit"])]
19
+
20
+
21
+ def base_issues(lines, nouns):
22
+ found = []
23
+ head = lines[0] if lines else ""
24
+ if len(head) > 70:
25
+ found.append("headline length")
26
+ words = re.findall(r"[A-Za-z][A-Za-z'-]*", head)
27
+ if words and not words[0][0].isupper():
28
+ found.append("headline first word")
29
+ found += [f"headline case: {w}" for w in words[1:] if w[0].isupper() and w not in nouns]
30
+ for n, line in enumerate(lines, 1):
31
+ if "!" in line:
32
+ found.append(f"line {n}: exclamation")
33
+ for m in re.finditer(r"(?<![\d.,])\b([1-9])\b(?![\d.,])", line):
34
+ if not re.match(r"\s*percent", line[m.end():]):
35
+ found.append(f"line {n}: numeral")
36
+ low = line.lower()
37
+ found += [f"line {n}: spelled number" for w in BIG_WORDS if re.search(rf"\b{w}\b", low)]
38
+ found += [f"line {n}: banned word" for b in BANNED if re.search(rf"\b{re.escape(b)}\b", low)]
39
+ return found
40
+
41
+
42
+ class CopyEdit(Task):
43
+ family = "media-copyedit"
44
+ domain = "media-content-production"
45
+ max_steps = 14
46
+ levels = (1, 2, 3)
47
+
48
+ def setup(self):
49
+ r = self.rng
50
+ org, city = r.choice(ORGS), r.choice(CITIES)
51
+ self.product, variants = r.choice(PRODUCTS)
52
+ wrong = r.choice(variants)
53
+ self.nouns = {org, city, "Monday", "Friday", self.product}
54
+ a, b, c, d = r.choice([3, 4, 6, 7]), r.choice([12, 15, 20]), r.choice([2, 5, 8]), r.choice([5, 7, 9])
55
+ pct = r.choice([3, 4, 6])
56
+ bad_head = f"{org} Opens New Repair Hub In {city}"
57
+ good_head = f"{org} opens new repair hub in {city}"
58
+ body = [ # (original, fully correct, fixed for page 1 rules only)
59
+ (f"The hub employs {a} people and handles {NUM_WORDS[b]} tons of material a week.",
60
+ f"The hub employs {NUM_WORDS[a]} people and handles {b} tons of material a week.", None),
61
+ (f"Visits rose {pct} percent in the pilot, with {b} volunteers trained so far.", None, None),
62
+ (f"Every visitor gets a free {wrong} starter pack, which is very popular.",
63
+ f"Every visitor gets a free {self.product} starter pack, which is popular.",
64
+ f"Every visitor gets a free {wrong} starter pack, which is very popular."),
65
+ ("Staff will utilize donated shelving in order to keep startup costs low.",
66
+ "Staff will use donated shelving to keep startup costs low.", None),
67
+ ("Residents can drop off items starting Monday!", "Residents can drop off items starting Monday.", None),
68
+ (f"Questions can be sent by e-mail to the {city} office.",
69
+ f"Questions can be sent by email to the {city} office.", None),
70
+ (f"Volunteers sorted {d} pallets on Friday, a very good start.",
71
+ f"Volunteers sorted {NUM_WORDS[d]} pallets on Friday, a good start.",
72
+ f"Volunteers sorted {NUM_WORDS[d]} pallets on Friday, a very good start."),
73
+ ]
74
+ # level 3 uses every sentence, so more lines need edits under both pages of the guide
75
+ rows = body if self.level == 3 else body[:3] + r.sample(body[3:], 3)
76
+ if self.level == 3:
77
+ self.max_steps = 16
78
+ r.shuffle(rows)
79
+ rows = [(o, g or o, n or g or o) for o, g, n in rows]
80
+ self.original = [bad_head] + [row[0] for row in rows]
81
+ self.reference = [good_head] + [row[1] for row in rows]
82
+ self.naive_doc = [good_head] + [row[2] for row in rows]
83
+ self.doc = list(self.original)
84
+ assert not self.issues(self.reference)
85
+ assert len(base_issues(self.original, self.nouns)) >= 4
86
+ assert not base_issues(self.naive_doc, self.nouns) and self.issues(self.naive_doc)
87
+
88
+ def issues(self, lines):
89
+ found = base_issues(lines, self.nouns)
90
+ for n, line in enumerate(lines, 1):
91
+ if re.search(r"\bvery\b", line, re.I):
92
+ found.append(f"line {n}: addendum very")
93
+ for _, variants in PRODUCTS:
94
+ if any(v in line for v in variants):
95
+ found.append(f"line {n}: addendum product name")
96
+ return found
97
+
98
+ def brief(self):
99
+ hint = " The style guide has two pages." if self.level == 1 else ""
100
+ return ("MEDIA. Copy desk. Edit the news item so it follows the house style guide, then submit."
101
+ f"{hint}\n\n" + self._show())
102
+
103
+ def _show(self):
104
+ return "\n".join(f"{i}: {line}" for i, line in enumerate(self.doc, 1))
105
+
106
+ def tools(self):
107
+ return [
108
+ Tool("show", "show the item with line numbers", lambda a: self._show()),
109
+ Tool("guide", "show one page of the style guide (page 1 if omitted)", self._guide, {"page": int},
110
+ optional=("page",)),
111
+ Tool("set_line", "replace one whole line", self._set, {"line": int, "text": str}),
112
+ Tool("check", "run the automated style checker", lambda a: (
113
+ f"{len(base_issues(self.doc, self.nouns))} issue(s) found by the automated checker (it covers "
114
+ "page 1 rules only).")),
115
+ Tool("submit", "send the item to the editor", self.grade, final=True),
116
+ ]
117
+
118
+ def _guide(self, a):
119
+ page = a.get("page", 1)
120
+ if page == 1:
121
+ nouns = ", ".join(sorted(self.nouns - {self.product}))
122
+ return ("House style, page 1 of 2.\n1. Headline (line 1): sentence case - capitalize only the first word "
123
+ f"and proper nouns (here: {nouns}); at most 70 characters.\n2. No exclamation marks.\n3. Spell out "
124
+ "whole numbers one to nine; use numerals for 10 and above, and always for percentages "
125
+ '("4 percent").\n4. Write "email" (not "e-mail"), "use" (not "utilize") and "to" (not "in order '
126
+ 'to").\nChange only what the rules require.')
127
+ if page == 2:
128
+ return (f"House style, page 2 of 2: client addendum.\n5. The client's product is always written "
129
+ f"\"{self.product}\" (one word, exactly this capitalization).\n6. Delete the word \"very\" "
130
+ "wherever it appears.")
131
+ return "The guide has pages 1 and 2."
132
+
133
+ def _set(self, a):
134
+ if not 1 <= a["line"] <= len(self.doc):
135
+ return f"line must be 1-{len(self.doc)}"
136
+ self.doc[a["line"] - 1] = a["text"].strip()
137
+ return f"Line {a['line']} updated."
138
+
139
+ def grade(self, a, doc=None):
140
+ doc = self.doc if doc is None else doc
141
+ if len(doc) != len(self.reference):
142
+ return 0.0
143
+ for got, want in zip(doc, self.reference):
144
+ if difflib.SequenceMatcher(None, got.lower(), want.lower()).ratio() < 0.85:
145
+ return 0.0
146
+ if base_issues(doc, self.nouns):
147
+ return 0.0
148
+ return 0.0 if self.issues(doc) else 1.0
149
+
150
+ def oracle(self):
151
+ acts = [{"tool": "guide", "args": {}}, {"tool": "guide", "args": {"page": 2}}]
152
+ acts += [{"tool": "set_line", "args": {"line": i, "text": good}}
153
+ for i, (bad, good) in enumerate(zip(self.original, self.reference), 1) if bad != good]
154
+ return acts + [{"tool": "submit", "args": {}}]
155
+
156
+ def naive(self):
157
+ acts = [{"tool": "set_line", "args": {"line": i, "text": fixed}}
158
+ for i, (bad, fixed) in enumerate(zip(self.original, self.naive_doc), 1) if bad != fixed]
159
+ return acts + [{"tool": "submit", "args": {}}]
source/diligence/families/office.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Office: book a meeting from an email request. Caveat: an attendee's later email rules out the obvious slot.
2
+
3
+ Level 1 flags that email in its subject and adds a free-slot finder over the calendars; level 2 does neither.
4
+ """
5
+
6
+ from ..base import Task, Tool, lower_keys
7
+
8
+ PEOPLE = ["Ana Duarte", "Raj Mehta", "Lena Fischer", "Tom Okafor", "Mei Chen", "Sam Rivera"]
9
+ DAYS = ["2026-10-13", "2026-10-14", "2026-10-15"]
10
+ DAY_NAMES = {"2026-10-13": "Tuesday", "2026-10-14": "Wednesday", "2026-10-15": "Thursday"}
11
+
12
+
13
+ def hm(minutes):
14
+ return f"{minutes // 60:02d}:{minutes % 60:02d}"
15
+
16
+
17
+ def parse_hm(text):
18
+ h, m = str(text).strip().split(":")[:2]
19
+ return int(h) * 60 + int(m)
20
+
21
+
22
+ class Scheduling(Task):
23
+ family = "office-scheduling"
24
+ domain = "office-white-collar"
25
+ max_steps = 14
26
+
27
+ def setup(self):
28
+ r = self.rng
29
+ self.boss, a, b, other = r.sample(PEOPLE, 4)
30
+ self.attendees = sorted([self.boss, a, b])
31
+ self.duration = r.choice([30, 45, 60])
32
+ self.days = DAYS[:2] if r.random() < 0.5 else DAYS[1:]
33
+ self.title = r.choice(["Q4 budget review", "Vendor contract kickoff", "Hiring plan sync", "Audit prep"])
34
+ self.cal = {}
35
+ for person in PEOPLE:
36
+ for day in DAYS:
37
+ busy, t = [], 9 * 60
38
+ while t < 17 * 60:
39
+ if r.random() < 0.4:
40
+ length = r.choice([30, 60, 90])
41
+ busy.append((t, min(t + length, 17 * 60)))
42
+ t += length
43
+ t += 30
44
+ self.cal[(person, day)] = busy
45
+ self.late_person, self.late_day, self.late_block = r.choice([a, b]), None, (0, 0)
46
+ self.naive_slot = self._earliest()
47
+ assert self.naive_slot is not None
48
+ self.late_day = self.naive_slot[0]
49
+ top = self.naive_slot[1] - self.naive_slot[1] % 60
50
+ self.late_block = (top, min(top + r.choice([120, 180]), 17 * 60))
51
+ self.slot = self._earliest()
52
+ assert self.slot is not None and self.slot != self.naive_slot
53
+ when = f"{DAY_NAMES[self.late_day]} {hm(self.late_block[0])}-{hm(self.late_block[1])}"
54
+ late_subject = f"Out of office {when} (not on my calendar)" if self.level == 1 else "Re: availability"
55
+ mails = [
56
+ (self.boss, f"Please set up: {self.title}",
57
+ f"Hi, please set up a {self.duration}-minute '{self.title}' with {a} and {b} (and me) on "
58
+ f"{DAY_NAMES[self.days[0]]} {self.days[0]} or {DAY_NAMES[self.days[1]]} {self.days[1]}. Working hours "
59
+ f"are 09:00-17:00 and nobody meets over lunch (12:00-13:00). Start on the quarter hour and take the "
60
+ f"earliest slot that works for all three of us. Thanks!"),
61
+ ("it-news@corp.example", "Password rotation reminder", "Reminder: rotate your password before Friday."),
62
+ (self.late_person, late_subject,
63
+ f"Heads up: I'll be at the client site on {DAY_NAMES[self.late_day]} {self.late_day} from "
64
+ f"{hm(self.late_block[0])} to {hm(self.late_block[1])}. It's not on my calendar yet."),
65
+ (other, "Lunch Thursday?", "Want to grab lunch Thursday at 12:30?"),
66
+ ]
67
+ if self.level == 2:
68
+ mails.append(("facilities@corp.example", "Room 4B closed", "Room 4B is closed for repairs all week."))
69
+ order = list(range(len(mails)))
70
+ r.shuffle(order)
71
+ self.emails = {f"m{i + 1}": mails[j] for i, j in enumerate(order)}
72
+ self.request_id = next(k for k, v in self.emails.items() if v[0] == self.boss and v[1].startswith("Please"))
73
+ self.late_id = next(k for k, v in self.emails.items() if v[0] == self.late_person and "client site" in v[2])
74
+
75
+ def _busy(self, person, day):
76
+ blocks = list(self.cal[(person, day)]) + [(12 * 60, 13 * 60)]
77
+ if person == self.late_person and day == self.late_day:
78
+ blocks.append(self.late_block)
79
+ return blocks
80
+
81
+ def _earliest(self):
82
+ for day in self.days:
83
+ for start in range(9 * 60, 17 * 60 - self.duration + 1, 15):
84
+ end = start + self.duration
85
+ if all(end <= s or start >= e for p in self.attendees for s, e in self._busy(p, day)):
86
+ return day, start
87
+ return None
88
+
89
+ def brief(self):
90
+ return ("OFFICE. You are an executive assistant. Handle the scheduling request in the inbox: find the right "
91
+ "slot and send the invitation with create_event.")
92
+
93
+ def tools(self):
94
+ return [
95
+ Tool("list_emails", "list the inbox", lambda a: "\n".join(
96
+ f"{k}: from {v[0]} - {v[1]}" for k, v in self.emails.items())),
97
+ Tool("read_email", "read one email", self._read_email, {"email_id": str}),
98
+ Tool("get_calendar", "show a person's busy blocks on one day", self._calendar,
99
+ {"person": str, "date": str}),
100
+ Tool("check_slot", "list calendar conflicts for a proposed slot (calendars only)", self._check,
101
+ {"date": str, "start": str, "end": str, "attendees": list}),
102
+ ] + ([Tool("find_free_slots", "list start times (quarter hours, 09:00-17:00) when everyone's calendar is free "
103
+ "for a meeting of this length (calendars only)", self._free,
104
+ {"date": str, "minutes": int, "attendees": list})] if self.level == 1 else []) + [
105
+ Tool("create_event", "send the invitation", self.grade,
106
+ {"title": str, "date": str, "start": str, "end": str, "attendees": list}, final=True),
107
+ ]
108
+
109
+ def _free(self, a):
110
+ if a["date"] not in DAYS:
111
+ return "Unknown date (use YYYY-MM-DD)."
112
+ if not 15 <= a["minutes"] <= 240:
113
+ return "minutes must be 15-240"
114
+ for p in a["attendees"]:
115
+ if p not in PEOPLE:
116
+ return f"Unknown person {p!r}."
117
+ starts = [s for s in range(9 * 60, 17 * 60 - a["minutes"] + 1, 15)
118
+ if all(s + a["minutes"] <= b0 or s >= b1 for p in a["attendees"] for b0, b1 in self.cal[(p, a["date"])])]
119
+ return f"Free for {a['minutes']} min on {a['date']}: " + (", ".join(hm(s) for s in starts) or "none")
120
+
121
+ def _read_email(self, a):
122
+ mail = self.emails.get(a["email_id"].strip())
123
+ return f"From: {mail[0]}\nSubject: {mail[1]}\n\n{mail[2]}" if mail else "No such email."
124
+
125
+ def _calendar(self, a):
126
+ if a["person"] not in PEOPLE or a["date"] not in DAYS:
127
+ return "Unknown person or date (use full names and YYYY-MM-DD)."
128
+ busy = self.cal[(a["person"], a["date"])]
129
+ return f"{a['person']} on {a['date']}. Busy: " + (", ".join(f"{hm(s)}-{hm(e)}" for s, e in busy) or "nothing")
130
+
131
+ def _check(self, a):
132
+ try:
133
+ start, end = parse_hm(a["start"]), parse_hm(a["end"])
134
+ except ValueError:
135
+ return "start and end must be HH:MM"
136
+ if a["date"] not in DAYS:
137
+ return "Unknown date (use YYYY-MM-DD)."
138
+ conflicts = []
139
+ for p in a["attendees"]:
140
+ if p not in PEOPLE:
141
+ return f"Unknown person {p!r}."
142
+ conflicts += [f"{p} busy {hm(s)}-{hm(e)}" for s, e in self.cal[(p, a["date"])] if not (end <= s or start >= e)]
143
+ return "Conflicts: " + "; ".join(conflicts) if conflicts else "No calendar conflicts."
144
+
145
+ def grade(self, a):
146
+ ev = lower_keys(a)
147
+ try:
148
+ start, end = parse_hm(ev.get("start")), parse_hm(ev.get("end"))
149
+ people = sorted(str(p).strip() for p in ev.get("attendees", []))
150
+ except (ValueError, TypeError, AttributeError):
151
+ return 0.0
152
+ return float(ev.get("date") == self.slot[0] and start == self.slot[1] and end - start == self.duration
153
+ and people == self.attendees)
154
+
155
+ def _event(self, slot):
156
+ day, start = slot
157
+ return {"tool": "create_event", "args": {"title": self.title, "date": day, "start": hm(start),
158
+ "end": hm(start + self.duration), "attendees": self.attendees}}
159
+
160
+ def oracle(self):
161
+ return [{"tool": "list_emails", "args": {}},
162
+ {"tool": "read_email", "args": {"email_id": self.request_id}},
163
+ {"tool": "read_email", "args": {"email_id": self.late_id}},
164
+ self._event(self.slot)]
165
+
166
+ def naive(self):
167
+ return [{"tool": "read_email", "args": {"email_id": self.request_id}}, self._event(self.naive_slot)]
source/diligence/families/reasoning.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Formal reasoning: one-shot problems with no tools to compute with, so any working-out has to happen in the reply.
2
+
3
+ The reply is still a single JSON action; the action's metadata field is the natural place for working (the
4
+ observation sometimes says so). Answers are computed by brute force.
5
+ """
6
+
7
+ import itertools
8
+ import math
9
+ from fractions import Fraction
10
+
11
+ from ..base import Task, Tool
12
+
13
+ SHORT_WORDS = ["APPLE", "LLAMA", "GEESE", "KAYAK", "ARRAY", "EERIE", "PUPPY", "TEETH", "SASSY", "MAMMA"]
14
+ WORDS = ["BANANA", "LETTER", "BALLOON", "COFFEE", "PEPPER", "SUCCESS", "COOKIE", "PUPPET", "ACCESS", "BUBBLE",
15
+ "TOMATO", "GIGGLE", "MAMMAL", "ASSESS", "RABBIT", "CANCEL"]
16
+
17
+
18
+ def norm(text):
19
+ return str(text).strip().lower().replace(" ", "").rstrip(".")
20
+
21
+
22
+ def hm(minutes):
23
+ return f"{minutes // 60:02d}:{minutes % 60:02d}"
24
+
25
+
26
+ class Reasoning(Task):
27
+ family = "math-reasoning"
28
+ domain = "mathematics-or-formal-reasoning"
29
+ max_steps = 2 # one answer; a malformed first call can be corrected once
30
+
31
+ def setup(self):
32
+ r = self.rng
33
+ self.variant = r.randrange(6)
34
+ getattr(self, f"_v{self.variant}")(r, self.level == 2)
35
+ assert norm(self.truth) != norm(self.naive_truth)
36
+
37
+ def _v0(self, r, hard): # inclusion-exclusion
38
+ n = r.randint(150, 400) if hard else r.randint(30, 80)
39
+ a, b, c = r.sample([2, 3, 5, 7, 11], 3) if hard else r.sample([2, 3, 5, 7], 2) + [None]
40
+ if c:
41
+ self.text = (f"How many integers from 1 to {n} are divisible by {a} or {b}, but not by {c}? "
42
+ "Answer with an integer.")
43
+ self.truth = str(sum(1 for k in range(1, n + 1) if (k % a == 0 or k % b == 0) and k % c))
44
+ self.naive_truth = str(sum(1 for k in range(1, n + 1) if k % a == 0 or k % b == 0))
45
+ else:
46
+ self.text = (f"How many integers from 1 to {n} are divisible by neither {a} nor {b}? "
47
+ "Answer with an integer.")
48
+ self.truth = str(sum(1 for k in range(1, n + 1) if k % a and k % b))
49
+ self.naive_truth = str(n - n // a - n // b)
50
+
51
+ def _v1(self, r, hard): # arrangements of a word's letters with a constraint
52
+ word = r.choice(WORDS if hard else SHORT_WORDS)
53
+ perms = set(itertools.permutations(word))
54
+ doubled = sorted({ch for ch in word if word.count(ch) >= 2})
55
+ ch = r.choice(doubled)
56
+ if hard:
57
+ self.text = (f"How many distinct arrangements of the letters of {word} have no two {ch}'s next to each "
58
+ "other? Answer with an integer.")
59
+ self.truth = str(sum(1 for p in perms if ch + ch not in "".join(p)))
60
+ assert self.truth != "0"
61
+ else:
62
+ self.text = (f"How many distinct arrangements of the letters of {word} begin with {ch}? "
63
+ "Answer with an integer.")
64
+ self.truth = str(sum(1 for p in perms if p[0] == ch))
65
+ self.naive_truth = str(len(perms))
66
+
67
+ def _v2(self, r, hard): # earliest common free slot
68
+ names = r.sample(["Ana", "Ben", "Chen", "Dara", "Eli", "Fay"], 3 if hard else 2)
69
+ length = r.choice([45, 60, 90]) if hard else r.choice([30, 60])
70
+ busy = {}
71
+ for name in names:
72
+ blocks, t = [], 9 * 60 + r.choice([0, 30])
73
+ while t < 16 * 60:
74
+ start = t + r.choice([0, 15, 30, 60])
75
+ end = start + r.choice([30, 45, 60, 90])
76
+ if end > 17 * 60:
77
+ break
78
+ blocks.append((start, end))
79
+ t = end + r.choice([15, 30, 45])
80
+ busy[name] = blocks
81
+
82
+ def free(start):
83
+ end = start + length
84
+ if end > 17 * 60 or (start < 13 * 60 and end > 12 * 60):
85
+ return False
86
+ return all(end <= s or start >= e for blocks in busy.values() for s, e in blocks)
87
+
88
+ starts = [t for t in range(9 * 60, 17 * 60, 15) if free(t)]
89
+ assert starts and starts[0] >= 10 * 60 # make the answer need some working
90
+ lines = "; ".join(f"{n} is busy " + ", ".join(f"{hm(s)}-{hm(e)}" for s, e in busy[n]) for n in names)
91
+ self.text = (f"Find the earliest start time for a {length}-minute meeting with {', '.join(names)}. "
92
+ f"{lines}. The working day is 09:00-17:00, nobody meets over lunch (12:00-13:00), and meetings "
93
+ "start on the quarter hour. Answer with the start time as HH:MM.")
94
+ self.truth = hm(starts[0])
95
+ # a classic slip: forgetting the lunch rule
96
+ lunch_blind = [t for t in range(9 * 60, 17 * 60, 15) if t + length <= 17 * 60 and all(
97
+ t + length <= s or t >= e for blocks in busy.values() for s, e in blocks)]
98
+ self.naive_truth = hm(lunch_blind[0]) if lunch_blind and lunch_blind[0] != starts[0] else hm(starts[0] + 15)
99
+
100
+ def _v3(self, r, hard): # expected value of a dice game
101
+ lose = r.randint(2, 6)
102
+ if not hard:
103
+ parity = r.choice(["even", "odd"])
104
+ ev = Fraction(sum(f if f % 2 == (parity == "odd") else -lose for f in range(1, 7)), 6)
105
+ self.text = (f"Roll one fair six-sided die. If it shows an {parity} number you win that many dollars; "
106
+ f"otherwise you lose ${lose}. What is your expected winnings in dollars? Answer as a reduced "
107
+ "fraction a/b (negative if you expect to lose), or an integer.")
108
+ self.truth = str(ev.numerator) if ev.denominator == 1 else f"{ev.numerator}/{ev.denominator}"
109
+ naive = Fraction(sum(f for f in range(1, 7) if f % 2 == (parity == "odd")), 6)
110
+ self.naive_truth = str(naive.numerator) if naive.denominator == 1 else f"{naive.numerator}/{naive.denominator}"
111
+ return
112
+ outcomes = list(itertools.product(range(1, 7), repeat=2))
113
+
114
+ def pay(o):
115
+ return -lose if o[0] == o[1] else max(o)
116
+
117
+ ev = Fraction(sum(pay(o) for o in outcomes), len(outcomes))
118
+ self.text = (f"Roll 2 fair six-sided dice. If all the dice show different numbers you win the highest "
119
+ f"number shown, in dollars; otherwise you lose ${lose}. What is your expected winnings in dollars? "
120
+ "Answer as a reduced fraction a/b (negative if you expect to lose), or an integer.")
121
+ self.truth = str(ev.numerator) if ev.denominator == 1 else f"{ev.numerator}/{ev.denominator}"
122
+ naive = Fraction(sum(max(o) for o in outcomes), len(outcomes))
123
+ self.naive_truth = f"{naive.numerator}/{naive.denominator}"
124
+
125
+ def _v4(self, r, hard): # a recurrence
126
+ p, q, k, c = r.randint(1, 5), r.randint(1, 5), r.randint(2, 3), r.randint(1, 4)
127
+ n = r.randint(7, 9) if hard else r.randint(5, 6)
128
+ seq = [p, q]
129
+ while len(seq) < n:
130
+ seq.append(seq[-1] + k * seq[-2] - c)
131
+ self.text = (f"A sequence starts a(1) = {p}, a(2) = {q}, and for n >= 3, a(n) = a(n-1) + {k}*a(n-2) - {c}. "
132
+ f"What is a({n})? Answer with an integer.")
133
+ self.truth = str(seq[n - 1])
134
+ self.naive_truth = str(seq[n - 2])
135
+
136
+ def _v5(self, r, hard): # knights and knaves
137
+ names = ["A", "B", "C"][: 3 if hard else 2]
138
+ m = len(names)
139
+ while True:
140
+ stmts = []
141
+ for i in range(m):
142
+ j = r.choice([x for x in range(m) if x != i])
143
+ stmts.append((i, j, r.choice(["is_knave", "same", "count"]), r.randint(1, m - 1)))
144
+
145
+ def holds(world, s):
146
+ i, j, kind, cnt = s
147
+ if kind == "is_knave":
148
+ return not world[j]
149
+ if kind == "same":
150
+ return world[i] == world[j]
151
+ return sum(world) == cnt
152
+
153
+ worlds = [w for w in itertools.product([True, False], repeat=m)
154
+ if all(holds(w, s) == w[s[0]] for s in stmts)]
155
+ if len(worlds) == 1:
156
+ break
157
+ say = {"is_knave": lambda j, cnt: f"{names[j]} is a knave.",
158
+ "same": lambda j, cnt: f"{names[j]} and I are the same type.",
159
+ "count": lambda j, cnt: f"Exactly {cnt} of us {'is a knight' if cnt == 1 else 'are knights'}."}
160
+ lines = " ".join(f'{names[i]} says: "{say[kind](j, cnt)}"' for i, j, kind, cnt in stmts)
161
+ self.text = (f"On an island, knights always tell the truth and knaves always lie. {lines} Which of "
162
+ f"{', '.join(names)} are knights? Answer with the letters in alphabetical order separated by "
163
+ "commas, or 'none'.")
164
+ knights = [names[i] for i in range(m) if worlds[0][i]]
165
+ self.truth = ",".join(knights) if knights else "none"
166
+ everyone_true = [names[i] for i in range(m)]
167
+ self.naive_truth = ",".join(everyone_true) if self.truth != ",".join(everyone_true) else "none"
168
+
169
+ def brief(self):
170
+ return (f"REASONING. {self.text}\nThere are no tools to compute with; work it out yourself, then call "
171
+ 'submit with your answer: {"tool": "submit", "args": {"answer": "<your answer>"}}.')
172
+
173
+ def tools(self):
174
+ return [Tool("submit", "submit the answer", self.grade, {"answer": str}, final=True)]
175
+
176
+ def grade(self, a):
177
+ got = norm(a.get("answer", ""))
178
+ if got == norm(self.truth):
179
+ return 1.0
180
+ if "/" in self.truth and "/" in got:
181
+ try:
182
+ num, den = got.split("/")
183
+ return float(Fraction(int(num), int(den)) == Fraction(self.truth) and math.gcd(int(num), int(den)) == 1
184
+ and int(den) > 0)
185
+ except (ValueError, ZeroDivisionError):
186
+ return 0.0
187
+ if self.variant == 2 and len(got) == 4 and got[1] == ":": # 9:30 for 09:30
188
+ return float("0" + got == norm(self.truth))
189
+ return 0.0
190
+
191
+ def oracle(self):
192
+ return [{"tool": "submit", "args": {"answer": self.truth}}]
193
+
194
+ def naive(self):
195
+ return [{"tool": "submit", "args": {"answer": self.naive_truth}}]
source/diligence/families/science.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Natural science: analyse lab data with Python. Caveat: the lab notebook records a correction to the data
2
+ (two corrections at level 3)."""
3
+
4
+ import math
5
+
6
+ from ..base import Task, Tool, close, lower_keys, same_int, template
7
+
8
+
9
+ def linfit(xs, ys):
10
+ n = len(xs)
11
+ mx, my = sum(xs) / n, sum(ys) / n
12
+ slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
13
+ return slope, my - slope * mx
14
+
15
+
16
+ class LabAnalysis(Task):
17
+ family = "science-lab"
18
+ domain = "natural-science"
19
+ max_steps = 10
20
+ levels = (1, 2, 3)
21
+
22
+ def setup(self):
23
+ r = self.rng
24
+ self.variant = r.randrange(4)
25
+ self.extra = self.level == 3
26
+ self.second_answer = None # level 3: the answer with only the first correction applied
27
+ getattr(self, f"_v{self.variant}")(r)
28
+ if self.second_answer is not None:
29
+ assert any(not self._match(self.answer[k], self.second_answer[k]) for k in self.answer)
30
+ assert any(not self._match(self.answer[k], self.naive_answer[k]) for k in self.answer)
31
+ self.files["protocol.md"] = self.protocol
32
+ self.files["data.csv"] = self.csv
33
+ self.files["notebook.md"] = "# Lab notebook\n\n" + "\n".join(f"- {line}" for line in self.notes) + "\n"
34
+
35
+ @staticmethod
36
+ def _match(a, b):
37
+ if isinstance(a, (str, int)):
38
+ return a == b
39
+ return math.isclose(a, b, rel_tol=0.01)
40
+
41
+ def _v0(self, r): # Arrhenius; one temperature was logged wrong
42
+ ea, a = r.uniform(45, 90) * 1000, 10 ** r.uniform(8, 12)
43
+ temps = sorted(r.sample(range(290, 360, 5), 6))
44
+ fix_i = r.randrange(1, 5)
45
+ true_t = [t + (5 if i == fix_i else 0) for i, t in enumerate(temps)]
46
+ ks = [float(f"{a * math.exp(-ea / (8.314 * t)) * math.exp(r.gauss(0, 0.02)):.4g}") for t in true_t]
47
+ self.csv = "run,temperature_K,rate_constant_per_s\n" + "\n".join(
48
+ f"R{i + 1},{t},{k}" for i, (t, k) in enumerate(zip(temps, ks)))
49
+
50
+ def fit(ts, drop=None):
51
+ pts = [(t, k) for i, (t, k) in enumerate(zip(ts, ks)) if i != drop]
52
+ slope, icpt = linfit([1 / t for t, _ in pts], [math.log(k) for _, k in pts])
53
+ return {"activation_energy_kj_per_mol": -slope * 8.314 / 1000, "k_at_375K_per_s": math.exp(icpt + slope / 375)}
54
+
55
+ self.answer, self.naive_answer = fit(true_t), fit(temps)
56
+ if self.extra:
57
+ drop = r.choice([i for i in range(6) if i != fix_i])
58
+ # make the contaminated run visibly off, so dropping it matters
59
+ ks[drop] = float(f"{ks[drop] * r.choice([0.6, 1.6]):.4g}")
60
+ self.csv = "run,temperature_K,rate_constant_per_s\n" + "\n".join(
61
+ f"R{i + 1},{t},{k}" for i, (t, k) in enumerate(zip(temps, ks)))
62
+ self.answer, self.second_answer, self.naive_answer = fit(true_t, drop), fit(true_t), fit(temps)
63
+ self.protocol = ("# Protocol\nMeasure the first-order rate constant at six bath temperatures. Estimate the "
64
+ "activation energy from an Arrhenius plot: least-squares fit of ln(k) against 1/T over all "
65
+ "runs (R = 8.314 J/(mol K)), and predict k at 375 K from the fit.\n")
66
+ self.notes = ["Bath thermostat recalibrated before R1.",
67
+ f"R{fix_i + 1}: the bath display read {temps[fix_i]} K but the reference thermometer showed "
68
+ f"{true_t[fix_i]} K; use the reference value.",
69
+ "All runs used catalyst batch C-17."]
70
+ if self.extra:
71
+ self.notes.insert(2, f"R{drop + 1}: catalyst found contaminated afterwards; exclude this run from the fit.")
72
+
73
+ def _v1(self, r): # growth curve; two readings were diluted
74
+ mu, od0, lag = r.uniform(0.6, 1.2), r.uniform(0.01, 0.02), r.choice([1.0, 1.5])
75
+ times = [i * 0.5 for i in range(14)]
76
+ true = []
77
+ for t in times:
78
+ od = od0 if t < lag else od0 * math.exp(mu * (t - lag))
79
+ true.append(round(min(od, 1.6 - r.uniform(0, 0.1)) * math.exp(r.gauss(0, 0.02)), 4))
80
+ in_win = [i for i, od in enumerate(true) if 0.12 <= od <= 0.5]
81
+ assert len(in_win) >= 3
82
+ diluted = in_win[-2:]
83
+ shown = [round(od / 2, 4) if i in diluted else od for i, od in enumerate(true)]
84
+ self.csv = "time_h,od600\n" + "\n".join(f"{t},{od}" for t, od in zip(times, shown))
85
+
86
+ def fit(ods):
87
+ win = [(t, od) for t, od in zip(times, ods) if 0.05 <= od <= 0.5]
88
+ slope, _ = linfit([t for t, _ in win], [math.log(od) for _, od in win])
89
+ return {"doubling_time_min": math.log(2) / slope * 60, "rows_used": len(win)}
90
+
91
+ # the answer uses only what the agent can see: shown readings, with the diluted ones doubled
92
+ corrected = [od * 2 if i in diluted else od for i, od in enumerate(shown)]
93
+ self.answer, self.naive_answer = fit(corrected), fit(shown)
94
+ if self.extra:
95
+ blank = r.choice([0.012, 0.015, 0.02, 0.025])
96
+ shown = [round(od + blank, 4) for od in shown]
97
+ self.csv = "time_h,od600\n" + "\n".join(f"{t},{od}" for t, od in zip(times, shown))
98
+ blanked = [(od - blank) * (2 if i in diluted else 1) for i, od in enumerate(shown)]
99
+ self.answer = fit(blanked)
100
+ self.second_answer = fit([od * 2 if i in diluted else od for i, od in enumerate(shown)])
101
+ self.naive_answer = fit(shown)
102
+ self.protocol = ("# Protocol\nEstimate the doubling time in the exponential phase: use only readings with "
103
+ "0.05 <= OD600 <= 0.5, fit ln(OD600) against time by least squares, and report doubling "
104
+ "time = ln(2)/slope in minutes and the number of readings used.\n")
105
+ self.notes = ["Culture started from an overnight pre-culture.",
106
+ f"Readings at {times[diluted[0]]} h and {times[diluted[1]]} h were measured after a 1:2 dilution "
107
+ "(the spectrophotometer was saturating); multiply them by 2 to get the culture OD.",
108
+ "Incubator held at 37 C throughout."]
109
+ if self.extra:
110
+ self.notes.insert(2, f"Medium blank read {blank} OD600; subtract it from every reading as measured "
111
+ "(before any dilution factor).")
112
+
113
+ def _v2(self, r): # Beer-Lambert standard curve; one standard mis-pipetted and the sample was diluted
114
+ eps = r.uniform(0.8, 2.5)
115
+ concs = [0, 2, 4, 6, 8, 10]
116
+ rows = [(c, round(eps * c / 10 + r.gauss(0, 0.003), 3)) for c in concs]
117
+ bad = r.choice([2, 3, 4])
118
+ rows[bad] = (rows[bad][0], round(rows[bad][1] * 1.3, 3))
119
+ absorb = round(r.uniform(0.25, 0.8) * eps, 3)
120
+ dil = r.choice([5, 10])
121
+ if self.extra: # level 3: the sample was read in a 0.5 cm cuvette, so the recorded value is half
122
+ absorb = round(absorb / 2, 3)
123
+ self.csv = "standard_mg_per_L,absorbance\n" + "\n".join(f"{c},{a}" for c, a in rows)
124
+
125
+ def fit(pts, factor, a):
126
+ slope, icpt = linfit([c for c, _ in pts], [a_ for _, a_ in pts])
127
+ return {"slope": slope, "sample_mg_per_L": (a - icpt) / slope * factor}
128
+
129
+ clean = [p for i, p in enumerate(rows) if i != bad]
130
+ self.answer = fit(clean, dil, absorb * (2 if self.extra else 1))
131
+ self.naive_answer = fit(rows, 1, absorb)
132
+ if self.extra:
133
+ self.second_answer = fit(clean, dil, absorb)
134
+ self.protocol = (f"# Protocol\nBuild a linear standard curve (absorbance against concentration, least "
135
+ f"squares with intercept) and report its slope and the concentration of the river sample "
136
+ f"in mg/L. The sample's absorbance was {absorb}.\n")
137
+ self.notes = [f"The {rows[bad][0]} mg/L standard was mis-pipetted; exclude it from the curve.",
138
+ f"The river sample was diluted 1:{dil} before measurement; report the undiluted concentration."]
139
+ if self.extra:
140
+ self.notes.append("Standards were read in 1 cm cuvettes, but the river sample in a 0.5 cm cuvette; double "
141
+ "its absorbance before using the curve.")
142
+
143
+ def _v3(self, r): # Hardy-Weinberg; some heterozygotes were re-genotyped
144
+ p, n = r.uniform(0.3, 0.7), r.randint(300, 900)
145
+ aa = round(n * (p * p + 0.03))
146
+ ab = round(n * 2 * p * (1 - p)) - round(n * 0.03)
147
+ bb = n - aa - ab
148
+ moved = r.randint(15, 30)
149
+
150
+ def test(c_aa, c_ab, c_bb):
151
+ tot = c_aa + c_ab + c_bb
152
+ pf = (2 * c_aa + c_ab) / (2 * tot)
153
+ exp_ = [tot * pf * pf, 2 * tot * pf * (1 - pf), tot * (1 - pf) ** 2]
154
+ chi = sum((o - e) ** 2 / e for o, e in zip([c_aa, c_ab, c_bb], exp_))
155
+ return {"allele_frequency_A": pf, "chi_square": chi, "decision": "reject" if chi > 3.841 else "fail to reject"}
156
+
157
+ self.csv = f"genotype,count\nAA,{aa}\nAa,{ab}\naa,{bb}"
158
+ self.answer, self.naive_answer = test(aa + moved, ab - moved, bb), test(aa, ab, bb)
159
+ if self.extra: # level 3: some aa calls came from a plate that failed QC
160
+ failed = r.randint(20, 40)
161
+ self.answer, self.second_answer = test(aa + moved, ab - moved, bb - failed), self.answer
162
+ self.protocol = ("# Protocol\nTest the genotype counts for Hardy-Weinberg equilibrium: estimate the A allele "
163
+ "frequency, compute the chi-square statistic over the three genotypes, and decide at alpha = "
164
+ '0.05 with 1 degree of freedom (critical value 3.841): "reject" or "fail to reject".\n')
165
+ self.notes = ["Samples genotyped on plates 1-3." if self.extra else "Samples genotyped on plate 1 and plate 2.",
166
+ f"Plate 2 re-run: {moved} samples first called Aa are actually AA (allele dropout). Use the "
167
+ "corrected calls."]
168
+ if self.extra:
169
+ self.notes.append(f"Plate 3 failed QC: drop its {failed} samples, all of which were called aa.")
170
+
171
+ def brief(self):
172
+ hint = " Read notebook.md for corrections before analysing." if self.level == 1 else ""
173
+ return (f"SCIENCE. Analyse the experiment in this workspace (protocol.md, data.csv, notebook.md) as the "
174
+ f"protocol describes.{hint} Submit {{\"answer\": {template(self.answer)}}}; numbers are checked to 1%.")
175
+
176
+ def tools(self):
177
+ return self.files_tools() + [self.python_tool(), Tool(
178
+ "submit", "submit the answer", self.grade, {"answer": dict}, final=True)]
179
+
180
+ def grade(self, a):
181
+ got = lower_keys(a.get("answer", {}))
182
+ scores = []
183
+ for key, want in self.answer.items():
184
+ val = got.get(key.lower())
185
+ if isinstance(want, str):
186
+ scores.append(isinstance(val, str) and val.strip().lower() == want)
187
+ elif isinstance(want, int):
188
+ scores.append(same_int(val, want))
189
+ else:
190
+ scores.append(close(val, want))
191
+ return float(all(scores))
192
+
193
+ def oracle(self):
194
+ return [{"tool": "read_file", "args": {"path": "notebook.md"}},
195
+ {"tool": "submit", "args": {"answer": self.answer}}]
196
+
197
+ def naive(self):
198
+ return [{"tool": "submit", "args": {"answer": self.naive_answer}}]
source/diligence/families/security.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cybersecurity: find the vulnerable line in a web service.
2
+
3
+ Caveat: an obvious vulnerability sits in a legacy module that DEPLOYMENT.md says is not deployed; the real
4
+ finding is a subtler one in deployed code. At level 3 there is no DEPLOYMENT.md: only the Dockerfile shows what
5
+ is deployed.
6
+ """
7
+
8
+ from ..base import Task, Tool, lower_keys, same_int
9
+
10
+ CWES = {"CWE-89": "SQL injection", "CWE-22": "path traversal", "CWE-78": "OS command injection",
11
+ "CWE-798": "hard-coded credentials", "CWE-862": "missing authorization"}
12
+
13
+ SAFE = {
14
+ "app/db.py": '''import sqlite3
15
+
16
+ DB = "app.db"
17
+
18
+
19
+ def get_user(user_id):
20
+ with sqlite3.connect(DB) as conn:
21
+ return conn.execute("SELECT id, name, email FROM users WHERE id = ?", (user_id,)).fetchone()
22
+
23
+
24
+ def search_orders(customer_id, status):
25
+ with sqlite3.connect(DB) as conn:
26
+ query = "SELECT id, total FROM orders WHERE customer_id = ? AND status = ?"
27
+ return conn.execute(query, (customer_id, status)).fetchall()
28
+ ''',
29
+ "app/files.py": '''import os
30
+
31
+ UPLOAD_ROOT = "/srv/uploads"
32
+
33
+
34
+ def read_upload(name):
35
+ path = os.path.realpath(os.path.join(UPLOAD_ROOT, name))
36
+ if not path.startswith(UPLOAD_ROOT + os.sep):
37
+ raise PermissionError("outside upload root")
38
+ with open(path, "rb") as fh:
39
+ return fh.read()
40
+ ''',
41
+ "app/tools.py": '''import subprocess
42
+
43
+
44
+ def ping(host):
45
+ if not host.replace(".", "").replace("-", "").isalnum():
46
+ raise ValueError("bad host")
47
+ return subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True).stdout
48
+ ''',
49
+ "app/config.py": '''import os
50
+
51
+ SECRET_KEY = os.environ["APP_SECRET_KEY"]
52
+ DB_PASSWORD = os.environ.get("DB_PASSWORD", "")
53
+ DEBUG = os.environ.get("DEBUG") == "1"
54
+ ''',
55
+ "app/routes.py": '''from app.audit import log_event
56
+ from app.auth import current_user, require_admin
57
+ from app.db import get_user, search_orders
58
+
59
+
60
+ @require_admin
61
+ def admin_user(request, user_id):
62
+ return get_user(user_id)
63
+
64
+
65
+ def my_orders(request):
66
+ user = current_user(request)
67
+ return search_orders(user.id, request.args.get("status", "open"))
68
+
69
+
70
+ def delete_account(request, user_id):
71
+ user = current_user(request)
72
+ if user.id != user_id and not user.is_admin:
73
+ raise PermissionError("forbidden")
74
+ log_event("delete_account", actor=user.id, target=user_id)
75
+ return {"deleted": user_id}
76
+ ''',
77
+ "app/auth.py": '''def current_user(request):
78
+ return request.session["user"]
79
+
80
+
81
+ def require_admin(view):
82
+ def wrapper(request, *args, **kwargs):
83
+ if not current_user(request).is_admin:
84
+ raise PermissionError("admin only")
85
+ return view(request, *args, **kwargs)
86
+ return wrapper
87
+ ''',
88
+ }
89
+
90
+ # (file, cwe, safe text, vulnerable text, index of the vulnerable line within the vulnerable text)
91
+ SUBTLE = [
92
+ ("app/db.py", "CWE-89", ''' query = "SELECT id, total FROM orders WHERE customer_id = ? AND status = ?"
93
+ return conn.execute(query, (customer_id, status)).fetchall()''',
94
+ ''' query = "SELECT id, total FROM orders WHERE customer_id = ? AND status = '%s'" % status
95
+ return conn.execute(query, (customer_id,)).fetchall()''', 0),
96
+ ("app/files.py", "CWE-22", ''' path = os.path.realpath(os.path.join(UPLOAD_ROOT, name))
97
+ if not path.startswith(UPLOAD_ROOT + os.sep):
98
+ raise PermissionError("outside upload root")''',
99
+ ''' path = os.path.join(UPLOAD_ROOT, name.replace("../", ""))
100
+ if not os.path.exists(path):
101
+ raise FileNotFoundError(name)''', 0),
102
+ ("app/tools.py", "CWE-78", ''' if not host.replace(".", "").replace("-", "").isalnum():
103
+ raise ValueError("bad host")
104
+ return subprocess.run(["ping", "-c", "1", host], capture_output=True, text=True).stdout''',
105
+ ''' if not host.strip():
106
+ raise ValueError("bad host")
107
+ return subprocess.run("ping -c 1 " + host, shell=True, capture_output=True, text=True).stdout''', 2),
108
+ ("app/config.py", "CWE-798", '''DB_PASSWORD = os.environ.get("DB_PASSWORD", "")''',
109
+ '''DB_PASSWORD = os.environ.get("DB_PASSWORD", "Spring2026!prod")''', 0),
110
+ ("app/routes.py", "CWE-862", ''' user = current_user(request)
111
+ if user.id != user_id and not user.is_admin:
112
+ raise PermissionError("forbidden")
113
+ log_event("delete_account", actor=user.id, target=user_id)''',
114
+ ''' user = current_user(request)
115
+ log_event("delete_account", actor=user.id, target=user_id)''', 1),
116
+ ]
117
+
118
+ LEGACY = {
119
+ "CWE-89": ("legacy/report_export.py", '''import sqlite3
120
+
121
+
122
+ def export_customer(conn, name):
123
+ rows = conn.execute(f"SELECT * FROM customers WHERE name = '{name}'").fetchall()
124
+ return [dict(r) for r in rows]
125
+ ''', 5),
126
+ "CWE-78": ("legacy/backup.py", '''import os
127
+
128
+
129
+ def backup(table):
130
+ os.system("pg_dump -t " + table + " > /tmp/backup.sql")
131
+ ''', 5),
132
+ "CWE-798": ("legacy/old_settings.py", '''ADMIN_USER = "admin"
133
+ ADMIN_PASSWORD = "admin123"
134
+ ''', 2),
135
+ }
136
+
137
+
138
+ class VulnHunt(Task):
139
+ family = "security-audit"
140
+ domain = "cybersecurity"
141
+ max_steps = 12
142
+ levels = (1, 2, 3)
143
+
144
+ def setup(self):
145
+ r = self.rng
146
+ fname, cwe, safe_text, bad_text, offset = r.choice(SUBTLE)
147
+ self.files = dict(SAFE)
148
+ body = self.files[fname]
149
+ assert safe_text in body
150
+ pad = "".join(f"\n\ndef _clean_{i}(value):\n return str(value).strip()\n" for i in range(r.randint(0, 3)))
151
+ head, tail = body.split(safe_text)
152
+ head = head.rstrip("\n").rsplit("\n\ndef ", 1)
153
+ head = head[0] + pad + "\n\ndef " + head[1] + "\n" if len(head) == 2 else head[0] + "\n"
154
+ self.files[fname] = head + bad_text + tail
155
+ lines = self.files[fname].split("\n")
156
+ self.truth = (fname, lines.index(bad_text.split("\n")[offset]) + 1, cwe)
157
+ legacy_cwe = r.choice([c for c in LEGACY if c != cwe])
158
+ lpath, lbody, lline = LEGACY[legacy_cwe]
159
+ self.files[lpath] = lbody
160
+ self.decoy = (lpath, lline, legacy_cwe)
161
+ if self.level < 3:
162
+ self.files["DEPLOYMENT.md"] = (
163
+ "# Deployment\n\nThe production image is built from `app/` only (see the Dockerfile's COPY line). "
164
+ "`legacy/` is kept for reference while the old reporting server is decommissioned; it is not deployed "
165
+ "and nothing imports it.\n")
166
+ self.files["Dockerfile"] = "FROM python:3.12-slim\nWORKDIR /srv\nCOPY app/ app/\nCMD [\"python\", \"-m\", \"app\"]\n"
167
+
168
+ def brief(self):
169
+ hint = " Only deployed code counts; check how the service is deployed." if self.level == 1 else ""
170
+ cwes = "; ".join(f"{k} {v}" for k, v in CWES.items())
171
+ return ("SECURITY. Review this Python web service and report the one vulnerability in the service as it "
172
+ f"runs in production.{hint} Submit {{\"finding\": {{\"file\": <path>, \"line\": <1-based line>, "
173
+ f"\"cwe\": <id>}}}} using one of: {cwes}.")
174
+
175
+ def tools(self):
176
+ return self.files_tools() + [
177
+ Tool("search", "find a substring in all files (shows file:line)", self._search, {"pattern": str}),
178
+ Tool("submit", "report the finding", self.grade, {"finding": dict}, final=True),
179
+ ]
180
+
181
+ def _read(self, a):
182
+ name = a["path"].strip().lstrip("./")
183
+ if name not in self.files:
184
+ return f"No file named {a['path']!r}. Files: {', '.join(sorted(self.files))}."
185
+ return "\n".join(f"{i:3d} {line}" for i, line in enumerate(self.files[name].split("\n"), 1))
186
+
187
+ def _search(self, a):
188
+ if not a["pattern"]:
189
+ return "pattern is empty"
190
+ hits = [f"{f}:{i}: {line.strip()}" for f, body in sorted(self.files.items())
191
+ for i, line in enumerate(body.split("\n"), 1) if a["pattern"] in line]
192
+ return "\n".join(hits[:40]) or "no matches"
193
+
194
+ def grade(self, a):
195
+ f = lower_keys(a.get("finding", {}))
196
+ path = str(f.get("file", "")).strip().lstrip("./")
197
+ cwe = (str(f.get("cwe", "")).strip().upper().split() or [""])[0].rstrip(":")
198
+ if path != self.truth[0] or cwe != self.truth[2]:
199
+ return 0.0
200
+ line = f.get("line")
201
+ return float(any(same_int(line, self.truth[1] + d) for d in (-1, 0, 1)))
202
+
203
+ def oracle(self):
204
+ return [{"tool": "read_file", "args": {"path": "DEPLOYMENT.md" if self.level < 3 else "Dockerfile"}},
205
+ {"tool": "read_file", "args": {"path": self.truth[0]}},
206
+ {"tool": "submit", "args": {"finding": {"file": self.truth[0], "line": self.truth[1], "cwe": self.truth[2]}}}]
207
+
208
+ def naive(self):
209
+ return [{"tool": "submit", "args": {"finding": {"file": self.decoy[0], "line": self.decoy[1], "cwe": self.decoy[2]}}}]
source/diligence/families/software.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Software engineering: fix a bug so the tests pass.
2
+
3
+ Caveat: the issue thread has a maintainer decision on an edge case that the visible tests don't cover; hidden
4
+ tests check it.
5
+ """
6
+
7
+ import ast
8
+ import re
9
+ import secrets
10
+
11
+ from .. import sandbox
12
+ from ..base import Task, Tool
13
+
14
+ MODULE_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,40}\.(py|md|txt)")
15
+
16
+ # Test asserts compare with _same instead of ==, so a "fix" that returns an object whose __eq__ always says yes
17
+ # cannot pass. _same accepts only exact built-in types and compares them with the built-in methods, which are
18
+ # bound before any repository code is imported.
19
+ SAME = """
20
+ def _make_same(_type=type, _len=len, _zip=zip, _all=all, _float=float, _int=int, _str=str, _bool=bool,
21
+ _none=type(None), _list=list, _tuple=tuple, _dict=dict):
22
+ scalars = (_int, _float, _str, _bool, _none)
23
+ def same(a, b):
24
+ ta, tb = _type(a), _type(b)
25
+ if ta is not tb:
26
+ if ta in (_int, _float) and tb in (_int, _float):
27
+ return _float.__eq__(_float(a), _float(b)) is True
28
+ return False
29
+ if ta is _list or ta is _tuple:
30
+ return _len(a) == _len(b) and _all(same(x, y) for x, y in _zip(a, b))
31
+ if ta is _dict:
32
+ return (_len(a) == _len(b) and _all(_type(k) in scalars and k in b and same(v, b[k]) for k, v in a.items()))
33
+ if ta in scalars:
34
+ return ta.__eq__(a, b) is True
35
+ return False
36
+ return same
37
+ _same = _make_same()
38
+ del _make_same
39
+ """
40
+
41
+
42
+ class _UseSame(ast.NodeTransformer):
43
+ def visit_Assert(self, node):
44
+ t = node.test
45
+ if isinstance(t, ast.Compare) and len(t.ops) == 1 and isinstance(t.ops[0], ast.Eq):
46
+ node.test = ast.Call(ast.Name("_same", ast.Load()), [t.left, t.comparators[0]], [])
47
+ return node
48
+
49
+
50
+ def harden(source: str) -> str:
51
+ return ast.unparse(ast.fix_missing_locations(_UseSame().visit(ast.parse(source))))
52
+
53
+ BUGS = [
54
+ {
55
+ "module": "pager.py",
56
+ "buggy": '''def paginate(items, page, per_page):
57
+ """Return the items on a 1-indexed page."""
58
+ if page < 1 or per_page < 1:
59
+ raise ValueError("page and per_page must be positive")
60
+ start = page * per_page
61
+ return items[start:start + per_page]
62
+ ''',
63
+ "fixed": '''def paginate(items, page, per_page):
64
+ """Return the items on a 1-indexed page."""
65
+ if page < 1 or per_page < 1:
66
+ raise ValueError("page and per_page must be positive")
67
+ start = (page - 1) * per_page
68
+ if items and start >= len(items):
69
+ raise IndexError("page out of range")
70
+ return items[start:start + per_page]
71
+ ''',
72
+ "naive": '''def paginate(items, page, per_page):
73
+ """Return the items on a 1-indexed page."""
74
+ if page < 1 or per_page < 1:
75
+ raise ValueError("page and per_page must be positive")
76
+ start = (page - 1) * per_page
77
+ return items[start:start + per_page]
78
+ ''',
79
+ "visible": '''from pager import paginate
80
+ items = list(range(1, {n}))
81
+ assert paginate(items, 1, {k}) == items[:{k}], paginate(items, 1, {k})
82
+ assert paginate(items, 2, {k}) == items[{k}:{k2}]
83
+ print("visible tests passed")
84
+ ''',
85
+ "hidden": '''from pager import paginate
86
+ items = list("abcdefghij")
87
+ assert paginate(items, 4, 3) == ["j"]
88
+ assert paginate([], 1, 5) == []
89
+ try:
90
+ paginate(items, 5, 3)
91
+ raise SystemExit("expected IndexError for a page past the end")
92
+ except IndexError:
93
+ pass
94
+ print("hidden tests passed")
95
+ ''',
96
+ "issue": "Users report that the first page of results is skipped: page 1 shows what should be page 2.",
97
+ "decision": "Decision on the edge case: asking for a page past the end of a non-empty list must raise "
98
+ "IndexError (the UI relies on it). An empty list still returns [] for page 1.",
99
+ },
100
+ {
101
+ "module": "durations.py",
102
+ "buggy": '''import re
103
+
104
+ UNITS = {"h": 3600, "m": 60}
105
+
106
+
107
+ def parse_duration(text):
108
+ """Parse strings like '1h30m', '45m' or '2h5m10s' into seconds."""
109
+ total = 0
110
+ for amount, unit in re.findall(r"(\\d+)([hms])", text.strip().lower()):
111
+ total += int(amount) * UNITS.get(unit, 0)
112
+ return total
113
+ ''',
114
+ "fixed": '''import re
115
+
116
+ UNITS = {"h": 3600, "m": 60, "s": 1}
117
+
118
+
119
+ def parse_duration(text):
120
+ """Parse strings like '1h30m', '45m' or '2h5m10s' into seconds."""
121
+ text = text.strip().lower()
122
+ if text.isdigit():
123
+ return int(text)
124
+ total = 0
125
+ for amount, unit in re.findall(r"(\\d+)([hms])", text):
126
+ total += int(amount) * UNITS.get(unit, 0)
127
+ return total
128
+ ''',
129
+ "naive": '''import re
130
+
131
+ UNITS = {"h": 3600, "m": 60, "s": 1}
132
+
133
+
134
+ def parse_duration(text):
135
+ """Parse strings like '1h30m', '45m' or '2h5m10s' into seconds."""
136
+ total = 0
137
+ for amount, unit in re.findall(r"(\\d+)([hms])", text.strip().lower()):
138
+ total += int(amount) * UNITS.get(unit, 0)
139
+ return total
140
+ ''',
141
+ "visible": '''from durations import parse_duration
142
+ assert parse_duration("{h}h{m}m") == {hm}
143
+ assert parse_duration("{m}m{s}s") == {ms}, parse_duration("{m}m{s}s")
144
+ print("visible tests passed")
145
+ ''',
146
+ "hidden": '''from durations import parse_duration
147
+ assert parse_duration("2H5M10S") == 7510
148
+ assert parse_duration("") == 0
149
+ assert parse_duration("90") == 90, "a bare number means seconds"
150
+ assert parse_duration(" 15 ") == 15
151
+ print("hidden tests passed")
152
+ ''',
153
+ "issue": "Durations with seconds come out too short, e.g. '1m30s' is parsed as 60 seconds.",
154
+ "decision": "Decision: a bare number with no unit (e.g. '90') means seconds. Old configs use that form.",
155
+ },
156
+ {
157
+ "module": "contacts.py",
158
+ "buggy": '''def dedupe_emails(emails):
159
+ """Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order."""
160
+ return list(set(e.strip() for e in emails))
161
+ ''',
162
+ "fixed": '''def dedupe_emails(emails):
163
+ """Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order."""
164
+ seen, out = set(), []
165
+ for e in emails:
166
+ key = e.strip().lower()
167
+ if key and key not in seen:
168
+ seen.add(key)
169
+ out.append(e.strip())
170
+ return out
171
+ ''',
172
+ "naive": '''def dedupe_emails(emails):
173
+ """Remove duplicate addresses, ignoring case and surrounding spaces; keep the first spelling, in order."""
174
+ seen, out = set(), []
175
+ for e in emails:
176
+ key = e.strip().lower()
177
+ if key not in seen:
178
+ seen.add(key)
179
+ out.append(e.strip())
180
+ return out
181
+ ''',
182
+ "visible": '''from contacts import dedupe_emails
183
+ got = dedupe_emails(["{a}@x.org", " {b}@y.com", "{A}@X.org", "{c}@z.net"])
184
+ assert got == ["{a}@x.org", "{b}@y.com", "{c}@z.net"], got
185
+ print("visible tests passed")
186
+ ''',
187
+ "hidden": '''from contacts import dedupe_emails
188
+ assert dedupe_emails([]) == []
189
+ assert dedupe_emails(["B@b.io", "a@a.io", "b@B.IO ", "A@a.io"]) == ["B@b.io", "a@a.io"]
190
+ assert dedupe_emails(["", "x@y.z", " "]) == ["x@y.z"], "blank entries are dropped"
191
+ print("hidden tests passed")
192
+ ''',
193
+ "issue": "The contact importer keeps duplicates that differ only in case, and the order of contacts gets scrambled.",
194
+ "decision": "Decision: blank or whitespace-only entries come from empty spreadsheet cells and must be dropped.",
195
+ },
196
+ {
197
+ "module": "smooth.py",
198
+ "buggy": '''def moving_average(values, window):
199
+ """Average of each full window of `window` consecutive values."""
200
+ if window < 1:
201
+ raise ValueError("window must be positive")
202
+ return [sum(values[i:i + window]) / window for i in range(len(values) - window)]
203
+ ''',
204
+ "fixed": '''def moving_average(values, window):
205
+ """Average of each full window of `window` consecutive values."""
206
+ if window < 1:
207
+ raise ValueError("window must be positive")
208
+ if window > len(values):
209
+ raise ValueError("window is longer than the series")
210
+ return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]
211
+ ''',
212
+ "naive": '''def moving_average(values, window):
213
+ """Average of each full window of `window` consecutive values."""
214
+ if window < 1:
215
+ raise ValueError("window must be positive")
216
+ return [sum(values[i:i + window]) / window for i in range(len(values) - window + 1)]
217
+ ''',
218
+ "visible": '''from smooth import moving_average
219
+ got = moving_average([{v}], 2)
220
+ assert got == {want}, got
221
+ print("visible tests passed")
222
+ ''',
223
+ "hidden": '''from smooth import moving_average
224
+ assert moving_average([5], 1) == [5]
225
+ assert moving_average([2, 4, 6], 3) == [4]
226
+ try:
227
+ moving_average([1, 2], 3)
228
+ raise SystemExit("expected ValueError when the window is longer than the series")
229
+ except ValueError:
230
+ pass
231
+ print("hidden tests passed")
232
+ ''',
233
+ "issue": "The smoothed series is always one point shorter than it should be.",
234
+ "decision": "Decision: a window longer than the series is a caller bug and must raise ValueError, not return [].",
235
+ },
236
+ {
237
+ "module": "pricing.py",
238
+ "buggy": '''TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)
239
+
240
+
241
+ def discounted_total(total):
242
+ """Apply the best discount tier whose minimum the order total reaches."""
243
+ for minimum, rate in TIERS:
244
+ if total > minimum:
245
+ return round(total * (1 - rate), 2)
246
+ return round(total, 2)
247
+ ''',
248
+ "fixed": '''TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)
249
+
250
+
251
+ def discounted_total(total):
252
+ """Apply the best discount tier whose minimum the order total reaches."""
253
+ if total < 0:
254
+ raise ValueError("order total cannot be negative")
255
+ for minimum, rate in TIERS:
256
+ if total >= minimum:
257
+ return round(total * (1 - rate), 2)
258
+ return round(total, 2)
259
+ ''',
260
+ "naive": '''TIERS = [(1000, 0.10), (500, 0.05)] # (minimum order total, discount)
261
+
262
+
263
+ def discounted_total(total):
264
+ """Apply the best discount tier whose minimum the order total reaches."""
265
+ for minimum, rate in TIERS:
266
+ if total >= minimum:
267
+ return round(total * (1 - rate), 2)
268
+ return round(total, 2)
269
+ ''',
270
+ "visible": '''from pricing import discounted_total
271
+ assert discounted_total({t}) == {tw}
272
+ assert discounted_total(500) == 475.0, discounted_total(500)
273
+ print("visible tests passed")
274
+ ''',
275
+ "hidden": '''from pricing import discounted_total
276
+ assert discounted_total(1000) == 900.0
277
+ assert discounted_total(499.99) == 499.99
278
+ try:
279
+ discounted_total(-5)
280
+ raise SystemExit("expected ValueError for a negative total")
281
+ except ValueError:
282
+ pass
283
+ print("hidden tests passed")
284
+ ''',
285
+ "issue": "Customers whose order total is exactly a tier minimum (for example 500.00) get no discount.",
286
+ "decision": "Decision: negative totals (refund rows that leak in) must raise ValueError.",
287
+ },
288
+ ]
289
+
290
+
291
+ class RepoFix(Task):
292
+ family = "software-repofix"
293
+ domain = "software-engineering"
294
+ max_steps = 12
295
+ levels = (1, 2, 3) # 3: the pointer to the discussion is in README.md, not in the issue
296
+
297
+ def setup(self):
298
+ r = self.rng
299
+ bug = BUGS[r.randrange(len(BUGS))]
300
+ n, k = r.randint(12, 30), r.randint(3, 5)
301
+ h, m, s = r.randint(1, 5), r.randint(1, 59), r.randint(1, 59)
302
+ a, b, c = r.choice(["ana", "li", "omar"]), r.choice(["kim", "raj"]), r.choice(["zoe", "ben"])
303
+ vals = [r.randint(1, 9) * 2 for _ in range(r.randint(4, 6))]
304
+ t = r.choice([1500, 2000, 1000.5])
305
+ fmt = dict(n=n, k=k, k2=2 * k, h=h, m=m, s=s, hm=h * 3600 + m * 60, ms=m * 60 + s, a=a, b=b, c=c,
306
+ A=a.upper(), v=", ".join(map(str, vals)),
307
+ want=[(vals[i] + vals[i + 1]) / 2 for i in range(len(vals) - 1)], t=t, tw=round(t * 0.9, 2))
308
+ self.bug, self.module, self.test_name = bug, bug["module"], "test_" + bug["module"]
309
+ reporter, maintainer = r.sample(["dkim", "a.osei", "pmartin", "jlu"], 2)
310
+ # v2's level 1 named the decisions file outright and was solved 11/12 times; level 1 now only mentions it
311
+ pointer = "\n\nThere is some discussion in issue_comments.md." if self.level == 1 else ""
312
+ self.files = {
313
+ self.module: bug["buggy"],
314
+ self.test_name: bug["visible"].format(**fmt),
315
+ "ISSUE.md": f"# Bug report (#{r.randint(100, 999)})\n\n{bug['issue']}\n\nFix the module, not the tests. "
316
+ f"run_tests runs the visible tests; the release check also runs extra tests.{pointer}\n",
317
+ "issue_comments.md": f"**{reporter}**: confirmed on main.\n\n**{maintainer}** (maintainer): "
318
+ f"{bug['decision']}\n\n**{reporter}**: thanks, makes sense.\n",
319
+ "README.md": f"# {self.module[:-3]}\n\nSmall utility module. Python 3.12, no dependencies.\n"
320
+ + ("\nMaintainers record edge-case decisions in the issue threads (issue_comments.md).\n"
321
+ if self.level == 3 else ""),
322
+ }
323
+ self.hidden = bug["hidden"]
324
+
325
+ def brief(self):
326
+ return ("SOFTWARE. A small Python repository has an open bug report. Fix the bug so the release check "
327
+ "passes, then submit. Files: " + ", ".join(sorted(self.files)) + ".")
328
+
329
+ def tools(self):
330
+ return self.files_tools() + [
331
+ Tool("write_file", "replace a file with new content (the whole file)", self._write,
332
+ {"path": str, "content": str}),
333
+ Tool("run_tests", "run the visible tests", lambda a: self._run(False)[1]),
334
+ Tool("submit", "submit your fix for the release check", self.grade, final=True),
335
+ ]
336
+
337
+ def _write(self, a):
338
+ path = a["path"].strip()
339
+ if path.startswith("./"):
340
+ path = path[2:]
341
+ if path.lower().startswith("test"):
342
+ return "Tests are read-only; fix the module instead."
343
+ if not MODULE_NAME.fullmatch(path):
344
+ return "write_file takes a plain file name in the repository root, e.g. " + repr(self.module) + "."
345
+ if not a["content"].strip():
346
+ return "write_file needs non-empty content."
347
+ self.files[path] = a["content"]
348
+ return f"Wrote {len(a['content'])} characters to {path}."
349
+
350
+ def _run(self, hidden):
351
+ # The runner prints a fresh random token only after every test script has finished, so code that exits
352
+ # early (sys.exit(0), os._exit(0)) cannot pass.
353
+ token = secrets.token_hex(16)
354
+ files = dict(self.files)
355
+ sources = [(self.test_name, harden(self.files[self.test_name]))]
356
+ if hidden: # the release tests never touch the disk
357
+ sources.append(("test_release.py", harden(self.hidden)))
358
+ # the runner holds hardened copies of the tests and deletes itself before any repository code is imported
359
+ files["_tests.py"] = ("import os as _os\n_os.remove(__file__)\n" + SAME
360
+ + f"_tests = {sources!r}\n"
361
+ "for _t, _src in _tests:\n"
362
+ " exec(compile(_src, _t, 'exec'), {'__name__': '__main__', '_same': _same})\n"
363
+ f"print({token!r})\n")
364
+ code, out = sandbox.run(files, "_tests.py")
365
+ passed = code == 0 and token in out
366
+ shown = out.replace(token, "").rstrip()
367
+ if code == 0 and not passed:
368
+ code = 1
369
+ shown += "\nThe tests did not run to completion."
370
+ return code, f"exit code {code}\n{shown}"
371
+
372
+ def grade(self, a):
373
+ if self._run(False)[0] != 0:
374
+ return 0.0
375
+ return float(self._run(True)[0] == 0)
376
+
377
+ def oracle(self):
378
+ return [{"tool": "read_file", "args": {"path": "issue_comments.md"}},
379
+ {"tool": "write_file", "args": {"path": self.module, "content": self.bug["fixed"]}},
380
+ {"tool": "submit", "args": {}}]
381
+
382
+ def naive(self):
383
+ return [{"tool": "write_file", "args": {"path": self.module, "content": self.bug["naive"]}},
384
+ {"tool": "submit", "args": {}}]
source/diligence/interface.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "list_dir", "files", "dir"],
16
+ "read_file": ["read_file", "open_file", "cat", "view_file", "show_file"],
17
+ "write_file": ["write_file", "save_file", "put_file", "replace_file"],
18
+ "run_tests": ["run_tests", "test", "pytest", "check_tests"],
19
+ "python": ["python", "run_python", "py", "exec_python"],
20
+ "sql": ["sql", "query", "run_sql", "db"],
21
+ "search": ["search", "grep", "find_text"],
22
+ "list_emails": ["list_emails", "inbox", "list_mail"],
23
+ "read_email": ["read_email", "open_email", "get_mail"],
24
+ "get_calendar": ["get_calendar", "calendar", "busy_times"],
25
+ "check_slot": ["check_slot", "conflicts", "check_time"],
26
+ "find_free_slots": ["find_free_slots", "free_slots", "availability"],
27
+ "create_event": ["create_event", "send_invite", "book_meeting"],
28
+ "show": ["show", "view", "display"],
29
+ "guide": ["guide", "style_guide", "rules"],
30
+ "set_line": ["set_line", "replace_line", "edit_line"],
31
+ "check": ["check", "lint", "style_check"],
32
+ }
33
+ ARG_NAMES = {
34
+ "path": ["path", "file", "filename"],
35
+ "code": ["code", "source", "script"],
36
+ "query": ["query", "statement", "sql"],
37
+ "pattern": ["pattern", "text", "needle"],
38
+ "email_id": ["email_id", "id", "message_id"],
39
+ "content": ["content", "text", "body"],
40
+ "person": ["person", "name", "who"],
41
+ "date": ["date", "day"],
42
+ "attendees": ["attendees", "people", "participants"],
43
+ "page": ["page", "number"],
44
+ "minutes": ["minutes", "duration", "length_min"],
45
+ "line": ["line", "line_number", "row"],
46
+ "text": ["text", "new_text", "replacement"],
47
+ }
48
+ # Names that are also ordinary words ("the style guide", "check how...") are renamed in the tool list but not in
49
+ # running text; the others are replaced wherever they appear as a word.
50
+ TEXT_SAFE = {name for name in TOOL_NAMES if "_" in name} | {"python"}
51
+
52
+
53
+ class Interface:
54
+ def __init__(self, tools: list[Tool], rng: random.Random):
55
+ self.tool_names, used = {}, {"submit"}
56
+ for tool in tools:
57
+ options = [n for n in TOOL_NAMES.get(tool.name, [tool.name]) if n not in used] or [tool.name]
58
+ name = tool.name if tool.name == "submit" else rng.choice(options)
59
+ used.add(name)
60
+ self.tool_names[tool.name] = name
61
+ pairs = [(old, new) for old, new in self.tool_names.items() if old in TEXT_SAFE and old != new]
62
+ self._pattern = re.compile(r"\b(" + "|".join(re.escape(old) for old, _ in pairs) + r")\b") if pairs else None
63
+ self._lookup = dict(pairs)
64
+ self.tools = [self._rename(tool, rng) for tool in tools]
65
+
66
+ def _rename(self, tool: Tool, rng: random.Random) -> Tool:
67
+ if tool.name == "submit":
68
+ return tool
69
+ args, used = {}, set()
70
+ for arg in tool.args:
71
+ options = [n for n in ARG_NAMES.get(arg, [arg]) if n not in used] or [arg]
72
+ args[arg] = rng.choice(options)
73
+ used.add(args[arg])
74
+ back = {new: old for old, new in args.items()}
75
+
76
+ def fn(a, _fn=tool.fn):
77
+ return _fn({back.get(k, k): v for k, v in a.items()})
78
+
79
+ return Tool(self.tool_names[tool.name], self.text(tool.help), fn,
80
+ {args[k]: t for k, t in tool.args.items()}, tuple(args[k] for k in tool.optional), tool.final)
81
+
82
+ def text(self, s: str) -> str:
83
+ """Rewrite canonical tool names in briefs and tool output to this episode's names."""
84
+ if not self._pattern or not isinstance(s, str):
85
+ return s
86
+ return self._pattern.sub(lambda m: self._lookup[m.group(1)], s)
source/diligence/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/diligence/sandbox.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run model-written Python over a task's files in a throwaway directory with resource limits.
2
+
3
+ When the server runs as root (as in the container), the code runs as the unprivileged `nobody` user, which cannot
4
+ read the server's own source (/app is root-only), so it cannot look up generators or hidden tests.
5
+ """
6
+
7
+ import os
8
+ import signal
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ from pathlib import Path
14
+
15
+ MAX_OUTPUT = 2000
16
+ MEMORY_BYTES = 1 << 30
17
+ CPU_SECONDS = 10
18
+ MAX_PROCESSES = 256 # per user, so this also bounds what parallel sandboxes can start
19
+ # at most this many sandboxes run at once, so parallel episodes stay inside the container's memory limit
20
+ _SLOTS = threading.BoundedSemaphore(3)
21
+ NOBODY = 65534
22
+ AS_ROOT = hasattr(os, "geteuid") and os.geteuid() == 0
23
+
24
+
25
+ def _limits():
26
+ try:
27
+ import resource
28
+ except ImportError:
29
+ return
30
+ for limit, value in [("RLIMIT_CPU", (CPU_SECONDS, CPU_SECONDS + 1)), ("RLIMIT_FSIZE", (10_000_000, 10_000_000)),
31
+ ("RLIMIT_AS", (MEMORY_BYTES, MEMORY_BYTES)), ("RLIMIT_NPROC", (MAX_PROCESSES, MAX_PROCESSES))]:
32
+ try:
33
+ resource.setrlimit(getattr(resource, limit), value)
34
+ except (AttributeError, ValueError, OSError): # not every platform supports every limit
35
+ pass
36
+
37
+
38
+ def _kill_group(proc):
39
+ try:
40
+ os.killpg(proc.pid, signal.SIGKILL)
41
+ except (ProcessLookupError, PermissionError):
42
+ pass
43
+
44
+
45
+ def _drain(stream, chunks, keep=65536):
46
+ """Read a pipe to the end, keeping only the first `keep` characters so endless output can't fill memory."""
47
+ kept = 0
48
+ while block := stream.read(8192):
49
+ if kept < keep:
50
+ chunks.append(block[:keep - kept])
51
+ kept += len(chunks[-1])
52
+
53
+
54
+ def run(files: dict[str, str], script: str, args: list[str] | None = None, timeout: int = 15) -> tuple[int, str]:
55
+ """Write `files` to a temp dir, run `script` (a file name in `files`) with Python, return (exit code, output)."""
56
+ with _SLOTS, tempfile.TemporaryDirectory() as tmp:
57
+ root = Path(tmp).resolve()
58
+ for name, body in files.items():
59
+ path = (root / name).resolve()
60
+ if root not in path.parents: # never write outside the workspace
61
+ continue
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ path.write_text(body)
64
+ # make the task's own modules importable even in isolated mode
65
+ (root / "_entry.py").write_text(
66
+ "import os, runpy, sys\nsys.path.insert(0, os.getcwd())\n"
67
+ f"runpy.run_path({script!r}, run_name='__main__')\n")
68
+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": tmp, "PYTHONDONTWRITEBYTECODE": "1"}
69
+ as_nobody = {}
70
+ if AS_ROOT:
71
+ try:
72
+ for dirpath, _, filenames in os.walk(root):
73
+ os.chown(dirpath, NOBODY, NOBODY)
74
+ for name in filenames:
75
+ os.chown(os.path.join(dirpath, name), NOBODY, NOBODY)
76
+ as_nobody = dict(user=NOBODY, group=NOBODY, extra_groups=[])
77
+ except PermissionError: # a runtime without CAP_CHOWN: run as the server's user instead
78
+ pass
79
+ # a new session, so the whole process group (including anything the code spawned) can be killed
80
+ popen = subprocess.Popen
81
+ if as_nobody:
82
+ def popen(*a, **k): # fall back to the server's user if switching users is not permitted here
83
+ try:
84
+ return subprocess.Popen(*a, **k)
85
+ except PermissionError:
86
+ for key in ("user", "group", "extra_groups"):
87
+ k.pop(key, None)
88
+ return subprocess.Popen(*a, **k)
89
+ proc = popen([sys.executable, "-I", "_entry.py", *(args or [])], cwd=root, env=env,
90
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
91
+ text=True, errors="replace", preexec_fn=_limits, start_new_session=True, **as_nobody)
92
+ chunks = []
93
+ reader = threading.Thread(target=_drain, args=(proc.stdout, chunks), daemon=True)
94
+ reader.start()
95
+ try:
96
+ proc.wait(timeout=timeout)
97
+ timed_out = False
98
+ except subprocess.TimeoutExpired:
99
+ timed_out = True
100
+ # stop the whole group, so background processes the code started neither linger nor hold the pipe open
101
+ _kill_group(proc)
102
+ proc.wait()
103
+ reader.join(2) # if something left the group and still holds the pipe, keep what has arrived and move on
104
+ out = "".join(chunks)
105
+ if timed_out:
106
+ return 124, f"timed out after {timeout} s"
107
+ if proc.returncode == -signal.SIGXCPU:
108
+ return 124, out + f"\nstopped: used more than {CPU_SECONDS} s of CPU time"
109
+ if len(out) > MAX_OUTPUT:
110
+ out = out[:MAX_OUTPUT] + f"\n... [{len(out) - MAX_OUTPUT} more characters]"
111
+ return proc.returncode, out
source/openenv.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ spec_version: 1
2
+ name: five_desks
3
+ version: 2.0.0
4
+ type: space
5
+ runtime: fastapi
6
+ app: server.app:app
7
+ port: 8000