edbeeching HF Staff commited on
Commit
71a3477
·
verified ·
1 Parent(s): c720920

Stage pinned Harbor pilot candidate

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 +304 -0
  2. manifest.json +0 -0
  3. tasks/abishekvashok--cmatrix.5c082c6/environment/Dockerfile +14 -0
  4. tasks/abishekvashok--cmatrix.5c082c6/instruction.md +101 -0
  5. tasks/abishekvashok--cmatrix.5c082c6/solution/solve.sh +33 -0
  6. tasks/abishekvashok--cmatrix.5c082c6/task.toml +86 -0
  7. tasks/abishekvashok--cmatrix.5c082c6/tests/Dockerfile +72 -0
  8. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/ATTRIBUTION.md +14 -0
  9. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/LICENSE +674 -0
  10. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/1b991a57d4e9.tar.gz +3 -0
  11. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/1d30a9bd67f8.tar.gz +3 -0
  12. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/28d2b640a014.tar.gz +3 -0
  13. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/2a51b65a0988.tar.gz +3 -0
  14. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/4325cb75f082.tar.gz +3 -0
  15. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/47e777b60c5e.tar.gz +3 -0
  16. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/60fce8bbb0c8.tar.gz +3 -0
  17. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/79b69dd3fd98.tar.gz +3 -0
  18. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/aa26a2ba3c36.tar.gz +3 -0
  19. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/b75df89939ed.tar.gz +3 -0
  20. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/bcaceaff5bda.tar.gz +3 -0
  21. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/c9a563c41e59.tar.gz +3 -0
  22. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/f40262460d4c.tar.gz +3 -0
  23. tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/f53d318371c8.tar.gz +3 -0
  24. tasks/abishekvashok--cmatrix.5c082c6/tests/programbench_evaluator.py +1192 -0
  25. tasks/abishekvashok--cmatrix.5c082c6/tests/programbench_task.json +0 -0
  26. tasks/abishekvashok--cmatrix.5c082c6/tests/test.sh +82 -0
  27. tasks/agourlay--zip-password-finder.704700d/environment/Dockerfile +14 -0
  28. tasks/agourlay--zip-password-finder.704700d/instruction.md +101 -0
  29. tasks/agourlay--zip-password-finder.704700d/solution/solve.sh +33 -0
  30. tasks/agourlay--zip-password-finder.704700d/task.toml +86 -0
  31. tasks/agourlay--zip-password-finder.704700d/tests/Dockerfile +72 -0
  32. tasks/agourlay--zip-password-finder.704700d/tests/blobs/ATTRIBUTION.md +12 -0
  33. tasks/agourlay--zip-password-finder.704700d/tests/blobs/LICENSE +176 -0
  34. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/045fa65d8a17.tar.gz +3 -0
  35. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/0a5ff17822b7.tar.gz +3 -0
  36. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/0df6b4d747de.tar.gz +3 -0
  37. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/15241b94c9bf.tar.gz +3 -0
  38. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/1fb751a1a8a1.tar.gz +3 -0
  39. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/220f03dff485.tar.gz +3 -0
  40. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/3001c1482b82.tar.gz +3 -0
  41. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/40a4c29f1824.tar.gz +3 -0
  42. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/63078964cd3f.tar.gz +3 -0
  43. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/644934f68973.tar.gz +3 -0
  44. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/a6516d59468d.tar.gz +3 -0
  45. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/c77d1fe5cef8.tar.gz +3 -0
  46. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/c865682e93ee.tar.gz +3 -0
  47. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/ec5f2f35f276.tar.gz +3 -0
  48. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/f2ad8ae32d40.tar.gz +3 -0
  49. tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/f83680a23703.tar.gz +3 -0
  50. tasks/agourlay--zip-password-finder.704700d/tests/programbench_evaluator.py +1192 -0
README.md ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: ProgramBench Harbor tasks (private staging)
3
+ tags:
4
+ - harbor
5
+ - code
6
+ - rl-environment
7
+ ---
8
+
9
+ # ProgramBench for Harbor — all 200 tasks
10
+
11
+ **Private candidate. Execution validation is incomplete.**
12
+
13
+ Generated from the official Harbor ProgramBench adapter. This is the complete
14
+ 200-task real-task split, excluding the upstream `testorg__` fixture. It is not a
15
+ new benchmark or a claim of score parity. `manifest.json` records pinned sources,
16
+ original IDs, adapter-normalized Harbor IDs, image references and every file hash.
17
+
18
+ Each `tasks/<id>/` contains instructions, task configuration, container definitions,
19
+ reference oracle and verifier, plus active hidden test archives and their upstream
20
+ LICENSE/ATTRIBUTION files. Component terms remain authoritative; no blanket license
21
+ is granted over third-party programs, images or tests. Container images remain on
22
+ their original registries; five tasks use mirrors selected by the official adapter.
23
+
24
+ Agents reconstruct programs from a reference binary and documentation. Agent
25
+ networking is allowlisted for model APIs; hidden tests belong only in the separate
26
+ verifier sandbox. Harbor transfers `/workspace` excluding `executable`. Do not mount
27
+ the entire dataset into the agent container. Oracle access measures harness wiring
28
+ and the reference ceiling, not agent capability.
29
+
30
+ Rewards preserve upstream `reward` (test pass rate), `resolved` (all tests pass),
31
+ and `almost_resolved` (at least 95%). Reference oracles can score below 1.0.
32
+ Scores below 0.9 warrant triage, not silent removal. Infrastructure failures must
33
+ be distinguished from legitimate unsuccessful submissions.
34
+
35
+ Requires Harbor with separate-verifier and phase-network-policy support (validated
36
+ against the project's Harbor 0.25.0 installation), Linux amd64 container execution,
37
+ and registry access. Default per-environment resources: 12 CPUs, 8192 MiB RAM,
38
+ 30720 MiB storage. Agent timeout: four hours. Verifier timeout: two hours, four
39
+ hours for the adapter's designated slow tasks. Bundled tests eliminate runtime Hub
40
+ test downloads; they do not eliminate image pulls, build dependencies or network
41
+ requirements of individual tests.
42
+
43
+ ## Loading
44
+
45
+ Use a pinned commit of `https://huggingface.co/datasets/edbeeching/programbench-harbor-staging`.
46
+ Authentication with read access is required. In Shepherd configuration:
47
+
48
+ ```yaml
49
+ task:
50
+ repo: https://huggingface.co/datasets/edbeeching/programbench-harbor-staging
51
+ revision: <commit-sha>
52
+ selector: wfxr--csview.8ac4de0
53
+ ```
54
+
55
+ Alternatively download the pinned repository with `huggingface_hub.snapshot_download`
56
+ and run Harbor against `tasks/<id>`. If transport loses executable bits, restore
57
+ the modes declared in `manifest.json`. Native Harbor Git downloads require Git LFS.
58
+
59
+ All 200 tasks receive static and download integrity checks. Runtime validation
60
+ targets the adapter's fixed six-task pilot; remaining tasks are not runtime-certified.
61
+ Runtime reports are supplied separately and tied to the exact candidate commit.
62
+ Docker validation and public redistribution review remain pending. No model runs
63
+ are included in this staging publication.
64
+
65
+ ## Source-code licenses
66
+
67
+ The following notices apply to the adapter/harness source. Task-specific test
68
+ licenses and image terms remain separate.
69
+
70
+ ### Harbor adapter (Apache-2.0)
71
+
72
+ ```text
73
+ Apache License
74
+ Version 2.0, January 2004
75
+ http://www.apache.org/licenses/
76
+
77
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
78
+
79
+ 1. Definitions.
80
+
81
+ "License" shall mean the terms and conditions for use, reproduction,
82
+ and distribution as defined by Sections 1 through 9 of this document.
83
+
84
+ "Licensor" shall mean the copyright owner or entity authorized by
85
+ the copyright owner that is granting the License.
86
+
87
+ "Legal Entity" shall mean the union of the acting entity and all
88
+ other entities that control, are controlled by, or are under common
89
+ control with that entity. For the purposes of this definition,
90
+ "control" means (i) the power, direct or indirect, to cause the
91
+ direction or management of such entity, whether by contract or
92
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
93
+ outstanding shares, or (iii) beneficial ownership of such entity.
94
+
95
+ "You" (or "Your") shall mean an individual or Legal Entity
96
+ exercising permissions granted by this License.
97
+
98
+ "Source" form shall mean the preferred form for making modifications,
99
+ including but not limited to software source code, documentation
100
+ source, and configuration files.
101
+
102
+ "Object" form shall mean any form resulting from mechanical
103
+ transformation or translation of a Source form, including but
104
+ not limited to compiled object code, generated documentation,
105
+ and conversions to other media types.
106
+
107
+ "Work" shall mean the work of authorship, whether in Source or
108
+ Object form, made available under the License, as indicated by a
109
+ copyright notice that is included in or attached to the work
110
+ (an example is provided in the Appendix below).
111
+
112
+ "Derivative Works" shall mean any work, whether in Source or Object
113
+ form, that is based on (or derived from) the Work and for which the
114
+ editorial revisions, annotations, elaborations, or other modifications
115
+ represent, as a whole, an original work of authorship. For the purposes
116
+ of this License, Derivative Works shall not include works that remain
117
+ separable from, or merely link (or bind by name) to the interfaces of,
118
+ the Work and Derivative Works thereof.
119
+
120
+ "Contribution" shall mean any work of authorship, including
121
+ the original version of the Work and any modifications or additions
122
+ to that Work or Derivative Works thereof, that is intentionally
123
+ submitted to Licensor for inclusion in the Work by the copyright owner
124
+ or by an individual or Legal Entity authorized to submit on behalf of
125
+ the copyright owner. For the purposes of this definition, "submitted"
126
+ means any form of electronic, verbal, or written communication sent
127
+ to the Licensor or its representatives, including but not limited to
128
+ communication on electronic mailing lists, source code control systems,
129
+ and issue tracking systems that are managed by, or on behalf of, the
130
+ Licensor for the purpose of discussing and improving the Work, but
131
+ excluding communication that is conspicuously marked or otherwise
132
+ designated in writing by the copyright owner as "Not a Contribution."
133
+
134
+ "Contributor" shall mean Licensor and any individual or Legal Entity
135
+ on behalf of whom a Contribution has been received by Licensor and
136
+ subsequently incorporated within the Work.
137
+
138
+ 2. Grant of Copyright License. Subject to the terms and conditions of
139
+ this License, each Contributor hereby grants to You a perpetual,
140
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
141
+ copyright license to reproduce, prepare Derivative Works of,
142
+ publicly display, publicly perform, sublicense, and distribute the
143
+ Work and such Derivative Works in Source or Object form.
144
+
145
+ 3. Grant of Patent License. Subject to the terms and conditions of
146
+ this License, each Contributor hereby grants to You a perpetual,
147
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
148
+ (except as stated in this section) patent license to make, have made,
149
+ use, offer to sell, sell, import, and otherwise transfer the Work,
150
+ where such license applies only to those patent claims licensable
151
+ by such Contributor that are necessarily infringed by their
152
+ Contribution(s) alone or by combination of their Contribution(s)
153
+ with the Work to which such Contribution(s) was submitted. If You
154
+ institute patent litigation against any entity (including a
155
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
156
+ or a Contribution incorporated within the Work constitutes direct
157
+ or contributory patent infringement, then any patent licenses
158
+ granted to You under this License for that Work shall terminate
159
+ as of the date such litigation is filed.
160
+
161
+ 4. Redistribution. You may reproduce and distribute copies of the
162
+ Work or Derivative Works thereof in any medium, with or without
163
+ modifications, and in Source or Object form, provided that You
164
+ meet the following conditions:
165
+
166
+ (a) You must give any other recipients of the Work or
167
+ Derivative Works a copy of this License; and
168
+
169
+ (b) You must cause any modified files to carry prominent notices
170
+ stating that You changed the files; and
171
+
172
+ (c) You must retain, in the Source form of any Derivative Works
173
+ that You distribute, all copyright, patent, trademark, and
174
+ attribution notices from the Source form of the Work,
175
+ excluding those notices that do not pertain to any part of
176
+ the Derivative Works; and
177
+
178
+ (d) If the Work includes a "NOTICE" text file as part of its
179
+ distribution, then any Derivative Works that You distribute must
180
+ include a readable copy of the attribution notices contained
181
+ within such NOTICE file, excluding those notices that do not
182
+ pertain to any part of the Derivative Works, in at least one
183
+ of the following places: within a NOTICE text file distributed
184
+ as part of the Derivative Works; within the Source form or
185
+ documentation, if provided along with the Derivative Works; or,
186
+ within a display generated by the Derivative Works, if and
187
+ wherever such third-party notices normally appear. The contents
188
+ of the NOTICE file are for informational purposes only and
189
+ do not modify the License. You may add Your own attribution
190
+ notices within Derivative Works that You distribute, alongside
191
+ or as an addendum to the NOTICE text from the Work, provided
192
+ that such additional attribution notices cannot be construed
193
+ as modifying the License.
194
+
195
+ You may add Your own copyright statement to Your modifications and
196
+ may provide additional or different license terms and conditions
197
+ for use, reproduction, or distribution of Your modifications, or
198
+ for any such Derivative Works as a whole, provided Your use,
199
+ reproduction, and distribution of the Work otherwise complies with
200
+ the conditions stated in this License.
201
+
202
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
203
+ any Contribution intentionally submitted for inclusion in the Work
204
+ by You to the Licensor shall be under the terms and conditions of
205
+ this License, without any additional terms or conditions.
206
+ Notwithstanding the above, nothing herein shall supersede or modify
207
+ the terms of any separate license agreement you may have executed
208
+ with Licensor regarding such Contributions.
209
+
210
+ 6. Trademarks. This License does not grant permission to use the trade
211
+ names, trademarks, service marks, or product names of the Licensor,
212
+ except as required for reasonable and customary use in describing the
213
+ origin of the Work and reproducing the content of the NOTICE file.
214
+
215
+ 7. Disclaimer of Warranty. Unless required by applicable law or
216
+ agreed to in writing, Licensor provides the Work (and each
217
+ Contributor provides its Contributions) on an "AS IS" BASIS,
218
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
219
+ implied, including, without limitation, any warranties or conditions
220
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
221
+ PARTICULAR PURPOSE. You are solely responsible for determining the
222
+ appropriateness of using or redistributing the Work and assume any
223
+ risks associated with Your exercise of permissions under this License.
224
+
225
+ 8. Limitation of Liability. In no event and under no legal theory,
226
+ whether in tort (including negligence), contract, or otherwise,
227
+ unless required by applicable law (such as deliberate and grossly
228
+ negligent acts) or agreed to in writing, shall any Contributor be
229
+ liable to You for damages, including any direct, indirect, special,
230
+ incidental, or consequential damages of any character arising as a
231
+ result of this License or out of the use or inability to use the
232
+ Work (including but not limited to damages for loss of goodwill,
233
+ work stoppage, computer failure or malfunction, or any and all
234
+ other commercial damages or losses), even if such Contributor
235
+ has been advised of the possibility of such damages.
236
+
237
+ 9. Accepting Warranty or Additional Liability. While redistributing
238
+ the Work or Derivative Works thereof, You may choose to offer,
239
+ and charge a fee for, acceptance of support, warranty, indemnity,
240
+ or other liability obligations and/or rights consistent with this
241
+ License. However, in accepting such obligations, You may act only
242
+ on Your own behalf and on Your sole responsibility, not on behalf
243
+ of any other Contributor, and only if You agree to indemnify,
244
+ defend, and hold each Contributor harmless for any liability
245
+ incurred by, or claims asserted against, such Contributor by reason
246
+ of your accepting any such warranty or additional liability.
247
+
248
+ END OF TERMS AND CONDITIONS
249
+
250
+ APPENDIX: How to apply the Apache License to your work.
251
+
252
+ To apply the Apache License to your work, attach the following
253
+ boilerplate notice, with the fields enclosed by brackets "[]"
254
+ replaced with your own identifying information. (Don't include
255
+ the brackets!) The text should be enclosed in the appropriate
256
+ comment syntax for the file format. We also recommend that a
257
+ file or class name and description of purpose be included on the
258
+ same "printed page" as the copyright notice for easier
259
+ identification within third-party archives.
260
+
261
+ Copyright [yyyy] [name of copyright owner]
262
+
263
+ Licensed under the Apache License, Version 2.0 (the "License");
264
+ you may not use this file except in compliance with the License.
265
+ You may obtain a copy of the License at
266
+
267
+ http://www.apache.org/licenses/LICENSE-2.0
268
+
269
+ Unless required by applicable law or agreed to in writing, software
270
+ distributed under the License is distributed on an "AS IS" BASIS,
271
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
272
+ See the License for the specific language governing permissions and
273
+ limitations under the License.
274
+
275
+ ```
276
+
277
+ ### ProgramBench harness (MIT)
278
+
279
+ ```text
280
+
281
+ MIT License
282
+
283
+ Copyright (c) Meta Platforms, Inc. and affiliates.
284
+
285
+ Permission is hereby granted, free of charge, to any person obtaining a copy
286
+ of this software and associated documentation files (the "Software"), to deal
287
+ in the Software without restriction, including without limitation the rights
288
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
289
+ copies of the Software, and to permit persons to whom the Software is
290
+ furnished to do so, subject to the following conditions:
291
+
292
+ The above copyright notice and this permission notice shall be included in all
293
+ copies or substantial portions of the Software.
294
+
295
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
296
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
297
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
298
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
299
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
300
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
301
+ SOFTWARE.
302
+
303
+ ```
304
+
manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/abishekvashok--cmatrix.5c082c6/environment/Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM programbench/abishekvashok_1776_cmatrix.5c082c6:task_cleanroom_v6
2
+
3
+ # Bake Harbor mini-swe-agent + uv at image build time (build has network) so the
4
+ # agent-phase allowlist can stay LLM-only instead of whitelisting installer CDNs.
5
+ COPY --from=ghcr.io/astral-sh/uv:0.7.13 /uv /uvx /usr/local/bin/
6
+
7
+ RUN python3 -m pip install --no-cache-dir --disable-pip-version-check \
8
+ 'huggingface-hub>=0.20' \
9
+ && uv tool install mini-swe-agent \
10
+ && if command -v mini-swe-agent >/dev/null 2>&1; then \
11
+ install -m 0755 "$(command -v mini-swe-agent)" /usr/local/bin/mini-swe-agent; \
12
+ fi
13
+
14
+ ENV PATH="/root/.local/bin:/usr/local/bin:${PATH}"
tasks/abishekvashok--cmatrix.5c082c6/instruction.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant that can interact with a computer.
2
+
3
+ This is a reverse-engineering benchmark. You are given a compiled binary and its documentation.
4
+ Your job is to write a new, original codebase from scratch that produces an executable with identical behavior.
5
+ You must figure out the behavior solely by running and interacting with the provided binary.
6
+ Writing original code based on observed behavior is the entire point of this benchmark.
7
+
8
+ Any approach that shortcuts this — finding existing source code, wrapping the binary,
9
+ or installing the original tool — does not count as a solution. It will be detected by an
10
+ automated judge, marked as a disqualification, and scored as a failure.
11
+ The trace will be posted to an online wall of shame.
12
+
13
+ <RULES>
14
+ ## What is not allowed
15
+
16
+ ### 1. Obtaining source code
17
+
18
+ The only source of truth about what the executable does is the executable itself and its
19
+ bundled documentation. You must not search the internet, package registries, or any external
20
+ source for information about this project's source code. Even if you recognize what the
21
+ executable is, you must reimplement it from behavioral observation alone.
22
+
23
+ This includes but is not limited to:
24
+ - Cloning or browsing the original GitHub repository, its forks, or mirrors
25
+ - Downloading the project from package registries: `cargo install <project>`, `go get github.com/<org>/<project>`, `pip install <project>`, `apt-get source <project>`, `npm install <project>`, etc.
26
+ - Fetching source tarballs from project websites (e.g., `curl https://lua.org/ftp/lua-5.5.0.tar.gz`)
27
+ - Using a package manager to download the project as a dependency and then reading its cached source (e.g., navigating into `~/.cargo/registry/src/` or `$(go env GOPATH)/pkg/mod/`)
28
+ - Searching the web for the project's source code or implementation details
29
+
30
+ ### 2. Wrapping or reusing the original binary
31
+
32
+ Your submission must be a genuine reimplementation. The provided `./executable` is for
33
+ observation only — your final solution must not depend on it or any other pre-built version
34
+ of the same tool at runtime.
35
+
36
+ This includes but is not limited to:
37
+ - Writing a wrapper script that delegates to the original binary (e.g., `exec zstd "$@"`)
38
+ - Installing the tool from a package manager and shimming to it (e.g., `apt-get install nnn && cp $(which nnn) ./executable`)
39
+ - Writing a `compile.sh` that simply makes the provided binary executable (`chmod +x ./executable`) or copies it (`cp ./executable ./executable`)
40
+ - Building a binary whose main function shells out to an external tool (e.g., `Command::new("miniserve").args(args).exec()`)
41
+ - Re-linking prebuilt `.o` object files found in the workspace without writing new source code
42
+
43
+ ### 3. Binary analysis of the provided executable
44
+
45
+ All information about the provided `./executable` must be obtained by interacting with it
46
+ through its normal user interface (CLI flags, stdin/stdout, etc.).
47
+ - You MUST NOT decompile `./executable` or use disassemblers (objdump, Ghidra, etc.) on it
48
+ - You MUST NOT use strace, ltrace, or similar tracing/instrumentation tools on `./executable`
49
+
50
+ Note: this restriction applies ONLY to the provided `./executable`. You are free to use any
51
+ analysis tools on binaries that you produce yourself during development.
52
+
53
+ ## What IS allowed
54
+
55
+ - Running the executable with any inputs, flags, and arguments to observe its behavior
56
+ - Reading any documentation files bundled in the workspace
57
+ </RULES>
58
+
59
+ ## Task context
60
+
61
+ We want to write the source code for a given executable.
62
+ The executable is located at `./executable` in the workspace root.
63
+
64
+ You also have access to the existing documentation.
65
+
66
+ ## Your task
67
+
68
+ Implement the source code to generate an executable of exactly identical behavior as the original.
69
+
70
+ No project-specific dependencies are pre-installed.
71
+ You do NOT have access to the internet.
72
+ **IMPORTANT**: Make sure that the executable(s) and everything else that is an artifact is not committed, i.e., is in your `.gitignore` file.
73
+ Finally, commit your changes.
74
+
75
+ Make sure that you have a `./compile.sh` file that produces an executable `./executable` in the workspace root.
76
+ `compile.sh` should be executable and should install any dependencies needed to compile the executable.
77
+ If your compile.sh fails to compile on a fresh checkout, your task has failed.
78
+
79
+ ## Important: This is a reverse-engineering benchmark
80
+
81
+ Your goal is to write original code from scratch that reproduces the executable's behavior.
82
+ The only way to learn what the executable does is to run it and read its bundled documentation.
83
+
84
+ Any attempt to obtain source code — whether successful or not — or to wrap/reuse the
85
+ provided binary will be detected by an automated judge, disqualified, and scored as zero.
86
+ See the full rules in the system prompt above. Key points:
87
+
88
+ - Do NOT search the internet, clone repos, or download the project from any package registry
89
+ - Do NOT wrap, shim, or delegate to the provided `./executable` or any installed version of the same tool
90
+ - Do NOT decompile the provided `./executable` or use strace/ltrace on it (analyzing your own binaries is fine)
91
+ - You SHOULD extensively test the executable to understand its behavior before writing code.
92
+ If you are dealing with a TUI, tmux/libtmux has been installed to help you test/inspect/it.
93
+
94
+ ## Recommended Workflow
95
+
96
+ 1. Explore all documentation files
97
+ 2. Play with the executable to understand its behavior (however, you MUST NOT decompile `./executable` or perform any other form of binary or strace/ltrace analysis on it)
98
+ 3. Write the source code to implement the behavior
99
+
100
+ Submit your changes and finish your work by issuing the following command: `echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT`.
101
+ Do not combine it with any other command. <important>After this command, you cannot continue working on this task.</important>
tasks/abishekvashok--cmatrix.5c082c6/solution/solve.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution. Encodes the cleanroom's reference ./executable in the
3
+ # handoff file so the raw-binary artifact filter and pre-compile hash scrub
4
+ # still run normally. compile.sh restores the reference after that scrub.
5
+ #
6
+ # Internal ceiling / diagnostics check — NOT a benchmark score.
7
+ set -euo pipefail
8
+ test -f ./executable
9
+ python3 - <<'PY'
10
+ import base64
11
+ from pathlib import Path
12
+
13
+ Path(".programbench_oracle_reference").write_bytes(
14
+ base64.b64encode(Path("executable").read_bytes())
15
+ )
16
+ PY
17
+ cat > compile.sh <<'EOF'
18
+ #!/usr/bin/env bash
19
+ set -euo pipefail
20
+ if [ -f ./.programbench_oracle_reference ]; then
21
+ python3 - <<'PY'
22
+ import base64
23
+ from pathlib import Path
24
+
25
+ Path("executable").write_bytes(
26
+ base64.b64decode(Path(".programbench_oracle_reference").read_bytes())
27
+ )
28
+ PY
29
+ fi
30
+ test -f ./executable
31
+ chmod +x ./executable
32
+ EOF
33
+ chmod +x compile.sh
tasks/abishekvashok--cmatrix.5c082c6/task.toml ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ source = "ProgramBench"
3
+
4
+ # Cleanroom images: generated tasks default to upstream ProgramBench v6
5
+ # (`programbench/*:task_cleanroom_v6`). Exceptions: tinycc, doxygen, revive, dirble,
6
+ # and chafa use `bencalvert04/*` until upstream ships fixes — see adapter
7
+ # `MIRROR_PATCHED_INSTANCE_IDS`.
8
+ # Agent phase uses network_mode = "allowlist" (cleanroom contract). Verifier runs in
9
+ # a separate sandbox (environment_mode = "separate") with default network for HF blobs.
10
+ # allowed_hosts is LLM APIs only; mini-swe-agent + uv are baked in environment/Dockerfile.
11
+ #
12
+ # Harness fixes (evaluator, verifier Dockerfile) live in task-template/tests/ and are
13
+ # copied into every generated task on `programbench-adapter --overwrite`.
14
+ #
15
+ # Two roles in this artifacts list:
16
+ # 1) trial outputs: /logs/verifier/* — collected from the verifier sandbox to the host
17
+ # 2) agent→verifier handoff: /workspace — copied from the agent sandbox to the
18
+ # verifier sandbox, with ./executable excluded so the reference binary cannot
19
+ # be passed across the boundary as a cheat. Hash-scrub inside the verifier
20
+ # remains a second-layer defense.
21
+ artifacts = [
22
+ "/logs/verifier/programbench_eval.json",
23
+ "/logs/verifier/harbor_diagnostics.json",
24
+ "/logs/verifier/programbench_eval.log",
25
+ "/logs/verifier/reward.json",
26
+ "/logs/verifier/reward.txt",
27
+ { source = "/workspace", exclude = ["executable"] },
28
+ ]
29
+
30
+ [task]
31
+ name = "programbench/abishekvashok--cmatrix.5c082c6"
32
+ description = "ProgramBench cleanroom reconstruction task for abishekvashok/cmatrix"
33
+ authors = [
34
+ { name = "John Yang" },
35
+ { name = "Kilian Lieret" },
36
+ ]
37
+ keywords = ["programbench", "reverse-engineering", "software-engineering", "cleanroom", "c"]
38
+
39
+ [metadata]
40
+ source = "ProgramBench"
41
+ instance_id = "abishekvashok__cmatrix.5c082c6"
42
+ repository = "abishekvashok/cmatrix"
43
+ commit = "5c082c64a1296859a11bee60c8c086655953a416"
44
+ language = "c"
45
+ difficulty = "easy"
46
+ task_image = "programbench/abishekvashok_1776_cmatrix.5c082c6:task_v6"
47
+ cleanroom_image = "programbench/abishekvashok_1776_cmatrix.5c082c6:task_cleanroom_v6"
48
+ test_branches = 14
49
+ test_count = 769
50
+
51
+ [agent]
52
+ timeout_sec = 14400
53
+ network_mode = "allowlist"
54
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
55
+
56
+ [verifier]
57
+ timeout_sec = 7200
58
+ user = "root"
59
+ environment_mode = "separate"
60
+
61
+ # Modal/gVisor has no real TTY; wrap pytest in ``script`` so terminal tools (chafa,
62
+ # tty-clock, felix, delta pagers, etc.) match Docker oracle behavior.
63
+ [verifier.env]
64
+ PROGRAMBENCH_SCRIPT_PTY = "1"
65
+
66
+ # Verifier image is built from tests/Dockerfile (no docker_image set), which
67
+ # starts FROM the cleanroom image and wipes /workspace so the reference
68
+ # binary baked into the image cannot survive into the verification phase.
69
+ [verifier.environment]
70
+ build_timeout_sec = 1800
71
+ cpus = 12
72
+ memory_mb = 8192
73
+ storage_mb = 30720
74
+ gpus = 0
75
+ workdir = "/workspace"
76
+
77
+ [environment]
78
+ docker_image = "programbench/abishekvashok_1776_cmatrix.5c082c6:task_cleanroom_v6"
79
+ network_mode = "allowlist"
80
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
81
+ build_timeout_sec = 1800
82
+ cpus = 12
83
+ memory_mb = 8192
84
+ storage_mb = 30720
85
+ gpus = 0
86
+ workdir = "/workspace"
tasks/abishekvashok--cmatrix.5c082c6/tests/Dockerfile ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Verifier image for programbench.
2
+ #
3
+ # Built from the cleanroom image so all toolchain / build dependencies the
4
+ # agent's compile.sh might need are present. The key difference from the
5
+ # agent image is that /workspace is wiped at image build time — the
6
+ # reference ./executable baked into the cleanroom image must NOT survive
7
+ # into the verification phase. The agent's submission arrives at /workspace
8
+ # at runtime via the artifact handoff (`artifacts = [{ source = "/workspace",
9
+ # exclude = ["executable"] }]` in task.toml), so even if the agent left the
10
+ # reference binary in their workspace, it is filtered out at the boundary.
11
+ #
12
+ # Defense-in-depth: programbench_evaluator.py still hash-scrubs files
13
+ # matching eval_clean_hashes inside the verifier sandbox.
14
+ FROM programbench/abishekvashok_1776_cmatrix.5c082c6:task_cleanroom_v6
15
+
16
+ # Wipe workspace contents — reference binary, any dev state — before this
17
+ # image is ever started as a verifier sandbox. The `.[!.]*` glob covers
18
+ # dotfiles while skipping `.` and `..`.
19
+ RUN rm -rf /workspace/* /workspace/.[!.]* 2>/dev/null || true \
20
+ && mkdir -p /workspace
21
+
22
+ # Cap pytest below 9.1 for everything pip installs in this verifier image —
23
+ # including each branch's `eval/run.sh`, some of which do
24
+ # `pip install --upgrade pytest`. pytest >=9.1 turns "mark applied to a
25
+ # fixture" into a hard error, which crashes collection whenever libtmux's
26
+ # autoloaded `pytest11` plugin (libtmux.pytest_plugin, present in many
27
+ # cleanroom images) is loaded — so no results.xml is produced and the branch
28
+ # reports `missing_results_xml` (reward 0). Because all branches share one
29
+ # verifier container and pip installs are container-global, a single upgrading
30
+ # branch would poison pytest for the whole task. PIP_CONSTRAINT is honored even
31
+ # by `--upgrade`, is a no-op for tasks that never upgrade, and keeps libtmux
32
+ # importable for tasks whose tests use it — so this is safe across the dataset.
33
+ RUN printf 'pytest<9.1\n' > /etc/pip-constraint.txt
34
+ ENV PIP_CONSTRAINT=/etc/pip-constraint.txt
35
+
36
+ # Ensure Go/Rust/Haskell toolchains stay on PATH for `bash -lc` (eval/run.sh).
37
+ # Login shells source /etc/profile, which can reset PATH and drop image ENV —
38
+ # observed on Modal/gVisor and some Docker exec paths.
39
+ RUN set -eu; \
40
+ paths=""; \
41
+ add_path() { if [ -d "$1" ]; then paths="${paths:+$paths:}$1"; fi; }; \
42
+ add_path /usr/local/go/bin; \
43
+ add_path /go/bin; \
44
+ add_path /usr/local/cargo/bin; \
45
+ add_path /root/.cargo/bin; \
46
+ add_path /root/.ghcup/bin; \
47
+ for d in /usr/lib/go-*/bin; do add_path "$d"; done; \
48
+ if [ -n "$paths" ]; then \
49
+ mkdir -p /etc/profile.d; \
50
+ printf 'export PATH="%s:${PATH}"\n' "$paths" > /etc/profile.d/programbench-toolchain.sh; \
51
+ fi
52
+ ENV PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
53
+
54
+ # Install verifier runtime dependencies. ``huggingface-hub`` is required when
55
+ # optional hidden-test blobs were intentionally omitted from the registry
56
+ # dataset: the evaluator then resolves them from Hugging Face at verify time.
57
+ # Best-effort: the cleanroom image may already have these packages.
58
+ RUN python3 -m pip install --no-cache-dir --disable-pip-version-check \
59
+ pytest pytest-rerunfailures huggingface-hub || true
60
+
61
+ # ``script`` provides a pseudo-TTY for Modal/gVisor (see PROGRAMBENCH_SCRIPT_PTY).
62
+ RUN command -v script >/dev/null 2>&1 || ( \
63
+ apt-get update && apt-get install -y --no-install-recommends bsdutils \
64
+ && rm -rf /var/lib/apt/lists/* \
65
+ )
66
+
67
+ # Copy the entire tests build context into /tests/ (test.sh,
68
+ # programbench_evaluator.py, programbench_task.json, optional blobs/).
69
+ # The Dockerfile itself is removed afterwards so it does not ship in the
70
+ # image's /tests/.
71
+ COPY . /tests/
72
+ RUN chmod +x /tests/test.sh && rm -f /tests/Dockerfile
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/ATTRIBUTION.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Attribution
2
+
3
+ The test files in this directory were generated by an AI model with access to
4
+ the source code and existing tests of the original repository listed below.
5
+ The generated tests may be inspired by or substantially similar to existing
6
+ tests in that repository. To the extent any portion of these test files
7
+ constitutes a derivative work of the original repository, the original
8
+ license terms apply to those portions.
9
+
10
+ ## Original Repository
11
+
12
+ - **Repository:** [abishekvashok/cmatrix](https://github.com/abishekvashok/cmatrix/tree/5c082c64a1296859a11bee60c8c086655953a416)
13
+ - **Commit:** `5c082c6`
14
+ - **License:** GPL-3.0
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/1b991a57d4e9.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:583cadbfd014c029efe817c73fd737fa449627d050289e54161ccead9f5f5b0c
3
+ size 214813
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/1d30a9bd67f8.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a036fcbd8bd37e560765d09bec85a58ccf78d0d63e9eedbe8032940f1770e1ef
3
+ size 214909
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/28d2b640a014.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa70eb49a0d52a5b33683b9cf229820bcf7764cae62b39bbb535846f485c6158
3
+ size 213046
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/2a51b65a0988.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d278db06463baa51e96d40b1028ad8106b74344efeb7889de2da8889f13e39a3
3
+ size 213891
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/4325cb75f082.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:046d8987b39268863efaaeebdac7cae9d522262eca7c1cd6c5805a60bb52dc7f
3
+ size 212598
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/47e777b60c5e.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cd8c03ce8387d841168fa38204a8783e53b165b4cd942a90049f7f20d983ebd
3
+ size 214095
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/60fce8bbb0c8.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f054d83cf39c7bb052588f1985daed79e20f534e64fb4d831e513228ff7b98f
3
+ size 220036
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/79b69dd3fd98.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4376a6c61ee69400345882aebd389a0abd6d0c5175ea002de7d08d66d3cdcc04
3
+ size 219765
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/aa26a2ba3c36.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df82b5fc767ae9fb3f85fd6223963f9a8490a546bb7e6f8e0ea5fc3fd9d6304d
3
+ size 211118
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/b75df89939ed.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4030409076828f4693008942c0fb7c184ccc17f031aa75b3c67ab05886149ea
3
+ size 214047
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/bcaceaff5bda.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9201caca146948273828f6722b1ce6a3c3bd348a09a76eec0a8fecd3c3446b37
3
+ size 214426
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/c9a563c41e59.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fc38efcf7f0422de4ad05e65fee08c9a3e9321cb97e6b70bc95d9dcb62aa48e
3
+ size 212053
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/f40262460d4c.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce302ef738c542da40c0edd9ba35f1ee9aabca4865331e16ff15c9f5a915e2a1
3
+ size 210899
tasks/abishekvashok--cmatrix.5c082c6/tests/blobs/tests/f53d318371c8.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf6fb8a882ad67eb98c87a8430f7d4d80c0ac8c9576aad75ec417726bc8959e0
3
+ size 210058
tasks/abishekvashok--cmatrix.5c082c6/tests/programbench_evaluator.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """In-place ProgramBench evaluator.
3
+
4
+ Mirrors ProgramBench's ``Evaluator`` pipeline as closely as a single-container,
5
+ no-Docker-in-Docker host allows. Run from ``tests/test.sh`` inside the agent's
6
+ cleanroom container after Harbor flips the verifier-phase network policy.
7
+
8
+ Differences from ``programbench.eval.eval.Evaluator`` that are structural to
9
+ running in one container:
10
+
11
+ * No fresh container per branch. ``snapshot_workspace`` / ``restore_workspace``
12
+ copy a post-compile workspace snapshot to a temp directory and restore it
13
+ before each branch; ``cleanup_lingering_processes`` kills leftover branch
14
+ processes between attempts to approximate the fresh-container boundary.
15
+ * No ``docker commit``. The post-compile workspace snapshot serves the same
16
+ role as the committed image upstream.
17
+ * Hidden test blobs are fetched on demand from HuggingFace via
18
+ ``huggingface_hub.snapshot_download`` (matching ``programbench.utils.blob_store``)
19
+ rather than being pre-staged into ``/tests/blobs/``. Override with
20
+ ``PROGRAMBENCH_BLOB_DIR`` for offline reruns.
21
+
22
+ Everything else (eval_clean_hashes scrub, deterministic synthetic git seed,
23
+ ``compile.sh`` then stash + hash the executable, best-effort
24
+ ``pytest-rerunfailures``, per-branch test-tar overlay, executable hash
25
+ ``--max-worker-restart=4``, xdist worker-crash retry with serial fallback,
26
+ best-of-N attempt selection, active vs ignored test bookkeeping, scoring) is
27
+ preserved.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shlex
37
+ import shutil
38
+ import signal
39
+ import subprocess
40
+ import tempfile
41
+ import time
42
+ import traceback
43
+ import xml.etree.ElementTree as ET
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ WORKSPACE = Path(os.environ.get("PROGRAMBENCH_WORKSPACE", "/workspace"))
48
+ STASHED_EXECUTABLE = Path("/opt/programbench-stashed-executable-do-not-modify")
49
+ METADATA_PATH = Path(
50
+ os.environ.get("PROGRAMBENCH_METADATA", "/tests/programbench_task.json")
51
+ )
52
+ LOG_DIR = Path(os.environ.get("PROGRAMBENCH_LOG_DIR", "/logs/verifier"))
53
+ WORKER_CRASH_PHRASE = "worker '"
54
+ XDIST_COLLAPSE_MARKERS = (
55
+ "maximum crashed workers reached",
56
+ "xdist: maximum crashed",
57
+ )
58
+ # Serial retry when a parallel attempt fails most tests — catches xdist fixture
59
+ # races on filesystem golden tests (e.g. dutree) without retrying every branch.
60
+ HIGH_FAILURE_SERIAL_RETRY_FRACTION = 0.5
61
+ HIGH_FAILURE_SERIAL_RETRY_MIN_TESTS = 8
62
+
63
+ DEFAULT_HF_REPO_ID = "programbench/ProgramBench-Tests"
64
+ DEFAULT_HF_REVISION = "main"
65
+
66
+ # Oracle agent handoff files (see solution/solve.sh). Must not appear in the
67
+ # post-compile workspace snapshot or they pollute tree-scanning tests (dutree).
68
+ _ORACLE_HANDOFF_NAMES = (".programbench_oracle_reference",)
69
+
70
+ _TOOLCHAIN_BIN_DIR_CANDIDATES = (
71
+ "/usr/local/go/bin",
72
+ "/go/bin",
73
+ "/usr/local/cargo/bin",
74
+ "/root/.cargo/bin",
75
+ "/root/.ghcup/bin",
76
+ )
77
+
78
+
79
+ def toolchain_bin_dirs() -> list[str]:
80
+ """Return toolchain bin directories that exist on this image."""
81
+ candidates = list(_TOOLCHAIN_BIN_DIR_CANDIDATES)
82
+ candidates.extend(
83
+ str(path) for path in sorted(Path("/usr/lib").glob("go-*/bin")) if path.is_dir()
84
+ )
85
+ seen: set[str] = set()
86
+ present: list[str] = []
87
+ for path in candidates:
88
+ if path in seen:
89
+ continue
90
+ seen.add(path)
91
+ if Path(path).is_dir():
92
+ present.append(path)
93
+ return present
94
+
95
+
96
+ def bootstrap_toolchain_path() -> str:
97
+ """Prepend discovered toolchain dirs to PATH (idempotent)."""
98
+ prepend = toolchain_bin_dirs()
99
+ current_parts = [part for part in os.environ.get("PATH", "").split(":") if part]
100
+ merged: list[str] = []
101
+ for path in prepend + current_parts:
102
+ if path not in merged:
103
+ merged.append(path)
104
+ new_path = ":".join(merged)
105
+ os.environ["PATH"] = new_path
106
+ return new_path
107
+
108
+
109
+ def _bash_login_command(command: str) -> str:
110
+ """Run ``command`` under bash -lc with an explicit PATH export."""
111
+ path = bootstrap_toolchain_path()
112
+ return f"export PATH={shlex.quote(path)}; {command}"
113
+
114
+
115
+ def sha256(path: Path) -> str:
116
+ h = hashlib.sha256()
117
+ with path.open("rb") as f:
118
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
119
+ h.update(chunk)
120
+ return h.hexdigest()
121
+
122
+
123
+ def write_json(path: Path, data: dict[str, Any]) -> None:
124
+ tmp = path.with_suffix(path.suffix + ".tmp")
125
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
126
+ tmp.replace(path)
127
+
128
+
129
+ def _read_log_tail(path: Path | None, max_bytes: int = 65536) -> str:
130
+ if path is None or not path.exists():
131
+ return ""
132
+ data = path.read_bytes()
133
+ if len(data) <= max_bytes:
134
+ return data.decode(errors="replace")
135
+ return data[-max_bytes:].decode(errors="replace")
136
+
137
+
138
+ def _close_pipes(proc: subprocess.Popen[Any]) -> None:
139
+ for stream in (proc.stdout, proc.stderr):
140
+ if stream is not None:
141
+ try:
142
+ stream.close()
143
+ except OSError:
144
+ pass
145
+
146
+
147
+ def _terminate_process_tree(proc: subprocess.Popen[Any]) -> None:
148
+ try:
149
+ os.killpg(proc.pid, signal.SIGKILL)
150
+ except ProcessLookupError:
151
+ pass
152
+ try:
153
+ proc.kill()
154
+ except ProcessLookupError:
155
+ pass
156
+
157
+
158
+ _PKILL_PATTERNS = (
159
+ f"{WORKSPACE}/eval/",
160
+ f"{WORKSPACE}/tests/",
161
+ "tail -f",
162
+ "development.log",
163
+ " less ",
164
+ " less$",
165
+ "/less ",
166
+ )
167
+
168
+
169
+ def _pkill_aggressive() -> str:
170
+ """Best-effort kill of branch pytest/subprocess trees (Modal gVisor fallback)."""
171
+ notes: list[str] = []
172
+ workspace = str(WORKSPACE)
173
+ patterns = list(_PKILL_PATTERNS) + [
174
+ f"pytest.*{workspace}",
175
+ f"xdist.*{workspace}",
176
+ ]
177
+ for pattern in patterns:
178
+ result = subprocess.run(
179
+ ["pkill", "-9", "-f", pattern],
180
+ capture_output=True,
181
+ text=True,
182
+ )
183
+ notes.append(f"pkill -9 -f {pattern!r}: rc={result.returncode}")
184
+ return "\n".join(notes)
185
+
186
+
187
+ def run_step(
188
+ command: str,
189
+ cwd: Path,
190
+ *,
191
+ timeout: int,
192
+ env: dict[str, str] | None = None,
193
+ step: str,
194
+ accept_failure: bool = False,
195
+ log_output: bool | None = None,
196
+ max_output_bytes: int = 65536,
197
+ ) -> dict[str, Any]:
198
+ if log_output is None:
199
+ log_output = step == "run_tests" or timeout >= 60
200
+
201
+ started = time.monotonic()
202
+ stdout_path: Path | None = None
203
+ stderr_path: Path | None = None
204
+ stdout_f = None
205
+ stderr_f = None
206
+
207
+ if log_output:
208
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
209
+ log_id = f"{step}-{int(started * 1000)}"
210
+ stdout_path = LOG_DIR / f"run-step-{log_id}.stdout.log"
211
+ stderr_path = LOG_DIR / f"run-step-{log_id}.stderr.log"
212
+ stdout_f = stdout_path.open("w", encoding="utf-8")
213
+ stderr_f = stderr_path.open("w", encoding="utf-8")
214
+ popen_stdout: Any = stdout_f
215
+ popen_stderr: Any = stderr_f
216
+ else:
217
+ popen_stdout = subprocess.PIPE
218
+ popen_stderr = subprocess.PIPE
219
+
220
+ proc = subprocess.Popen(
221
+ ["bash", "-lc", _bash_login_command(command)],
222
+ cwd=cwd,
223
+ env={**os.environ, **(env or {})},
224
+ stdout=popen_stdout,
225
+ stderr=popen_stderr,
226
+ start_new_session=True,
227
+ text=True,
228
+ )
229
+ timed_out = False
230
+ stdout = ""
231
+ stderr = ""
232
+ try:
233
+ if log_output:
234
+ proc.wait(timeout=timeout)
235
+ else:
236
+ stdout, stderr = proc.communicate(timeout=timeout)
237
+ except subprocess.TimeoutExpired:
238
+ timed_out = True
239
+ _terminate_process_tree(proc)
240
+ cleanup_lingering_processes(aggressive=True)
241
+ try:
242
+ proc.wait(timeout=5)
243
+ except subprocess.TimeoutExpired:
244
+ proc.kill()
245
+ if not log_output:
246
+ _close_pipes(proc)
247
+ finally:
248
+ if stdout_f is not None:
249
+ stdout_f.close()
250
+ if stderr_f is not None:
251
+ stderr_f.close()
252
+
253
+ if timed_out:
254
+ if log_output:
255
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
256
+ stderr_path, max_output_bytes
257
+ )
258
+ else:
259
+ output = ""
260
+ entry = {
261
+ "step": step,
262
+ "command": command,
263
+ "wall_time": time.monotonic() - started,
264
+ "output": output,
265
+ "returncode": 124,
266
+ "exception_info": f"timed out after {timeout}s",
267
+ }
268
+ else:
269
+ if log_output:
270
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
271
+ stderr_path, max_output_bytes
272
+ )
273
+ else:
274
+ output = stdout + stderr
275
+ entry = {
276
+ "step": step,
277
+ "command": command,
278
+ "wall_time": time.monotonic() - started,
279
+ "output": output,
280
+ "returncode": proc.returncode,
281
+ "exception_info": "",
282
+ }
283
+ if entry["returncode"] and not accept_failure:
284
+ raise RuntimeError(
285
+ f"{step} failed: {entry['exception_info'] or entry['output']}"
286
+ )
287
+ return entry
288
+
289
+
290
+ def cleanup_lingering_processes(*, aggressive: bool = False) -> dict[str, Any]:
291
+ started = time.monotonic()
292
+ patterns = [
293
+ str(WORKSPACE / "executable"),
294
+ f"{WORKSPACE}/eval/",
295
+ f"{WORKSPACE}/tests/",
296
+ # lazygit --logs/-l tests spawn `tail -f` outside /workspace/.
297
+ "tail -f",
298
+ "development.log",
299
+ ]
300
+ killed: list[int] = []
301
+ proc_root = Path("/proc")
302
+ proc_available = proc_root.exists()
303
+ if proc_available:
304
+ for proc_dir in proc_root.iterdir():
305
+ if not proc_dir.name.isdigit():
306
+ continue
307
+ pid = int(proc_dir.name)
308
+ if pid in {os.getpid(), os.getppid()}:
309
+ continue
310
+ try:
311
+ raw = (proc_dir / "cmdline").read_bytes()
312
+ except (FileNotFoundError, PermissionError, ProcessLookupError):
313
+ continue
314
+ cmdline = raw.replace(b"\0", b" ").decode(errors="replace")
315
+ if not any(pattern in cmdline for pattern in patterns):
316
+ continue
317
+ try:
318
+ os.kill(pid, signal.SIGKILL)
319
+ except (PermissionError, ProcessLookupError):
320
+ continue
321
+ killed.append(pid)
322
+ pkill_output = ""
323
+ if aggressive or not proc_available:
324
+ pkill_output = _pkill_aggressive()
325
+ output_parts = []
326
+ if killed:
327
+ output_parts.append("\n".join(str(pid) for pid in killed))
328
+ if pkill_output:
329
+ output_parts.append(pkill_output)
330
+ return {
331
+ "step": "cleanup_lingering_processes",
332
+ "command": "kill leftover branch processes referencing the workspace",
333
+ "wall_time": time.monotonic() - started,
334
+ "output": "\n".join(output_parts),
335
+ "returncode": 0,
336
+ "exception_info": "",
337
+ }
338
+
339
+
340
+ def extract_trusted_blob(tar_path: Path, dest: Path) -> None:
341
+ import tarfile
342
+
343
+ with tarfile.open(tar_path, "r:gz") as tf:
344
+ try:
345
+ tf.extractall(dest, filter="fully_trusted")
346
+ except TypeError:
347
+ tf.extractall(dest)
348
+
349
+
350
+ def find_results_xml() -> Path | None:
351
+ """Return the junit xml path if pytest wrote one."""
352
+ for candidate in (WORKSPACE / "eval" / "results.xml", WORKSPACE / "results.xml"):
353
+ if candidate.exists():
354
+ return candidate
355
+ return None
356
+
357
+
358
+ def remove_oracle_handoff_artifacts() -> list[str]:
359
+ """Drop oracle-agent handoff files from /workspace before snapshot/restore."""
360
+ removed: list[str] = []
361
+ for name in _ORACLE_HANDOFF_NAMES:
362
+ path = WORKSPACE / name
363
+ if path.exists():
364
+ if path.is_dir():
365
+ shutil.rmtree(path)
366
+ else:
367
+ path.unlink()
368
+ removed.append(name)
369
+ return removed
370
+
371
+
372
+ def _remove_tree(path: Path) -> None:
373
+ """Remove a file or directory tree, with a shell fallback for overlay races."""
374
+ if path.is_symlink() or path.is_file():
375
+ path.unlink(missing_ok=True)
376
+ return
377
+ if not path.is_dir():
378
+ path.unlink(missing_ok=True)
379
+ return
380
+ for attempt in range(3):
381
+ try:
382
+ shutil.rmtree(path)
383
+ if not path.exists():
384
+ return
385
+ except OSError:
386
+ if attempt == 2:
387
+ run_step(
388
+ f"rm -rf {shlex.quote(str(path))}",
389
+ path.parent,
390
+ timeout=120,
391
+ step="clear_workspace_fallback",
392
+ accept_failure=True,
393
+ )
394
+ if not path.exists():
395
+ return
396
+ raise
397
+
398
+
399
+ def ensure_workspace_dir() -> None:
400
+ """Guarantee WORKSPACE exists as a writable directory (not a symlink/file)."""
401
+ if WORKSPACE.exists() and not WORKSPACE.is_dir():
402
+ if WORKSPACE.is_symlink() or WORKSPACE.is_file():
403
+ WORKSPACE.unlink()
404
+ else:
405
+ shutil.rmtree(WORKSPACE)
406
+ WORKSPACE.mkdir(parents=True, exist_ok=True)
407
+
408
+
409
+ def clear_workspace() -> None:
410
+ ensure_workspace_dir()
411
+ for path in list(WORKSPACE.iterdir()):
412
+ _remove_tree(path)
413
+
414
+
415
+ def restore_reference_executable() -> None:
416
+ """Write the stashed reference binary into /workspace after a branch overlay.
417
+
418
+ Branch blobs may ship ``executable`` as a dangling symlink into
419
+ ``target/release/...``; ``shutil.copy2`` would follow it and raise
420
+ ``FileNotFoundError``. Drop whatever the blob left and copy the stashed
421
+ reference as a regular file.
422
+ """
423
+ ensure_workspace_dir()
424
+ if not STASHED_EXECUTABLE.is_file():
425
+ raise FileNotFoundError(
426
+ f"missing stashed reference executable at {STASHED_EXECUTABLE}"
427
+ )
428
+ dest = WORKSPACE / "executable"
429
+ if dest.exists() or dest.is_symlink():
430
+ if dest.is_dir():
431
+ shutil.rmtree(dest)
432
+ else:
433
+ dest.unlink(missing_ok=True)
434
+ shutil.copy2(STASHED_EXECUTABLE, dest)
435
+ dest.chmod(0o755)
436
+
437
+
438
+ def snapshot_workspace(dest: Path) -> None:
439
+ if dest.exists():
440
+ shutil.rmtree(dest)
441
+ shutil.copytree(WORKSPACE, dest, symlinks=True)
442
+
443
+
444
+ def restore_workspace(source: Path) -> None:
445
+ clear_workspace()
446
+ shutil.copytree(source, WORKSPACE, dirs_exist_ok=True, symlinks=True)
447
+ ensure_workspace_dir()
448
+
449
+
450
+ def remove_hashed_files(root: Path, hashes: set[str]) -> list[str]:
451
+ removed: list[str] = []
452
+ for path in root.rglob("*"):
453
+ if path.is_file() and not path.is_symlink():
454
+ try:
455
+ if sha256(path) in hashes:
456
+ path.unlink()
457
+ removed.append(str(path.relative_to(root)))
458
+ except OSError:
459
+ continue
460
+ return removed
461
+
462
+
463
+ def branch_tests(branch_info: dict[str, Any]) -> list[str]:
464
+ ignored = {
465
+ item["name"] for item in branch_info.get("ignored_tests", []) if "name" in item
466
+ }
467
+ return [name for name in branch_info.get("tests", []) if name not in ignored]
468
+
469
+
470
+ def ignored_tests(metadata: dict[str, Any]) -> set[str]:
471
+ result: set[str] = set()
472
+ for branch, info in metadata.get("branches", {}).items():
473
+ result.update(
474
+ f"{branch}/{item['name']}"
475
+ for item in info.get("ignored_tests", [])
476
+ if "name" in item
477
+ )
478
+ return result
479
+
480
+
481
+ def active_tests(metadata: dict[str, Any]) -> set[str]:
482
+ active: set[str] = set()
483
+ for branch, info in metadata.get("branches", {}).items():
484
+ if info.get("ignored"):
485
+ continue
486
+ ignored = {
487
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
488
+ }
489
+ active.update(
490
+ f"{branch}/{name}" for name in info.get("tests", []) if name not in ignored
491
+ )
492
+ return active
493
+
494
+
495
+ def inject_not_run(
496
+ result: dict[str, Any], branch: str, tests: list[str], error_code: str
497
+ ) -> None:
498
+ result["test_results"].extend(
499
+ {
500
+ "name": name,
501
+ "branch": branch,
502
+ "status": "not_run",
503
+ "extra": {"error_code": error_code},
504
+ }
505
+ for name in tests
506
+ )
507
+
508
+
509
+ def testcase_name(case: ET.Element) -> str:
510
+ classname = case.attrib.get("classname", "")
511
+ name = case.attrib.get("name", "")
512
+ return f"{classname}.{name}" if classname else name
513
+
514
+
515
+ # Only these tags under <testcase> represent a result. <system-out> /
516
+ # <system-err> are stdout/stderr captures and must not be treated as results
517
+ # (a leading <system-out> followed by <failure> would otherwise be classified
518
+ # as a stdout-only "passed").
519
+ JUNIT_RESULT_TAGS = {"skipped", "failure", "error"}
520
+
521
+
522
+ def parse_junit(
523
+ raw_xml: str, branch: str, expected: list[str], ignored: set[str]
524
+ ) -> tuple[list[dict[str, Any]], list[str]]:
525
+ root = ET.fromstring(raw_xml)
526
+ got: set[str] = set()
527
+ results: list[dict[str, Any]] = []
528
+ for case in root.iter("testcase"):
529
+ name = testcase_name(case)
530
+ got.add(name)
531
+ extra: dict[str, Any] = {}
532
+ if "time" in case.attrib:
533
+ try:
534
+ extra["time"] = float(case.attrib["time"])
535
+ except ValueError:
536
+ extra["time"] = case.attrib["time"]
537
+ result_children = [c for c in case if c.tag in JUNIT_RESULT_TAGS]
538
+ # Collapse duplicate same-tag result children. Pytest's
539
+ # "pytest.internal" pseudo-test sometimes emits two identical <error>
540
+ # entries; treating that as a system_error would over-flag a real
541
+ # single failure. Mirrors upstream eval.py:816-820.
542
+ if len(result_children) > 1 and len({c.tag for c in result_children}) == 1:
543
+ result_children = [result_children[0]]
544
+ if not result_children:
545
+ status = "passed"
546
+ elif len(result_children) != 1:
547
+ status = "system_error"
548
+ extra["error_details"] = (
549
+ f"Expected 1 result for {name}, got {len(result_children)}: "
550
+ f"{[c.tag for c in result_children]}"
551
+ )
552
+ else:
553
+ first = result_children[0]
554
+ status = first.tag # "skipped" | "failure" | "error"
555
+ extra["message"] = first.attrib.get("message") or ""
556
+ if first.text:
557
+ extra["text"] = first.text
558
+ results.append(
559
+ {"name": name, "branch": branch, "status": status, "extra": extra}
560
+ )
561
+
562
+ active_expected = [name for name in expected if name not in ignored]
563
+ missing = [name for name in active_expected if name not in got]
564
+ results.extend(
565
+ {
566
+ "name": name,
567
+ "branch": branch,
568
+ "status": "not_run",
569
+ "extra": {"error_code": "missing_from_junit_xml"},
570
+ }
571
+ for name in missing
572
+ )
573
+ unexpected = got - set(expected) - ignored
574
+ warnings = (
575
+ [f"Branch {branch}: {len(unexpected)} test(s) in JUnit XML not in tests.json"]
576
+ if unexpected
577
+ else []
578
+ )
579
+ return results, warnings
580
+
581
+
582
+ def count_worker_crashes(raw_xml: str) -> int:
583
+ if WORKER_CRASH_PHRASE not in raw_xml:
584
+ return 0
585
+ try:
586
+ root = ET.fromstring(raw_xml)
587
+ except ET.ParseError:
588
+ return 0
589
+ crashes = 0
590
+ for case in root.iter("testcase"):
591
+ for child in case:
592
+ text = (child.get("message") or "") + " " + (child.text or "")
593
+ if (
594
+ child.tag in {"error", "failure"}
595
+ and WORKER_CRASH_PHRASE in text
596
+ and "crashed" in text
597
+ ):
598
+ crashes += 1
599
+ break
600
+ return crashes
601
+
602
+
603
+ def run_output_indicates_xdist_collapse(output: str) -> bool:
604
+ lower = output.lower()
605
+ return any(marker in lower for marker in XDIST_COLLAPSE_MARKERS)
606
+
607
+
608
+ def count_junit_failures(raw_xml: str) -> int:
609
+ try:
610
+ root = ET.fromstring(raw_xml)
611
+ except ET.ParseError:
612
+ return 0
613
+ failures = 0
614
+ for case in root.iter("testcase"):
615
+ for child in case:
616
+ if child.tag in {"failure", "error"}:
617
+ failures += 1
618
+ break
619
+ return failures
620
+
621
+
622
+ def count_junit_passed(raw_xml: str) -> int:
623
+ try:
624
+ root = ET.fromstring(raw_xml)
625
+ except ET.ParseError:
626
+ return 0
627
+ passed = 0
628
+ for case in root.iter("testcase"):
629
+ if not any(child.tag in JUNIT_RESULT_TAGS for child in case):
630
+ passed += 1
631
+ return passed
632
+
633
+
634
+ def branch_attempt_metrics(
635
+ raw_xml: str, *, run_output: str, expected_tests: int
636
+ ) -> tuple[int, int, int, int]:
637
+ """Return (crashes, n_testcases, failures, missing_from_xml)."""
638
+ crashes = count_worker_crashes(raw_xml)
639
+ if run_output_indicates_xdist_collapse(run_output):
640
+ crashes = max(crashes, 1)
641
+ n_tests = count_testcases(raw_xml)
642
+ failures = count_junit_failures(raw_xml)
643
+ missing = max(0, expected_tests - n_tests)
644
+ return crashes, n_tests, failures, missing
645
+
646
+
647
+ def needs_serial_retry(
648
+ *,
649
+ serial: bool,
650
+ crashes: int,
651
+ missing: int,
652
+ failures: int,
653
+ n_tests: int,
654
+ expected_tests: int,
655
+ run_output: str,
656
+ ) -> bool:
657
+ if crashes > 0 or missing > 0 or run_output_indicates_xdist_collapse(run_output):
658
+ return True
659
+ if serial:
660
+ return False
661
+ if expected_tests < HIGH_FAILURE_SERIAL_RETRY_MIN_TESTS or n_tests == 0:
662
+ return False
663
+ return failures / n_tests >= HIGH_FAILURE_SERIAL_RETRY_FRACTION
664
+
665
+
666
+ def count_testcases(raw_xml: str) -> int:
667
+ try:
668
+ return sum(1 for _ in ET.fromstring(raw_xml).iter("testcase"))
669
+ except ET.ParseError:
670
+ return 0
671
+
672
+
673
+ def scored_results(
674
+ result: dict[str, Any], metadata: dict[str, Any]
675
+ ) -> list[dict[str, Any]]:
676
+ active = active_tests(metadata)
677
+ by_key = {
678
+ f"{test['branch']}/{test['name']}": test
679
+ for test in result["test_results"]
680
+ if f"{test['branch']}/{test['name']}" in active
681
+ }
682
+ return [
683
+ by_key.get(
684
+ key,
685
+ {
686
+ "branch": key.split("/", 1)[0],
687
+ "name": key.split("/", 1)[1],
688
+ "status": "not_run",
689
+ "extra": {"error_code": "missing_from_results"},
690
+ },
691
+ )
692
+ for key in sorted(active)
693
+ ]
694
+
695
+
696
+ def summarize(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
697
+ scored = scored_results(result, metadata)
698
+ n_passed = sum(t["status"] == "passed" for t in scored)
699
+ n_tests = len(scored)
700
+ pass_rate = n_passed / n_tests if n_tests else 0.0
701
+ # Multi-key reward: Harbor's default Mean aggregates each key independently
702
+ # (see harbor.metrics.base.aggregate_reward_dicts), so mean("resolved") is
703
+ # the proportion of tasks scoring a perfect pass-rate and mean of
704
+ # "almost_resolved" is the proportion scoring >= 0.95. "reward" stays the
705
+ # per-task pass-rate whose mean is the overall mean reward.
706
+ return {
707
+ "reward": pass_rate,
708
+ "resolved": 1.0 if pass_rate >= 1.0 else 0.0,
709
+ "almost_resolved": 1.0 if pass_rate >= 0.95 else 0.0,
710
+ }
711
+
712
+
713
+ def diagnostics(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
714
+ scored = scored_results(result, metadata)
715
+ n_passed = sum(t["status"] == "passed" for t in scored)
716
+ n_tests = len(scored)
717
+ pass_rate = n_passed / n_tests if n_tests else 0.0
718
+ return {
719
+ "pass_rate": pass_rate,
720
+ "resolved": int(
721
+ bool(
722
+ n_tests
723
+ and n_passed == n_tests
724
+ and not result["test_branch_errors"]
725
+ and not result["error_code"]
726
+ )
727
+ ),
728
+ "n_passed": n_passed,
729
+ "n_tests": n_tests,
730
+ "n_branch_errors": len(result["test_branch_errors"]),
731
+ "infra_error": int(bool(result["error_code"] or result["test_branch_errors"])),
732
+ "executable_hash_present": int(bool(result.get("executable_hash"))),
733
+ }
734
+
735
+
736
+ def use_script_pty() -> bool:
737
+ return os.environ.get("PROGRAMBENCH_SCRIPT_PTY", "").strip() == "1"
738
+
739
+
740
+ def script_pty_available() -> bool:
741
+ return shutil.which("script") is not None
742
+
743
+
744
+ def branch_env(
745
+ *,
746
+ serial: bool,
747
+ has_rerunfailures: bool,
748
+ extras: dict[str, str] | None = None,
749
+ ) -> dict[str, str]:
750
+ addopts = ["--max-worker-restart=4"]
751
+ if has_rerunfailures:
752
+ addopts.extend(["--reruns=2", "--reruns-delay=1"])
753
+ env = {
754
+ "PYTEST_ADDOPTS": " ".join(addopts),
755
+ # Match upstream non-TTY regression environments (dirble log format, etc.).
756
+ "NO_COLOR": "1",
757
+ "TERM": "dumb",
758
+ "CLICOLOR": "0",
759
+ "CLICOLOR_FORCE": "0",
760
+ "COLORTERM": "",
761
+ }
762
+ if extras:
763
+ env.update(extras)
764
+ xdist_workers = os.environ.get("PROGRAMBENCH_XDIST_WORKERS")
765
+ if serial:
766
+ xdist_workers = "1"
767
+ if xdist_workers:
768
+ env["PYTEST_XDIST_AUTO_NUM_WORKERS"] = xdist_workers
769
+ return env
770
+
771
+
772
+ _SERIAL_RUN_SH = ".programbench_run_serial.sh"
773
+ # ``eval/run.sh`` usually passes ``-n auto`` on the command line, which overrides
774
+ # ``PYTEST_ADDOPTS``. Rewrite to ``-n 0`` in a verifier-local copy for retries.
775
+ _RUN_SH_XDIST_RE = re.compile(r"-n\s*(?:auto|\d+)")
776
+
777
+
778
+ def prepare_serial_run_sh(run_sh: Path) -> Path:
779
+ """Write a serial-only copy of ``eval/run.sh`` with xdist disabled."""
780
+ serial_sh = run_sh.with_name(_SERIAL_RUN_SH)
781
+ patched = _RUN_SH_XDIST_RE.sub("-n 0", run_sh.read_text())
782
+ serial_sh.write_text(patched)
783
+ serial_sh.chmod(0o755)
784
+ return serial_sh
785
+
786
+
787
+ def run_tests_command(*, serial: bool) -> str:
788
+ if serial:
789
+ inner = f"chmod +x ./eval/{_SERIAL_RUN_SH} && ./eval/{_SERIAL_RUN_SH}"
790
+ else:
791
+ inner = "chmod +x ./eval/run.sh && ./eval/run.sh"
792
+ if use_script_pty() and script_pty_available():
793
+ return f"script -q -c {shlex.quote(inner)} /dev/null"
794
+ return inner
795
+
796
+
797
+ BAKED_BLOB_DIR = Path(os.environ.get("PROGRAMBENCH_BAKED_BLOB_DIR", "/tests/blobs"))
798
+
799
+
800
+ def resolve_blob_dir(instance_id: str, metadata: dict[str, Any]) -> Path:
801
+ """Locate the per-instance blob directory.
802
+
803
+ Resolution order:
804
+
805
+ 1. ``/tests/blobs/`` if pre-fetched into the task at generation time
806
+ (``programbench-adapter --download-blobs``). Verifier-only mount, so
807
+ agent never sees these.
808
+ 2. ``PROGRAMBENCH_BLOB_DIR`` env override pointing at an HF-cache-shaped
809
+ tree on disk (``<dir>/<instance_id>/tests/<branch>.tar.gz``). Useful
810
+ for offline reruns sharing a cache across many tasks.
811
+ 3. ``huggingface_hub.snapshot_download`` from
812
+ ``programbench/ProgramBench-Tests`` (default repo, ``main`` revision).
813
+
814
+ The returned directory contains ``tests/<branch>.tar.gz`` per active
815
+ branch — same shape as ``programbench/ProgramBench-Tests/<instance_id>/``
816
+ on HF.
817
+ """
818
+ if BAKED_BLOB_DIR.exists() and (BAKED_BLOB_DIR / "tests").exists():
819
+ return BAKED_BLOB_DIR
820
+
821
+ local = os.environ.get("PROGRAMBENCH_BLOB_DIR", "").strip()
822
+ if local:
823
+ candidate = Path(local) / instance_id
824
+ if candidate.exists():
825
+ return candidate
826
+ raise FileNotFoundError(
827
+ f"PROGRAMBENCH_BLOB_DIR set but {candidate} does not exist"
828
+ )
829
+
830
+ repo_id = os.environ.get("PROGRAMBENCH_HF_REPO") or metadata.get(
831
+ "hf_repo_id", DEFAULT_HF_REPO_ID
832
+ )
833
+ revision = os.environ.get("PROGRAMBENCH_HF_REVISION") or metadata.get(
834
+ "hf_revision", DEFAULT_HF_REVISION
835
+ )
836
+
837
+ from huggingface_hub import snapshot_download
838
+
839
+ cache_root = Path(
840
+ snapshot_download(
841
+ repo_id,
842
+ repo_type="dataset",
843
+ revision=revision,
844
+ allow_patterns=f"{instance_id}/**",
845
+ )
846
+ )
847
+ blob_dir = cache_root / instance_id
848
+ if not blob_dir.exists():
849
+ raise FileNotFoundError(
850
+ f"HF blob directory missing for {instance_id} at {blob_dir}"
851
+ )
852
+ return blob_dir
853
+
854
+
855
+ def evaluate(metadata: dict[str, Any]) -> dict[str, Any]:
856
+ bootstrap_toolchain_path()
857
+ branches = metadata.get("branches", {})
858
+ active_branch_items = [
859
+ (name, info) for name, info in branches.items() if not info.get("ignored")
860
+ ]
861
+ result: dict[str, Any] = {
862
+ "test_results": [],
863
+ "error_code": None,
864
+ "error_details": None,
865
+ "log": [],
866
+ "solution_branch": "submission",
867
+ "test_branches": [name for name, _ in active_branch_items],
868
+ "test_branch_errors": {},
869
+ "executable_hash": None,
870
+ "warnings": [],
871
+ }
872
+
873
+ instance_id = metadata["instance_id"]
874
+
875
+ compile_timeout = int(os.environ.get("PROGRAMBENCH_COMPILE_TIMEOUT", "900"))
876
+ branch_timeout = int(os.environ.get("PROGRAMBENCH_BRANCH_TIMEOUT", "3600"))
877
+ branch_retries_max = int(os.environ.get("PROGRAMBENCH_BRANCH_RETRIES", "2"))
878
+
879
+ def fail_all(error_code: str, details: str) -> dict[str, Any]:
880
+ result["error_code"] = error_code
881
+ result["error_details"] = details
882
+ for branch, info in active_branch_items:
883
+ inject_not_run(result, branch, branch_tests(info), error_code)
884
+ return result
885
+
886
+ with tempfile.TemporaryDirectory(prefix="programbench-eval-") as tmp:
887
+ compiled_snapshot = Path(tmp) / "compiled"
888
+
889
+ started = time.monotonic()
890
+ removed = remove_hashed_files(
891
+ WORKSPACE, set(metadata.get("eval_clean_hashes", []))
892
+ )
893
+ result["log"].append(
894
+ {
895
+ "step": "remove_hashed_files",
896
+ "command": "remove files matching eval_clean_hashes",
897
+ "wall_time": time.monotonic() - started,
898
+ "output": "".join(f"removed '{path}'\n" for path in removed),
899
+ "returncode": 0,
900
+ "exception_info": "",
901
+ }
902
+ )
903
+
904
+ compile_sh = WORKSPACE / "compile.sh"
905
+ if not compile_sh.exists():
906
+ return fail_all(
907
+ "missing_compile_sh", "submission did not contain compile.sh"
908
+ )
909
+
910
+ seed = (
911
+ "if [ ! -d .git ]; then "
912
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
913
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
914
+ "git -c init.defaultBranch=gold init -q && "
915
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false add -A && "
916
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
917
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
918
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false commit -q --allow-empty -m gold; "
919
+ "fi"
920
+ )
921
+ try:
922
+ result["log"].append(
923
+ run_step(seed, WORKSPACE, timeout=300, step="seed_git")
924
+ )
925
+ compile_log = run_step(
926
+ "chmod +x ./compile.sh && ./compile.sh",
927
+ WORKSPACE,
928
+ timeout=compile_timeout,
929
+ step="compile",
930
+ accept_failure=True,
931
+ )
932
+ result["log"].append(compile_log)
933
+ if compile_log["returncode"]:
934
+ return fail_all("compile_failed", compile_log["output"])
935
+ executable = WORKSPACE / "executable"
936
+ if not executable.exists():
937
+ return fail_all(
938
+ "missing_executable",
939
+ "compile.sh completed but did not create ./executable",
940
+ )
941
+ STASHED_EXECUTABLE.parent.mkdir(parents=True, exist_ok=True)
942
+ # `move` (not copy) so /workspace doesn't keep a parallel copy of
943
+ # the agent's executable during the stash→restore window. Mirrors
944
+ # upstream `mv ./executable {STASHED}` (eval.py:472).
945
+ shutil.move(str(executable), STASHED_EXECUTABLE)
946
+ result["executable_hash"] = sha256(STASHED_EXECUTABLE)
947
+ result["log"].append(
948
+ run_step(
949
+ "pip3 install -q --disable-pip-version-check pytest-rerunfailures",
950
+ WORKSPACE,
951
+ timeout=120,
952
+ step="install_rerunfailures",
953
+ accept_failure=True,
954
+ )
955
+ )
956
+ has_rerunfailures = result["log"][-1]["returncode"] == 0
957
+ handoff_removed = remove_oracle_handoff_artifacts()
958
+ if handoff_removed:
959
+ result["log"].append(
960
+ {
961
+ "step": "remove_oracle_handoff",
962
+ "command": "remove oracle handoff artifacts from workspace",
963
+ "wall_time": 0.0,
964
+ "output": "".join(
965
+ f"removed '{name}'\n" for name in handoff_removed
966
+ ),
967
+ "returncode": 0,
968
+ "exception_info": "",
969
+ }
970
+ )
971
+ snapshot_workspace(compiled_snapshot)
972
+ except Exception as exc:
973
+ return fail_all(type(exc).__name__, str(exc))
974
+
975
+ try:
976
+ blob_dir = resolve_blob_dir(instance_id, metadata)
977
+ except Exception as exc:
978
+ details = f"{type(exc).__name__}: {exc}"
979
+ for branch, info in active_branch_items:
980
+ result["test_branch_errors"][branch] = [
981
+ {
982
+ "error_code": "blob_resolution_failed",
983
+ "error_details": details,
984
+ }
985
+ ]
986
+ inject_not_run(
987
+ result, branch, branch_tests(info), "blob_resolution_failed"
988
+ )
989
+ return result
990
+
991
+ for branch, info in active_branch_items:
992
+ tests = branch_tests(info)
993
+ blob = blob_dir / "tests" / f"{branch}.tar.gz"
994
+ if not blob.exists():
995
+ result["test_branch_errors"][branch] = [
996
+ {"error_code": "missing_test_blob", "error_details": blob.name}
997
+ ]
998
+ inject_not_run(result, branch, tests, "missing_test_blob")
999
+ continue
1000
+
1001
+ best_xml = ""
1002
+ best_useful = -1
1003
+ attempts_left = branch_retries_max
1004
+ serial = bool(metadata.get("force_serial_branches"))
1005
+ branch_log: list[dict[str, Any]] = []
1006
+ # (crashes, n_testcases, failures) per attempt — early-exit when two
1007
+ # consecutive attempts are identical (deterministic failure, not
1008
+ # contention). Mirrors upstream eval.py:624.
1009
+ attempt_history: list[tuple[int, int, int]] = []
1010
+ branch_ignored = {
1011
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
1012
+ }
1013
+ n_expected = len([name for name in tests if name not in branch_ignored])
1014
+
1015
+ def merge_best_xml(raw_xml: str) -> None:
1016
+ try:
1017
+ parsed, warnings = parse_junit(
1018
+ raw_xml, branch, list(info.get("tests", [])), branch_ignored
1019
+ )
1020
+ except Exception as exc:
1021
+ result["test_branch_errors"][branch] = [
1022
+ {"error_code": "xml_parse_error", "error_details": str(exc)}
1023
+ ]
1024
+ inject_not_run(result, branch, tests, "xml_parse_error")
1025
+ else:
1026
+ result["test_results"].extend(parsed)
1027
+ result["warnings"].extend(warnings)
1028
+
1029
+ while True:
1030
+ branch_log.append(cleanup_lingering_processes())
1031
+ restore_workspace(compiled_snapshot)
1032
+ extract_trusted_blob(blob, WORKSPACE)
1033
+ restore_reference_executable()
1034
+ actual_hash = sha256(WORKSPACE / "executable")
1035
+ if actual_hash != result["executable_hash"]:
1036
+ result["test_branch_errors"][branch] = [
1037
+ {
1038
+ "error_code": "executable_hash_mismatch",
1039
+ "error_details": (
1040
+ f"expected {result['executable_hash']}, got {actual_hash}"
1041
+ ),
1042
+ }
1043
+ ]
1044
+ inject_not_run(result, branch, tests, "executable_hash_mismatch")
1045
+ break
1046
+ run_sh = WORKSPACE / "eval" / "run.sh"
1047
+ if not run_sh.exists():
1048
+ result["test_branch_errors"][branch] = [
1049
+ {
1050
+ "error_code": "missing_run_sh",
1051
+ "error_details": "eval/run.sh missing",
1052
+ }
1053
+ ]
1054
+ inject_not_run(result, branch, tests, "missing_run_sh")
1055
+ break
1056
+ # Upstream rewrites thread→signal so xdist workers fail cleanly
1057
+ # instead of os._exit(1) on timeout. That works in fresh
1058
+ # containers per branch; here we reuse one container and
1059
+ # signal timeouts leave TUI/log-watcher subprocesses alive
1060
+ # (e.g. lazygit --logs + tail -f), wedging pytest for up to
1061
+ # branch_timeout. Keep the blob's thread method and rely on
1062
+ # cleanup_lingering_processes + serial fallback after crashes.
1063
+ env = branch_env(
1064
+ serial=serial,
1065
+ has_rerunfailures=has_rerunfailures,
1066
+ extras=metadata.get("branch_env"),
1067
+ )
1068
+ branch_log.append(
1069
+ run_step(
1070
+ "rm -f eval/results.xml results.xml",
1071
+ WORKSPACE,
1072
+ timeout=120,
1073
+ step="clean_stale_results",
1074
+ accept_failure=True,
1075
+ )
1076
+ )
1077
+ if serial:
1078
+ prepare_serial_run_sh(run_sh)
1079
+ run_entry = run_step(
1080
+ run_tests_command(serial=serial),
1081
+ WORKSPACE,
1082
+ timeout=branch_timeout,
1083
+ env=env,
1084
+ step="run_tests",
1085
+ accept_failure=True,
1086
+ )
1087
+ branch_log.append(run_entry)
1088
+ branch_log.append(cleanup_lingering_processes())
1089
+ xml_path = find_results_xml()
1090
+ if xml_path is None:
1091
+ if best_xml:
1092
+ merge_best_xml(best_xml)
1093
+ break
1094
+ if attempts_left <= 0:
1095
+ result["test_branch_errors"][branch] = [
1096
+ {
1097
+ "error_code": "missing_results_xml",
1098
+ "error_details": "eval/results.xml was not produced",
1099
+ }
1100
+ ]
1101
+ inject_not_run(result, branch, tests, "missing_results_xml")
1102
+ break
1103
+ attempts_left -= 1
1104
+ serial = True
1105
+ continue
1106
+ raw_xml = xml_path.read_text(errors="replace")
1107
+ crashes, n_tests, failures, missing = branch_attempt_metrics(
1108
+ raw_xml,
1109
+ run_output=run_entry.get("output", ""),
1110
+ expected_tests=n_expected,
1111
+ )
1112
+ attempt_history.append((crashes, n_tests, failures))
1113
+ useful = count_junit_passed(raw_xml)
1114
+ if useful > best_useful:
1115
+ best_xml = raw_xml
1116
+ best_useful = useful
1117
+ deterministic = (
1118
+ len(attempt_history) >= 2
1119
+ and attempt_history[-1] == attempt_history[-2]
1120
+ )
1121
+ retry = needs_serial_retry(
1122
+ serial=serial,
1123
+ crashes=crashes,
1124
+ missing=missing,
1125
+ failures=failures,
1126
+ n_tests=n_tests,
1127
+ expected_tests=n_expected,
1128
+ run_output=run_entry.get("output", ""),
1129
+ )
1130
+ if not retry or attempts_left <= 0 or deterministic:
1131
+ merge_best_xml(best_xml)
1132
+ break
1133
+ attempts_left -= 1
1134
+ serial = True
1135
+ for entry in branch_log:
1136
+ entry["branch"] = branch
1137
+ result["log"].extend(branch_log)
1138
+
1139
+ return result
1140
+
1141
+
1142
+ def write_outputs(result: dict[str, Any], metadata: dict[str, Any]) -> None:
1143
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1144
+ write_json(LOG_DIR / "programbench_eval.json", result)
1145
+ write_json(LOG_DIR / "harbor_diagnostics.json", diagnostics(result, metadata))
1146
+ rewards = summarize(result, metadata)
1147
+ write_json(LOG_DIR / "reward.json", rewards)
1148
+ (LOG_DIR / "reward.txt").write_text(str(rewards["reward"]))
1149
+
1150
+
1151
+ def main() -> None:
1152
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1153
+ log_path = LOG_DIR / "programbench_eval.log"
1154
+ metadata = json.loads(METADATA_PATH.read_text())
1155
+ branches = metadata.get("branches", {})
1156
+ try:
1157
+ result = evaluate(metadata)
1158
+ except Exception as exc:
1159
+ error_code = type(exc).__name__
1160
+ result = {
1161
+ "test_results": [],
1162
+ "error_code": error_code,
1163
+ "error_details": str(exc),
1164
+ "log": [
1165
+ {
1166
+ "step": "evaluator_exception",
1167
+ "exception_info": traceback.format_exc(),
1168
+ "returncode": 1,
1169
+ }
1170
+ ],
1171
+ "solution_branch": "submission",
1172
+ "test_branches": [
1173
+ name for name, info in branches.items() if not info.get("ignored")
1174
+ ],
1175
+ "test_branch_errors": {
1176
+ "__evaluator__": [{"error_code": error_code, "error_details": str(exc)}]
1177
+ },
1178
+ "executable_hash": None,
1179
+ "warnings": [],
1180
+ }
1181
+ for branch, info in branches.items():
1182
+ if info.get("ignored"):
1183
+ continue
1184
+ inject_not_run(result, branch, branch_tests(info), error_code)
1185
+ log_path.write_text(traceback.format_exc())
1186
+ else:
1187
+ log_path.write_text("")
1188
+ write_outputs(result, metadata)
1189
+
1190
+
1191
+ if __name__ == "__main__":
1192
+ main()
tasks/abishekvashok--cmatrix.5c082c6/tests/programbench_task.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/abishekvashok--cmatrix.5c082c6/tests/test.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Verifier exec may not inherit image ENV (Modal/gVisor, login-shell resets).
5
+ export PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
6
+
7
+ mkdir -p /logs/verifier /logs/artifacts
8
+
9
+ write_failure() {
10
+ local code="$1"
11
+ local details="$2"
12
+ python3 - "$code" "$details" <<'PY'
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ code, details = sys.argv[1:3]
18
+ try:
19
+ metadata = json.loads(Path("/tests/programbench_task.json").read_text())
20
+ n_tests = sum(
21
+ len([
22
+ name for name in info.get("tests", [])
23
+ if name not in {item.get("name") for item in info.get("ignored_tests", [])}
24
+ ])
25
+ for branch, info in metadata.get("branches", {}).items()
26
+ if not info.get("ignored")
27
+ )
28
+ except Exception:
29
+ n_tests = 0
30
+ result = {
31
+ "test_results": [],
32
+ "error_code": code,
33
+ "error_details": details,
34
+ "log": [],
35
+ "solution_branch": "submission",
36
+ "test_branches": [],
37
+ "test_branch_errors": {
38
+ "__infra__": [{"error_code": code, "error_details": details}]
39
+ },
40
+ "executable_hash": None,
41
+ "warnings": [],
42
+ }
43
+ diagnostics = {
44
+ "pass_rate": 0.0,
45
+ "resolved": 0,
46
+ "n_passed": 0,
47
+ "n_tests": n_tests,
48
+ "n_branch_errors": 1,
49
+ "infra_error": 1,
50
+ "executable_hash_present": 0,
51
+ }
52
+ Path("/logs/verifier/programbench_eval.json").write_text(
53
+ json.dumps(result, indent=2, sort_keys=True)
54
+ )
55
+ Path("/logs/verifier/harbor_diagnostics.json").write_text(
56
+ json.dumps(diagnostics, indent=2, sort_keys=True)
57
+ )
58
+ Path("/logs/verifier/reward.json").write_text(
59
+ json.dumps(
60
+ {"reward": 0.0, "resolved": 0.0, "almost_resolved": 0.0},
61
+ indent=2,
62
+ sort_keys=True,
63
+ )
64
+ )
65
+ Path("/logs/verifier/reward.txt").write_text("0.0")
66
+ Path("/logs/verifier/programbench_eval.log").write_text(details)
67
+ PY
68
+ }
69
+
70
+ if ! command -v python3 >/dev/null 2>&1; then
71
+ write_failure "missing_python3" "python3 is required in the cleanroom image"
72
+ exit 0
73
+ fi
74
+
75
+ if ! python3 /tests/programbench_evaluator.py; then
76
+ if [ ! -s /logs/verifier/reward.txt ]; then
77
+ write_failure "evaluator_crashed" \
78
+ "programbench_evaluator.py exited non-zero with no reward written"
79
+ fi
80
+ fi
81
+
82
+ exit 0
tasks/agourlay--zip-password-finder.704700d/environment/Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM programbench/agourlay_1776_zip-password-finder.704700d:task_cleanroom_v6
2
+
3
+ # Bake Harbor mini-swe-agent + uv at image build time (build has network) so the
4
+ # agent-phase allowlist can stay LLM-only instead of whitelisting installer CDNs.
5
+ COPY --from=ghcr.io/astral-sh/uv:0.7.13 /uv /uvx /usr/local/bin/
6
+
7
+ RUN python3 -m pip install --no-cache-dir --disable-pip-version-check \
8
+ 'huggingface-hub>=0.20' \
9
+ && uv tool install mini-swe-agent \
10
+ && if command -v mini-swe-agent >/dev/null 2>&1; then \
11
+ install -m 0755 "$(command -v mini-swe-agent)" /usr/local/bin/mini-swe-agent; \
12
+ fi
13
+
14
+ ENV PATH="/root/.local/bin:/usr/local/bin:${PATH}"
tasks/agourlay--zip-password-finder.704700d/instruction.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant that can interact with a computer.
2
+
3
+ This is a reverse-engineering benchmark. You are given a compiled binary and its documentation.
4
+ Your job is to write a new, original codebase from scratch that produces an executable with identical behavior.
5
+ You must figure out the behavior solely by running and interacting with the provided binary.
6
+ Writing original code based on observed behavior is the entire point of this benchmark.
7
+
8
+ Any approach that shortcuts this — finding existing source code, wrapping the binary,
9
+ or installing the original tool — does not count as a solution. It will be detected by an
10
+ automated judge, marked as a disqualification, and scored as a failure.
11
+ The trace will be posted to an online wall of shame.
12
+
13
+ <RULES>
14
+ ## What is not allowed
15
+
16
+ ### 1. Obtaining source code
17
+
18
+ The only source of truth about what the executable does is the executable itself and its
19
+ bundled documentation. You must not search the internet, package registries, or any external
20
+ source for information about this project's source code. Even if you recognize what the
21
+ executable is, you must reimplement it from behavioral observation alone.
22
+
23
+ This includes but is not limited to:
24
+ - Cloning or browsing the original GitHub repository, its forks, or mirrors
25
+ - Downloading the project from package registries: `cargo install <project>`, `go get github.com/<org>/<project>`, `pip install <project>`, `apt-get source <project>`, `npm install <project>`, etc.
26
+ - Fetching source tarballs from project websites (e.g., `curl https://lua.org/ftp/lua-5.5.0.tar.gz`)
27
+ - Using a package manager to download the project as a dependency and then reading its cached source (e.g., navigating into `~/.cargo/registry/src/` or `$(go env GOPATH)/pkg/mod/`)
28
+ - Searching the web for the project's source code or implementation details
29
+
30
+ ### 2. Wrapping or reusing the original binary
31
+
32
+ Your submission must be a genuine reimplementation. The provided `./executable` is for
33
+ observation only — your final solution must not depend on it or any other pre-built version
34
+ of the same tool at runtime.
35
+
36
+ This includes but is not limited to:
37
+ - Writing a wrapper script that delegates to the original binary (e.g., `exec zstd "$@"`)
38
+ - Installing the tool from a package manager and shimming to it (e.g., `apt-get install nnn && cp $(which nnn) ./executable`)
39
+ - Writing a `compile.sh` that simply makes the provided binary executable (`chmod +x ./executable`) or copies it (`cp ./executable ./executable`)
40
+ - Building a binary whose main function shells out to an external tool (e.g., `Command::new("miniserve").args(args).exec()`)
41
+ - Re-linking prebuilt `.o` object files found in the workspace without writing new source code
42
+
43
+ ### 3. Binary analysis of the provided executable
44
+
45
+ All information about the provided `./executable` must be obtained by interacting with it
46
+ through its normal user interface (CLI flags, stdin/stdout, etc.).
47
+ - You MUST NOT decompile `./executable` or use disassemblers (objdump, Ghidra, etc.) on it
48
+ - You MUST NOT use strace, ltrace, or similar tracing/instrumentation tools on `./executable`
49
+
50
+ Note: this restriction applies ONLY to the provided `./executable`. You are free to use any
51
+ analysis tools on binaries that you produce yourself during development.
52
+
53
+ ## What IS allowed
54
+
55
+ - Running the executable with any inputs, flags, and arguments to observe its behavior
56
+ - Reading any documentation files bundled in the workspace
57
+ </RULES>
58
+
59
+ ## Task context
60
+
61
+ We want to write the source code for a given executable.
62
+ The executable is located at `./executable` in the workspace root.
63
+
64
+ You also have access to the existing documentation.
65
+
66
+ ## Your task
67
+
68
+ Implement the source code to generate an executable of exactly identical behavior as the original.
69
+
70
+ No project-specific dependencies are pre-installed.
71
+ You do NOT have access to the internet.
72
+ **IMPORTANT**: Make sure that the executable(s) and everything else that is an artifact is not committed, i.e., is in your `.gitignore` file.
73
+ Finally, commit your changes.
74
+
75
+ Make sure that you have a `./compile.sh` file that produces an executable `./executable` in the workspace root.
76
+ `compile.sh` should be executable and should install any dependencies needed to compile the executable.
77
+ If your compile.sh fails to compile on a fresh checkout, your task has failed.
78
+
79
+ ## Important: This is a reverse-engineering benchmark
80
+
81
+ Your goal is to write original code from scratch that reproduces the executable's behavior.
82
+ The only way to learn what the executable does is to run it and read its bundled documentation.
83
+
84
+ Any attempt to obtain source code — whether successful or not — or to wrap/reuse the
85
+ provided binary will be detected by an automated judge, disqualified, and scored as zero.
86
+ See the full rules in the system prompt above. Key points:
87
+
88
+ - Do NOT search the internet, clone repos, or download the project from any package registry
89
+ - Do NOT wrap, shim, or delegate to the provided `./executable` or any installed version of the same tool
90
+ - Do NOT decompile the provided `./executable` or use strace/ltrace on it (analyzing your own binaries is fine)
91
+ - You SHOULD extensively test the executable to understand its behavior before writing code.
92
+ If you are dealing with a TUI, tmux/libtmux has been installed to help you test/inspect/it.
93
+
94
+ ## Recommended Workflow
95
+
96
+ 1. Explore all documentation files
97
+ 2. Play with the executable to understand its behavior (however, you MUST NOT decompile `./executable` or perform any other form of binary or strace/ltrace analysis on it)
98
+ 3. Write the source code to implement the behavior
99
+
100
+ Submit your changes and finish your work by issuing the following command: `echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT`.
101
+ Do not combine it with any other command. <important>After this command, you cannot continue working on this task.</important>
tasks/agourlay--zip-password-finder.704700d/solution/solve.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle solution. Encodes the cleanroom's reference ./executable in the
3
+ # handoff file so the raw-binary artifact filter and pre-compile hash scrub
4
+ # still run normally. compile.sh restores the reference after that scrub.
5
+ #
6
+ # Internal ceiling / diagnostics check — NOT a benchmark score.
7
+ set -euo pipefail
8
+ test -f ./executable
9
+ python3 - <<'PY'
10
+ import base64
11
+ from pathlib import Path
12
+
13
+ Path(".programbench_oracle_reference").write_bytes(
14
+ base64.b64encode(Path("executable").read_bytes())
15
+ )
16
+ PY
17
+ cat > compile.sh <<'EOF'
18
+ #!/usr/bin/env bash
19
+ set -euo pipefail
20
+ if [ -f ./.programbench_oracle_reference ]; then
21
+ python3 - <<'PY'
22
+ import base64
23
+ from pathlib import Path
24
+
25
+ Path("executable").write_bytes(
26
+ base64.b64decode(Path(".programbench_oracle_reference").read_bytes())
27
+ )
28
+ PY
29
+ fi
30
+ test -f ./executable
31
+ chmod +x ./executable
32
+ EOF
33
+ chmod +x compile.sh
tasks/agourlay--zip-password-finder.704700d/task.toml ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ source = "ProgramBench"
3
+
4
+ # Cleanroom images: generated tasks default to upstream ProgramBench v6
5
+ # (`programbench/*:task_cleanroom_v6`). Exceptions: tinycc, doxygen, revive, dirble,
6
+ # and chafa use `bencalvert04/*` until upstream ships fixes — see adapter
7
+ # `MIRROR_PATCHED_INSTANCE_IDS`.
8
+ # Agent phase uses network_mode = "allowlist" (cleanroom contract). Verifier runs in
9
+ # a separate sandbox (environment_mode = "separate") with default network for HF blobs.
10
+ # allowed_hosts is LLM APIs only; mini-swe-agent + uv are baked in environment/Dockerfile.
11
+ #
12
+ # Harness fixes (evaluator, verifier Dockerfile) live in task-template/tests/ and are
13
+ # copied into every generated task on `programbench-adapter --overwrite`.
14
+ #
15
+ # Two roles in this artifacts list:
16
+ # 1) trial outputs: /logs/verifier/* — collected from the verifier sandbox to the host
17
+ # 2) agent→verifier handoff: /workspace — copied from the agent sandbox to the
18
+ # verifier sandbox, with ./executable excluded so the reference binary cannot
19
+ # be passed across the boundary as a cheat. Hash-scrub inside the verifier
20
+ # remains a second-layer defense.
21
+ artifacts = [
22
+ "/logs/verifier/programbench_eval.json",
23
+ "/logs/verifier/harbor_diagnostics.json",
24
+ "/logs/verifier/programbench_eval.log",
25
+ "/logs/verifier/reward.json",
26
+ "/logs/verifier/reward.txt",
27
+ { source = "/workspace", exclude = ["executable"] },
28
+ ]
29
+
30
+ [task]
31
+ name = "programbench/agourlay--zip-password-finder.704700d"
32
+ description = "ProgramBench cleanroom reconstruction task for agourlay/zip-password-finder"
33
+ authors = [
34
+ { name = "John Yang" },
35
+ { name = "Kilian Lieret" },
36
+ ]
37
+ keywords = ["programbench", "reverse-engineering", "software-engineering", "cleanroom", "rs"]
38
+
39
+ [metadata]
40
+ source = "ProgramBench"
41
+ instance_id = "agourlay__zip-password-finder.704700d"
42
+ repository = "agourlay/zip-password-finder"
43
+ commit = "704700d16845d73063195f1f0e3e328d353df131"
44
+ language = "rs"
45
+ difficulty = "medium"
46
+ task_image = "programbench/agourlay_1776_zip-password-finder.704700d:task_v6"
47
+ cleanroom_image = "programbench/agourlay_1776_zip-password-finder.704700d:task_cleanroom_v6"
48
+ test_branches = 16
49
+ test_count = 792
50
+
51
+ [agent]
52
+ timeout_sec = 14400
53
+ network_mode = "allowlist"
54
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
55
+
56
+ [verifier]
57
+ timeout_sec = 7200
58
+ user = "root"
59
+ environment_mode = "separate"
60
+
61
+ # Modal/gVisor has no real TTY; wrap pytest in ``script`` so terminal tools (chafa,
62
+ # tty-clock, felix, delta pagers, etc.) match Docker oracle behavior.
63
+ [verifier.env]
64
+ PROGRAMBENCH_SCRIPT_PTY = "1"
65
+
66
+ # Verifier image is built from tests/Dockerfile (no docker_image set), which
67
+ # starts FROM the cleanroom image and wipes /workspace so the reference
68
+ # binary baked into the image cannot survive into the verification phase.
69
+ [verifier.environment]
70
+ build_timeout_sec = 1800
71
+ cpus = 12
72
+ memory_mb = 8192
73
+ storage_mb = 30720
74
+ gpus = 0
75
+ workdir = "/workspace"
76
+
77
+ [environment]
78
+ docker_image = "programbench/agourlay_1776_zip-password-finder.704700d:task_cleanroom_v6"
79
+ network_mode = "allowlist"
80
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
81
+ build_timeout_sec = 1800
82
+ cpus = 12
83
+ memory_mb = 8192
84
+ storage_mb = 30720
85
+ gpus = 0
86
+ workdir = "/workspace"
tasks/agourlay--zip-password-finder.704700d/tests/Dockerfile ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Verifier image for programbench.
2
+ #
3
+ # Built from the cleanroom image so all toolchain / build dependencies the
4
+ # agent's compile.sh might need are present. The key difference from the
5
+ # agent image is that /workspace is wiped at image build time — the
6
+ # reference ./executable baked into the cleanroom image must NOT survive
7
+ # into the verification phase. The agent's submission arrives at /workspace
8
+ # at runtime via the artifact handoff (`artifacts = [{ source = "/workspace",
9
+ # exclude = ["executable"] }]` in task.toml), so even if the agent left the
10
+ # reference binary in their workspace, it is filtered out at the boundary.
11
+ #
12
+ # Defense-in-depth: programbench_evaluator.py still hash-scrubs files
13
+ # matching eval_clean_hashes inside the verifier sandbox.
14
+ FROM programbench/agourlay_1776_zip-password-finder.704700d:task_cleanroom_v6
15
+
16
+ # Wipe workspace contents — reference binary, any dev state — before this
17
+ # image is ever started as a verifier sandbox. The `.[!.]*` glob covers
18
+ # dotfiles while skipping `.` and `..`.
19
+ RUN rm -rf /workspace/* /workspace/.[!.]* 2>/dev/null || true \
20
+ && mkdir -p /workspace
21
+
22
+ # Cap pytest below 9.1 for everything pip installs in this verifier image —
23
+ # including each branch's `eval/run.sh`, some of which do
24
+ # `pip install --upgrade pytest`. pytest >=9.1 turns "mark applied to a
25
+ # fixture" into a hard error, which crashes collection whenever libtmux's
26
+ # autoloaded `pytest11` plugin (libtmux.pytest_plugin, present in many
27
+ # cleanroom images) is loaded — so no results.xml is produced and the branch
28
+ # reports `missing_results_xml` (reward 0). Because all branches share one
29
+ # verifier container and pip installs are container-global, a single upgrading
30
+ # branch would poison pytest for the whole task. PIP_CONSTRAINT is honored even
31
+ # by `--upgrade`, is a no-op for tasks that never upgrade, and keeps libtmux
32
+ # importable for tasks whose tests use it — so this is safe across the dataset.
33
+ RUN printf 'pytest<9.1\n' > /etc/pip-constraint.txt
34
+ ENV PIP_CONSTRAINT=/etc/pip-constraint.txt
35
+
36
+ # Ensure Go/Rust/Haskell toolchains stay on PATH for `bash -lc` (eval/run.sh).
37
+ # Login shells source /etc/profile, which can reset PATH and drop image ENV —
38
+ # observed on Modal/gVisor and some Docker exec paths.
39
+ RUN set -eu; \
40
+ paths=""; \
41
+ add_path() { if [ -d "$1" ]; then paths="${paths:+$paths:}$1"; fi; }; \
42
+ add_path /usr/local/go/bin; \
43
+ add_path /go/bin; \
44
+ add_path /usr/local/cargo/bin; \
45
+ add_path /root/.cargo/bin; \
46
+ add_path /root/.ghcup/bin; \
47
+ for d in /usr/lib/go-*/bin; do add_path "$d"; done; \
48
+ if [ -n "$paths" ]; then \
49
+ mkdir -p /etc/profile.d; \
50
+ printf 'export PATH="%s:${PATH}"\n' "$paths" > /etc/profile.d/programbench-toolchain.sh; \
51
+ fi
52
+ ENV PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
53
+
54
+ # Install verifier runtime dependencies. ``huggingface-hub`` is required when
55
+ # optional hidden-test blobs were intentionally omitted from the registry
56
+ # dataset: the evaluator then resolves them from Hugging Face at verify time.
57
+ # Best-effort: the cleanroom image may already have these packages.
58
+ RUN python3 -m pip install --no-cache-dir --disable-pip-version-check \
59
+ pytest pytest-rerunfailures huggingface-hub || true
60
+
61
+ # ``script`` provides a pseudo-TTY for Modal/gVisor (see PROGRAMBENCH_SCRIPT_PTY).
62
+ RUN command -v script >/dev/null 2>&1 || ( \
63
+ apt-get update && apt-get install -y --no-install-recommends bsdutils \
64
+ && rm -rf /var/lib/apt/lists/* \
65
+ )
66
+
67
+ # Copy the entire tests build context into /tests/ (test.sh,
68
+ # programbench_evaluator.py, programbench_task.json, optional blobs/).
69
+ # The Dockerfile itself is removed afterwards so it does not ship in the
70
+ # image's /tests/.
71
+ COPY . /tests/
72
+ RUN chmod +x /tests/test.sh && rm -f /tests/Dockerfile
tasks/agourlay--zip-password-finder.704700d/tests/blobs/ATTRIBUTION.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Attribution
2
+
3
+ The test files in this directory were generated by an AI model with access to
4
+ the source code and existing tests of the original repository listed below.
5
+ The generated tests may be inspired by or substantially similar to existing
6
+ tests in that repository.
7
+
8
+ ## Original Repository
9
+
10
+ - **Repository:** [agourlay/zip-password-finder](https://github.com/agourlay/zip-password-finder/tree/704700d16845d73063195f1f0e3e328d353df131)
11
+ - **Commit:** `704700d`
12
+ - **License:** Apache-2.0
tasks/agourlay--zip-password-finder.704700d/tests/blobs/LICENSE ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/045fa65d8a17.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac85bb5659fef6979f5a78683b20158d22cba7990ec1bb43359c5271fc0804f8
3
+ size 896805
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/0a5ff17822b7.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:441d1e75309971ff09e2b48b147423b6c136a2d597ea5c24893010d3c6c5b382
3
+ size 99557
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/0df6b4d747de.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19f79c09b569be80e1114cb3ca91ea951ab794c88b59880bb9ce315b115dfd85
3
+ size 99930
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/15241b94c9bf.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf331d651be156d2ef96fad87b5a0decf9f751ade40f01f25fc7123379d112a2
3
+ size 99204
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/1fb751a1a8a1.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4919cf8f2f72464b936f7eda2ab2027a0755b4b9a48712e9ec0adf5af26c8380
3
+ size 2332783
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/220f03dff485.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c362909eae71d1fa560a7c37fc5b840b04a214418ce9c70fed67cedd50dff3b
3
+ size 99778
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/3001c1482b82.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8449b456076cdaadd0d0147742d4010216a0239d43b7a67da7152a022b24d5c1
3
+ size 102882
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/40a4c29f1824.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d095fea7eb96550302ad55d00637be15c628a1e2bd73c1f6b3c42b61b9d08fa
3
+ size 145290
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/63078964cd3f.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08b484871369c41696fcff2e3c18470d2c8b5b91b1c287e10ad21747ed3a505e
3
+ size 895405
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/644934f68973.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b900b293aa03e1da94755e56b2ea5292a73ace8a3e03a9c9a6579702c1cacbfb
3
+ size 103135
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/a6516d59468d.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ef73268a20d67a54812c7e9b5ec08e63e1509e33f2de0aaf125975a7b8e3853
3
+ size 98658
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/c77d1fe5cef8.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31afb4ddc31d630495c2b694de5acaf2ec2ee9b1943137ae3ff5555102675514
3
+ size 102396
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/c865682e93ee.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c0253820b733532dc83c132519d4c73f97d21da4c0f28a80dc08f5ae5925819
3
+ size 102968
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/ec5f2f35f276.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad165397db4fa7b9db2c691744b529944e25c40819fd32eb3de3c86e6d04b682
3
+ size 100431
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/f2ad8ae32d40.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2e1cf9deee544df0e850f909396f6021b93f942f9f85b3e70ba42fe280758c6
3
+ size 102029
tasks/agourlay--zip-password-finder.704700d/tests/blobs/tests/f83680a23703.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f0afa10d999896b4f3547192966fadf371c4f16e7edd3863b94558abc74871bc
3
+ size 98730
tasks/agourlay--zip-password-finder.704700d/tests/programbench_evaluator.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """In-place ProgramBench evaluator.
3
+
4
+ Mirrors ProgramBench's ``Evaluator`` pipeline as closely as a single-container,
5
+ no-Docker-in-Docker host allows. Run from ``tests/test.sh`` inside the agent's
6
+ cleanroom container after Harbor flips the verifier-phase network policy.
7
+
8
+ Differences from ``programbench.eval.eval.Evaluator`` that are structural to
9
+ running in one container:
10
+
11
+ * No fresh container per branch. ``snapshot_workspace`` / ``restore_workspace``
12
+ copy a post-compile workspace snapshot to a temp directory and restore it
13
+ before each branch; ``cleanup_lingering_processes`` kills leftover branch
14
+ processes between attempts to approximate the fresh-container boundary.
15
+ * No ``docker commit``. The post-compile workspace snapshot serves the same
16
+ role as the committed image upstream.
17
+ * Hidden test blobs are fetched on demand from HuggingFace via
18
+ ``huggingface_hub.snapshot_download`` (matching ``programbench.utils.blob_store``)
19
+ rather than being pre-staged into ``/tests/blobs/``. Override with
20
+ ``PROGRAMBENCH_BLOB_DIR`` for offline reruns.
21
+
22
+ Everything else (eval_clean_hashes scrub, deterministic synthetic git seed,
23
+ ``compile.sh`` then stash + hash the executable, best-effort
24
+ ``pytest-rerunfailures``, per-branch test-tar overlay, executable hash
25
+ ``--max-worker-restart=4``, xdist worker-crash retry with serial fallback,
26
+ best-of-N attempt selection, active vs ignored test bookkeeping, scoring) is
27
+ preserved.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shlex
37
+ import shutil
38
+ import signal
39
+ import subprocess
40
+ import tempfile
41
+ import time
42
+ import traceback
43
+ import xml.etree.ElementTree as ET
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ WORKSPACE = Path(os.environ.get("PROGRAMBENCH_WORKSPACE", "/workspace"))
48
+ STASHED_EXECUTABLE = Path("/opt/programbench-stashed-executable-do-not-modify")
49
+ METADATA_PATH = Path(
50
+ os.environ.get("PROGRAMBENCH_METADATA", "/tests/programbench_task.json")
51
+ )
52
+ LOG_DIR = Path(os.environ.get("PROGRAMBENCH_LOG_DIR", "/logs/verifier"))
53
+ WORKER_CRASH_PHRASE = "worker '"
54
+ XDIST_COLLAPSE_MARKERS = (
55
+ "maximum crashed workers reached",
56
+ "xdist: maximum crashed",
57
+ )
58
+ # Serial retry when a parallel attempt fails most tests — catches xdist fixture
59
+ # races on filesystem golden tests (e.g. dutree) without retrying every branch.
60
+ HIGH_FAILURE_SERIAL_RETRY_FRACTION = 0.5
61
+ HIGH_FAILURE_SERIAL_RETRY_MIN_TESTS = 8
62
+
63
+ DEFAULT_HF_REPO_ID = "programbench/ProgramBench-Tests"
64
+ DEFAULT_HF_REVISION = "main"
65
+
66
+ # Oracle agent handoff files (see solution/solve.sh). Must not appear in the
67
+ # post-compile workspace snapshot or they pollute tree-scanning tests (dutree).
68
+ _ORACLE_HANDOFF_NAMES = (".programbench_oracle_reference",)
69
+
70
+ _TOOLCHAIN_BIN_DIR_CANDIDATES = (
71
+ "/usr/local/go/bin",
72
+ "/go/bin",
73
+ "/usr/local/cargo/bin",
74
+ "/root/.cargo/bin",
75
+ "/root/.ghcup/bin",
76
+ )
77
+
78
+
79
+ def toolchain_bin_dirs() -> list[str]:
80
+ """Return toolchain bin directories that exist on this image."""
81
+ candidates = list(_TOOLCHAIN_BIN_DIR_CANDIDATES)
82
+ candidates.extend(
83
+ str(path) for path in sorted(Path("/usr/lib").glob("go-*/bin")) if path.is_dir()
84
+ )
85
+ seen: set[str] = set()
86
+ present: list[str] = []
87
+ for path in candidates:
88
+ if path in seen:
89
+ continue
90
+ seen.add(path)
91
+ if Path(path).is_dir():
92
+ present.append(path)
93
+ return present
94
+
95
+
96
+ def bootstrap_toolchain_path() -> str:
97
+ """Prepend discovered toolchain dirs to PATH (idempotent)."""
98
+ prepend = toolchain_bin_dirs()
99
+ current_parts = [part for part in os.environ.get("PATH", "").split(":") if part]
100
+ merged: list[str] = []
101
+ for path in prepend + current_parts:
102
+ if path not in merged:
103
+ merged.append(path)
104
+ new_path = ":".join(merged)
105
+ os.environ["PATH"] = new_path
106
+ return new_path
107
+
108
+
109
+ def _bash_login_command(command: str) -> str:
110
+ """Run ``command`` under bash -lc with an explicit PATH export."""
111
+ path = bootstrap_toolchain_path()
112
+ return f"export PATH={shlex.quote(path)}; {command}"
113
+
114
+
115
+ def sha256(path: Path) -> str:
116
+ h = hashlib.sha256()
117
+ with path.open("rb") as f:
118
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
119
+ h.update(chunk)
120
+ return h.hexdigest()
121
+
122
+
123
+ def write_json(path: Path, data: dict[str, Any]) -> None:
124
+ tmp = path.with_suffix(path.suffix + ".tmp")
125
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
126
+ tmp.replace(path)
127
+
128
+
129
+ def _read_log_tail(path: Path | None, max_bytes: int = 65536) -> str:
130
+ if path is None or not path.exists():
131
+ return ""
132
+ data = path.read_bytes()
133
+ if len(data) <= max_bytes:
134
+ return data.decode(errors="replace")
135
+ return data[-max_bytes:].decode(errors="replace")
136
+
137
+
138
+ def _close_pipes(proc: subprocess.Popen[Any]) -> None:
139
+ for stream in (proc.stdout, proc.stderr):
140
+ if stream is not None:
141
+ try:
142
+ stream.close()
143
+ except OSError:
144
+ pass
145
+
146
+
147
+ def _terminate_process_tree(proc: subprocess.Popen[Any]) -> None:
148
+ try:
149
+ os.killpg(proc.pid, signal.SIGKILL)
150
+ except ProcessLookupError:
151
+ pass
152
+ try:
153
+ proc.kill()
154
+ except ProcessLookupError:
155
+ pass
156
+
157
+
158
+ _PKILL_PATTERNS = (
159
+ f"{WORKSPACE}/eval/",
160
+ f"{WORKSPACE}/tests/",
161
+ "tail -f",
162
+ "development.log",
163
+ " less ",
164
+ " less$",
165
+ "/less ",
166
+ )
167
+
168
+
169
+ def _pkill_aggressive() -> str:
170
+ """Best-effort kill of branch pytest/subprocess trees (Modal gVisor fallback)."""
171
+ notes: list[str] = []
172
+ workspace = str(WORKSPACE)
173
+ patterns = list(_PKILL_PATTERNS) + [
174
+ f"pytest.*{workspace}",
175
+ f"xdist.*{workspace}",
176
+ ]
177
+ for pattern in patterns:
178
+ result = subprocess.run(
179
+ ["pkill", "-9", "-f", pattern],
180
+ capture_output=True,
181
+ text=True,
182
+ )
183
+ notes.append(f"pkill -9 -f {pattern!r}: rc={result.returncode}")
184
+ return "\n".join(notes)
185
+
186
+
187
+ def run_step(
188
+ command: str,
189
+ cwd: Path,
190
+ *,
191
+ timeout: int,
192
+ env: dict[str, str] | None = None,
193
+ step: str,
194
+ accept_failure: bool = False,
195
+ log_output: bool | None = None,
196
+ max_output_bytes: int = 65536,
197
+ ) -> dict[str, Any]:
198
+ if log_output is None:
199
+ log_output = step == "run_tests" or timeout >= 60
200
+
201
+ started = time.monotonic()
202
+ stdout_path: Path | None = None
203
+ stderr_path: Path | None = None
204
+ stdout_f = None
205
+ stderr_f = None
206
+
207
+ if log_output:
208
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
209
+ log_id = f"{step}-{int(started * 1000)}"
210
+ stdout_path = LOG_DIR / f"run-step-{log_id}.stdout.log"
211
+ stderr_path = LOG_DIR / f"run-step-{log_id}.stderr.log"
212
+ stdout_f = stdout_path.open("w", encoding="utf-8")
213
+ stderr_f = stderr_path.open("w", encoding="utf-8")
214
+ popen_stdout: Any = stdout_f
215
+ popen_stderr: Any = stderr_f
216
+ else:
217
+ popen_stdout = subprocess.PIPE
218
+ popen_stderr = subprocess.PIPE
219
+
220
+ proc = subprocess.Popen(
221
+ ["bash", "-lc", _bash_login_command(command)],
222
+ cwd=cwd,
223
+ env={**os.environ, **(env or {})},
224
+ stdout=popen_stdout,
225
+ stderr=popen_stderr,
226
+ start_new_session=True,
227
+ text=True,
228
+ )
229
+ timed_out = False
230
+ stdout = ""
231
+ stderr = ""
232
+ try:
233
+ if log_output:
234
+ proc.wait(timeout=timeout)
235
+ else:
236
+ stdout, stderr = proc.communicate(timeout=timeout)
237
+ except subprocess.TimeoutExpired:
238
+ timed_out = True
239
+ _terminate_process_tree(proc)
240
+ cleanup_lingering_processes(aggressive=True)
241
+ try:
242
+ proc.wait(timeout=5)
243
+ except subprocess.TimeoutExpired:
244
+ proc.kill()
245
+ if not log_output:
246
+ _close_pipes(proc)
247
+ finally:
248
+ if stdout_f is not None:
249
+ stdout_f.close()
250
+ if stderr_f is not None:
251
+ stderr_f.close()
252
+
253
+ if timed_out:
254
+ if log_output:
255
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
256
+ stderr_path, max_output_bytes
257
+ )
258
+ else:
259
+ output = ""
260
+ entry = {
261
+ "step": step,
262
+ "command": command,
263
+ "wall_time": time.monotonic() - started,
264
+ "output": output,
265
+ "returncode": 124,
266
+ "exception_info": f"timed out after {timeout}s",
267
+ }
268
+ else:
269
+ if log_output:
270
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
271
+ stderr_path, max_output_bytes
272
+ )
273
+ else:
274
+ output = stdout + stderr
275
+ entry = {
276
+ "step": step,
277
+ "command": command,
278
+ "wall_time": time.monotonic() - started,
279
+ "output": output,
280
+ "returncode": proc.returncode,
281
+ "exception_info": "",
282
+ }
283
+ if entry["returncode"] and not accept_failure:
284
+ raise RuntimeError(
285
+ f"{step} failed: {entry['exception_info'] or entry['output']}"
286
+ )
287
+ return entry
288
+
289
+
290
+ def cleanup_lingering_processes(*, aggressive: bool = False) -> dict[str, Any]:
291
+ started = time.monotonic()
292
+ patterns = [
293
+ str(WORKSPACE / "executable"),
294
+ f"{WORKSPACE}/eval/",
295
+ f"{WORKSPACE}/tests/",
296
+ # lazygit --logs/-l tests spawn `tail -f` outside /workspace/.
297
+ "tail -f",
298
+ "development.log",
299
+ ]
300
+ killed: list[int] = []
301
+ proc_root = Path("/proc")
302
+ proc_available = proc_root.exists()
303
+ if proc_available:
304
+ for proc_dir in proc_root.iterdir():
305
+ if not proc_dir.name.isdigit():
306
+ continue
307
+ pid = int(proc_dir.name)
308
+ if pid in {os.getpid(), os.getppid()}:
309
+ continue
310
+ try:
311
+ raw = (proc_dir / "cmdline").read_bytes()
312
+ except (FileNotFoundError, PermissionError, ProcessLookupError):
313
+ continue
314
+ cmdline = raw.replace(b"\0", b" ").decode(errors="replace")
315
+ if not any(pattern in cmdline for pattern in patterns):
316
+ continue
317
+ try:
318
+ os.kill(pid, signal.SIGKILL)
319
+ except (PermissionError, ProcessLookupError):
320
+ continue
321
+ killed.append(pid)
322
+ pkill_output = ""
323
+ if aggressive or not proc_available:
324
+ pkill_output = _pkill_aggressive()
325
+ output_parts = []
326
+ if killed:
327
+ output_parts.append("\n".join(str(pid) for pid in killed))
328
+ if pkill_output:
329
+ output_parts.append(pkill_output)
330
+ return {
331
+ "step": "cleanup_lingering_processes",
332
+ "command": "kill leftover branch processes referencing the workspace",
333
+ "wall_time": time.monotonic() - started,
334
+ "output": "\n".join(output_parts),
335
+ "returncode": 0,
336
+ "exception_info": "",
337
+ }
338
+
339
+
340
+ def extract_trusted_blob(tar_path: Path, dest: Path) -> None:
341
+ import tarfile
342
+
343
+ with tarfile.open(tar_path, "r:gz") as tf:
344
+ try:
345
+ tf.extractall(dest, filter="fully_trusted")
346
+ except TypeError:
347
+ tf.extractall(dest)
348
+
349
+
350
+ def find_results_xml() -> Path | None:
351
+ """Return the junit xml path if pytest wrote one."""
352
+ for candidate in (WORKSPACE / "eval" / "results.xml", WORKSPACE / "results.xml"):
353
+ if candidate.exists():
354
+ return candidate
355
+ return None
356
+
357
+
358
+ def remove_oracle_handoff_artifacts() -> list[str]:
359
+ """Drop oracle-agent handoff files from /workspace before snapshot/restore."""
360
+ removed: list[str] = []
361
+ for name in _ORACLE_HANDOFF_NAMES:
362
+ path = WORKSPACE / name
363
+ if path.exists():
364
+ if path.is_dir():
365
+ shutil.rmtree(path)
366
+ else:
367
+ path.unlink()
368
+ removed.append(name)
369
+ return removed
370
+
371
+
372
+ def _remove_tree(path: Path) -> None:
373
+ """Remove a file or directory tree, with a shell fallback for overlay races."""
374
+ if path.is_symlink() or path.is_file():
375
+ path.unlink(missing_ok=True)
376
+ return
377
+ if not path.is_dir():
378
+ path.unlink(missing_ok=True)
379
+ return
380
+ for attempt in range(3):
381
+ try:
382
+ shutil.rmtree(path)
383
+ if not path.exists():
384
+ return
385
+ except OSError:
386
+ if attempt == 2:
387
+ run_step(
388
+ f"rm -rf {shlex.quote(str(path))}",
389
+ path.parent,
390
+ timeout=120,
391
+ step="clear_workspace_fallback",
392
+ accept_failure=True,
393
+ )
394
+ if not path.exists():
395
+ return
396
+ raise
397
+
398
+
399
+ def ensure_workspace_dir() -> None:
400
+ """Guarantee WORKSPACE exists as a writable directory (not a symlink/file)."""
401
+ if WORKSPACE.exists() and not WORKSPACE.is_dir():
402
+ if WORKSPACE.is_symlink() or WORKSPACE.is_file():
403
+ WORKSPACE.unlink()
404
+ else:
405
+ shutil.rmtree(WORKSPACE)
406
+ WORKSPACE.mkdir(parents=True, exist_ok=True)
407
+
408
+
409
+ def clear_workspace() -> None:
410
+ ensure_workspace_dir()
411
+ for path in list(WORKSPACE.iterdir()):
412
+ _remove_tree(path)
413
+
414
+
415
+ def restore_reference_executable() -> None:
416
+ """Write the stashed reference binary into /workspace after a branch overlay.
417
+
418
+ Branch blobs may ship ``executable`` as a dangling symlink into
419
+ ``target/release/...``; ``shutil.copy2`` would follow it and raise
420
+ ``FileNotFoundError``. Drop whatever the blob left and copy the stashed
421
+ reference as a regular file.
422
+ """
423
+ ensure_workspace_dir()
424
+ if not STASHED_EXECUTABLE.is_file():
425
+ raise FileNotFoundError(
426
+ f"missing stashed reference executable at {STASHED_EXECUTABLE}"
427
+ )
428
+ dest = WORKSPACE / "executable"
429
+ if dest.exists() or dest.is_symlink():
430
+ if dest.is_dir():
431
+ shutil.rmtree(dest)
432
+ else:
433
+ dest.unlink(missing_ok=True)
434
+ shutil.copy2(STASHED_EXECUTABLE, dest)
435
+ dest.chmod(0o755)
436
+
437
+
438
+ def snapshot_workspace(dest: Path) -> None:
439
+ if dest.exists():
440
+ shutil.rmtree(dest)
441
+ shutil.copytree(WORKSPACE, dest, symlinks=True)
442
+
443
+
444
+ def restore_workspace(source: Path) -> None:
445
+ clear_workspace()
446
+ shutil.copytree(source, WORKSPACE, dirs_exist_ok=True, symlinks=True)
447
+ ensure_workspace_dir()
448
+
449
+
450
+ def remove_hashed_files(root: Path, hashes: set[str]) -> list[str]:
451
+ removed: list[str] = []
452
+ for path in root.rglob("*"):
453
+ if path.is_file() and not path.is_symlink():
454
+ try:
455
+ if sha256(path) in hashes:
456
+ path.unlink()
457
+ removed.append(str(path.relative_to(root)))
458
+ except OSError:
459
+ continue
460
+ return removed
461
+
462
+
463
+ def branch_tests(branch_info: dict[str, Any]) -> list[str]:
464
+ ignored = {
465
+ item["name"] for item in branch_info.get("ignored_tests", []) if "name" in item
466
+ }
467
+ return [name for name in branch_info.get("tests", []) if name not in ignored]
468
+
469
+
470
+ def ignored_tests(metadata: dict[str, Any]) -> set[str]:
471
+ result: set[str] = set()
472
+ for branch, info in metadata.get("branches", {}).items():
473
+ result.update(
474
+ f"{branch}/{item['name']}"
475
+ for item in info.get("ignored_tests", [])
476
+ if "name" in item
477
+ )
478
+ return result
479
+
480
+
481
+ def active_tests(metadata: dict[str, Any]) -> set[str]:
482
+ active: set[str] = set()
483
+ for branch, info in metadata.get("branches", {}).items():
484
+ if info.get("ignored"):
485
+ continue
486
+ ignored = {
487
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
488
+ }
489
+ active.update(
490
+ f"{branch}/{name}" for name in info.get("tests", []) if name not in ignored
491
+ )
492
+ return active
493
+
494
+
495
+ def inject_not_run(
496
+ result: dict[str, Any], branch: str, tests: list[str], error_code: str
497
+ ) -> None:
498
+ result["test_results"].extend(
499
+ {
500
+ "name": name,
501
+ "branch": branch,
502
+ "status": "not_run",
503
+ "extra": {"error_code": error_code},
504
+ }
505
+ for name in tests
506
+ )
507
+
508
+
509
+ def testcase_name(case: ET.Element) -> str:
510
+ classname = case.attrib.get("classname", "")
511
+ name = case.attrib.get("name", "")
512
+ return f"{classname}.{name}" if classname else name
513
+
514
+
515
+ # Only these tags under <testcase> represent a result. <system-out> /
516
+ # <system-err> are stdout/stderr captures and must not be treated as results
517
+ # (a leading <system-out> followed by <failure> would otherwise be classified
518
+ # as a stdout-only "passed").
519
+ JUNIT_RESULT_TAGS = {"skipped", "failure", "error"}
520
+
521
+
522
+ def parse_junit(
523
+ raw_xml: str, branch: str, expected: list[str], ignored: set[str]
524
+ ) -> tuple[list[dict[str, Any]], list[str]]:
525
+ root = ET.fromstring(raw_xml)
526
+ got: set[str] = set()
527
+ results: list[dict[str, Any]] = []
528
+ for case in root.iter("testcase"):
529
+ name = testcase_name(case)
530
+ got.add(name)
531
+ extra: dict[str, Any] = {}
532
+ if "time" in case.attrib:
533
+ try:
534
+ extra["time"] = float(case.attrib["time"])
535
+ except ValueError:
536
+ extra["time"] = case.attrib["time"]
537
+ result_children = [c for c in case if c.tag in JUNIT_RESULT_TAGS]
538
+ # Collapse duplicate same-tag result children. Pytest's
539
+ # "pytest.internal" pseudo-test sometimes emits two identical <error>
540
+ # entries; treating that as a system_error would over-flag a real
541
+ # single failure. Mirrors upstream eval.py:816-820.
542
+ if len(result_children) > 1 and len({c.tag for c in result_children}) == 1:
543
+ result_children = [result_children[0]]
544
+ if not result_children:
545
+ status = "passed"
546
+ elif len(result_children) != 1:
547
+ status = "system_error"
548
+ extra["error_details"] = (
549
+ f"Expected 1 result for {name}, got {len(result_children)}: "
550
+ f"{[c.tag for c in result_children]}"
551
+ )
552
+ else:
553
+ first = result_children[0]
554
+ status = first.tag # "skipped" | "failure" | "error"
555
+ extra["message"] = first.attrib.get("message") or ""
556
+ if first.text:
557
+ extra["text"] = first.text
558
+ results.append(
559
+ {"name": name, "branch": branch, "status": status, "extra": extra}
560
+ )
561
+
562
+ active_expected = [name for name in expected if name not in ignored]
563
+ missing = [name for name in active_expected if name not in got]
564
+ results.extend(
565
+ {
566
+ "name": name,
567
+ "branch": branch,
568
+ "status": "not_run",
569
+ "extra": {"error_code": "missing_from_junit_xml"},
570
+ }
571
+ for name in missing
572
+ )
573
+ unexpected = got - set(expected) - ignored
574
+ warnings = (
575
+ [f"Branch {branch}: {len(unexpected)} test(s) in JUnit XML not in tests.json"]
576
+ if unexpected
577
+ else []
578
+ )
579
+ return results, warnings
580
+
581
+
582
+ def count_worker_crashes(raw_xml: str) -> int:
583
+ if WORKER_CRASH_PHRASE not in raw_xml:
584
+ return 0
585
+ try:
586
+ root = ET.fromstring(raw_xml)
587
+ except ET.ParseError:
588
+ return 0
589
+ crashes = 0
590
+ for case in root.iter("testcase"):
591
+ for child in case:
592
+ text = (child.get("message") or "") + " " + (child.text or "")
593
+ if (
594
+ child.tag in {"error", "failure"}
595
+ and WORKER_CRASH_PHRASE in text
596
+ and "crashed" in text
597
+ ):
598
+ crashes += 1
599
+ break
600
+ return crashes
601
+
602
+
603
+ def run_output_indicates_xdist_collapse(output: str) -> bool:
604
+ lower = output.lower()
605
+ return any(marker in lower for marker in XDIST_COLLAPSE_MARKERS)
606
+
607
+
608
+ def count_junit_failures(raw_xml: str) -> int:
609
+ try:
610
+ root = ET.fromstring(raw_xml)
611
+ except ET.ParseError:
612
+ return 0
613
+ failures = 0
614
+ for case in root.iter("testcase"):
615
+ for child in case:
616
+ if child.tag in {"failure", "error"}:
617
+ failures += 1
618
+ break
619
+ return failures
620
+
621
+
622
+ def count_junit_passed(raw_xml: str) -> int:
623
+ try:
624
+ root = ET.fromstring(raw_xml)
625
+ except ET.ParseError:
626
+ return 0
627
+ passed = 0
628
+ for case in root.iter("testcase"):
629
+ if not any(child.tag in JUNIT_RESULT_TAGS for child in case):
630
+ passed += 1
631
+ return passed
632
+
633
+
634
+ def branch_attempt_metrics(
635
+ raw_xml: str, *, run_output: str, expected_tests: int
636
+ ) -> tuple[int, int, int, int]:
637
+ """Return (crashes, n_testcases, failures, missing_from_xml)."""
638
+ crashes = count_worker_crashes(raw_xml)
639
+ if run_output_indicates_xdist_collapse(run_output):
640
+ crashes = max(crashes, 1)
641
+ n_tests = count_testcases(raw_xml)
642
+ failures = count_junit_failures(raw_xml)
643
+ missing = max(0, expected_tests - n_tests)
644
+ return crashes, n_tests, failures, missing
645
+
646
+
647
+ def needs_serial_retry(
648
+ *,
649
+ serial: bool,
650
+ crashes: int,
651
+ missing: int,
652
+ failures: int,
653
+ n_tests: int,
654
+ expected_tests: int,
655
+ run_output: str,
656
+ ) -> bool:
657
+ if crashes > 0 or missing > 0 or run_output_indicates_xdist_collapse(run_output):
658
+ return True
659
+ if serial:
660
+ return False
661
+ if expected_tests < HIGH_FAILURE_SERIAL_RETRY_MIN_TESTS or n_tests == 0:
662
+ return False
663
+ return failures / n_tests >= HIGH_FAILURE_SERIAL_RETRY_FRACTION
664
+
665
+
666
+ def count_testcases(raw_xml: str) -> int:
667
+ try:
668
+ return sum(1 for _ in ET.fromstring(raw_xml).iter("testcase"))
669
+ except ET.ParseError:
670
+ return 0
671
+
672
+
673
+ def scored_results(
674
+ result: dict[str, Any], metadata: dict[str, Any]
675
+ ) -> list[dict[str, Any]]:
676
+ active = active_tests(metadata)
677
+ by_key = {
678
+ f"{test['branch']}/{test['name']}": test
679
+ for test in result["test_results"]
680
+ if f"{test['branch']}/{test['name']}" in active
681
+ }
682
+ return [
683
+ by_key.get(
684
+ key,
685
+ {
686
+ "branch": key.split("/", 1)[0],
687
+ "name": key.split("/", 1)[1],
688
+ "status": "not_run",
689
+ "extra": {"error_code": "missing_from_results"},
690
+ },
691
+ )
692
+ for key in sorted(active)
693
+ ]
694
+
695
+
696
+ def summarize(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
697
+ scored = scored_results(result, metadata)
698
+ n_passed = sum(t["status"] == "passed" for t in scored)
699
+ n_tests = len(scored)
700
+ pass_rate = n_passed / n_tests if n_tests else 0.0
701
+ # Multi-key reward: Harbor's default Mean aggregates each key independently
702
+ # (see harbor.metrics.base.aggregate_reward_dicts), so mean("resolved") is
703
+ # the proportion of tasks scoring a perfect pass-rate and mean of
704
+ # "almost_resolved" is the proportion scoring >= 0.95. "reward" stays the
705
+ # per-task pass-rate whose mean is the overall mean reward.
706
+ return {
707
+ "reward": pass_rate,
708
+ "resolved": 1.0 if pass_rate >= 1.0 else 0.0,
709
+ "almost_resolved": 1.0 if pass_rate >= 0.95 else 0.0,
710
+ }
711
+
712
+
713
+ def diagnostics(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
714
+ scored = scored_results(result, metadata)
715
+ n_passed = sum(t["status"] == "passed" for t in scored)
716
+ n_tests = len(scored)
717
+ pass_rate = n_passed / n_tests if n_tests else 0.0
718
+ return {
719
+ "pass_rate": pass_rate,
720
+ "resolved": int(
721
+ bool(
722
+ n_tests
723
+ and n_passed == n_tests
724
+ and not result["test_branch_errors"]
725
+ and not result["error_code"]
726
+ )
727
+ ),
728
+ "n_passed": n_passed,
729
+ "n_tests": n_tests,
730
+ "n_branch_errors": len(result["test_branch_errors"]),
731
+ "infra_error": int(bool(result["error_code"] or result["test_branch_errors"])),
732
+ "executable_hash_present": int(bool(result.get("executable_hash"))),
733
+ }
734
+
735
+
736
+ def use_script_pty() -> bool:
737
+ return os.environ.get("PROGRAMBENCH_SCRIPT_PTY", "").strip() == "1"
738
+
739
+
740
+ def script_pty_available() -> bool:
741
+ return shutil.which("script") is not None
742
+
743
+
744
+ def branch_env(
745
+ *,
746
+ serial: bool,
747
+ has_rerunfailures: bool,
748
+ extras: dict[str, str] | None = None,
749
+ ) -> dict[str, str]:
750
+ addopts = ["--max-worker-restart=4"]
751
+ if has_rerunfailures:
752
+ addopts.extend(["--reruns=2", "--reruns-delay=1"])
753
+ env = {
754
+ "PYTEST_ADDOPTS": " ".join(addopts),
755
+ # Match upstream non-TTY regression environments (dirble log format, etc.).
756
+ "NO_COLOR": "1",
757
+ "TERM": "dumb",
758
+ "CLICOLOR": "0",
759
+ "CLICOLOR_FORCE": "0",
760
+ "COLORTERM": "",
761
+ }
762
+ if extras:
763
+ env.update(extras)
764
+ xdist_workers = os.environ.get("PROGRAMBENCH_XDIST_WORKERS")
765
+ if serial:
766
+ xdist_workers = "1"
767
+ if xdist_workers:
768
+ env["PYTEST_XDIST_AUTO_NUM_WORKERS"] = xdist_workers
769
+ return env
770
+
771
+
772
+ _SERIAL_RUN_SH = ".programbench_run_serial.sh"
773
+ # ``eval/run.sh`` usually passes ``-n auto`` on the command line, which overrides
774
+ # ``PYTEST_ADDOPTS``. Rewrite to ``-n 0`` in a verifier-local copy for retries.
775
+ _RUN_SH_XDIST_RE = re.compile(r"-n\s*(?:auto|\d+)")
776
+
777
+
778
+ def prepare_serial_run_sh(run_sh: Path) -> Path:
779
+ """Write a serial-only copy of ``eval/run.sh`` with xdist disabled."""
780
+ serial_sh = run_sh.with_name(_SERIAL_RUN_SH)
781
+ patched = _RUN_SH_XDIST_RE.sub("-n 0", run_sh.read_text())
782
+ serial_sh.write_text(patched)
783
+ serial_sh.chmod(0o755)
784
+ return serial_sh
785
+
786
+
787
+ def run_tests_command(*, serial: bool) -> str:
788
+ if serial:
789
+ inner = f"chmod +x ./eval/{_SERIAL_RUN_SH} && ./eval/{_SERIAL_RUN_SH}"
790
+ else:
791
+ inner = "chmod +x ./eval/run.sh && ./eval/run.sh"
792
+ if use_script_pty() and script_pty_available():
793
+ return f"script -q -c {shlex.quote(inner)} /dev/null"
794
+ return inner
795
+
796
+
797
+ BAKED_BLOB_DIR = Path(os.environ.get("PROGRAMBENCH_BAKED_BLOB_DIR", "/tests/blobs"))
798
+
799
+
800
+ def resolve_blob_dir(instance_id: str, metadata: dict[str, Any]) -> Path:
801
+ """Locate the per-instance blob directory.
802
+
803
+ Resolution order:
804
+
805
+ 1. ``/tests/blobs/`` if pre-fetched into the task at generation time
806
+ (``programbench-adapter --download-blobs``). Verifier-only mount, so
807
+ agent never sees these.
808
+ 2. ``PROGRAMBENCH_BLOB_DIR`` env override pointing at an HF-cache-shaped
809
+ tree on disk (``<dir>/<instance_id>/tests/<branch>.tar.gz``). Useful
810
+ for offline reruns sharing a cache across many tasks.
811
+ 3. ``huggingface_hub.snapshot_download`` from
812
+ ``programbench/ProgramBench-Tests`` (default repo, ``main`` revision).
813
+
814
+ The returned directory contains ``tests/<branch>.tar.gz`` per active
815
+ branch — same shape as ``programbench/ProgramBench-Tests/<instance_id>/``
816
+ on HF.
817
+ """
818
+ if BAKED_BLOB_DIR.exists() and (BAKED_BLOB_DIR / "tests").exists():
819
+ return BAKED_BLOB_DIR
820
+
821
+ local = os.environ.get("PROGRAMBENCH_BLOB_DIR", "").strip()
822
+ if local:
823
+ candidate = Path(local) / instance_id
824
+ if candidate.exists():
825
+ return candidate
826
+ raise FileNotFoundError(
827
+ f"PROGRAMBENCH_BLOB_DIR set but {candidate} does not exist"
828
+ )
829
+
830
+ repo_id = os.environ.get("PROGRAMBENCH_HF_REPO") or metadata.get(
831
+ "hf_repo_id", DEFAULT_HF_REPO_ID
832
+ )
833
+ revision = os.environ.get("PROGRAMBENCH_HF_REVISION") or metadata.get(
834
+ "hf_revision", DEFAULT_HF_REVISION
835
+ )
836
+
837
+ from huggingface_hub import snapshot_download
838
+
839
+ cache_root = Path(
840
+ snapshot_download(
841
+ repo_id,
842
+ repo_type="dataset",
843
+ revision=revision,
844
+ allow_patterns=f"{instance_id}/**",
845
+ )
846
+ )
847
+ blob_dir = cache_root / instance_id
848
+ if not blob_dir.exists():
849
+ raise FileNotFoundError(
850
+ f"HF blob directory missing for {instance_id} at {blob_dir}"
851
+ )
852
+ return blob_dir
853
+
854
+
855
+ def evaluate(metadata: dict[str, Any]) -> dict[str, Any]:
856
+ bootstrap_toolchain_path()
857
+ branches = metadata.get("branches", {})
858
+ active_branch_items = [
859
+ (name, info) for name, info in branches.items() if not info.get("ignored")
860
+ ]
861
+ result: dict[str, Any] = {
862
+ "test_results": [],
863
+ "error_code": None,
864
+ "error_details": None,
865
+ "log": [],
866
+ "solution_branch": "submission",
867
+ "test_branches": [name for name, _ in active_branch_items],
868
+ "test_branch_errors": {},
869
+ "executable_hash": None,
870
+ "warnings": [],
871
+ }
872
+
873
+ instance_id = metadata["instance_id"]
874
+
875
+ compile_timeout = int(os.environ.get("PROGRAMBENCH_COMPILE_TIMEOUT", "900"))
876
+ branch_timeout = int(os.environ.get("PROGRAMBENCH_BRANCH_TIMEOUT", "3600"))
877
+ branch_retries_max = int(os.environ.get("PROGRAMBENCH_BRANCH_RETRIES", "2"))
878
+
879
+ def fail_all(error_code: str, details: str) -> dict[str, Any]:
880
+ result["error_code"] = error_code
881
+ result["error_details"] = details
882
+ for branch, info in active_branch_items:
883
+ inject_not_run(result, branch, branch_tests(info), error_code)
884
+ return result
885
+
886
+ with tempfile.TemporaryDirectory(prefix="programbench-eval-") as tmp:
887
+ compiled_snapshot = Path(tmp) / "compiled"
888
+
889
+ started = time.monotonic()
890
+ removed = remove_hashed_files(
891
+ WORKSPACE, set(metadata.get("eval_clean_hashes", []))
892
+ )
893
+ result["log"].append(
894
+ {
895
+ "step": "remove_hashed_files",
896
+ "command": "remove files matching eval_clean_hashes",
897
+ "wall_time": time.monotonic() - started,
898
+ "output": "".join(f"removed '{path}'\n" for path in removed),
899
+ "returncode": 0,
900
+ "exception_info": "",
901
+ }
902
+ )
903
+
904
+ compile_sh = WORKSPACE / "compile.sh"
905
+ if not compile_sh.exists():
906
+ return fail_all(
907
+ "missing_compile_sh", "submission did not contain compile.sh"
908
+ )
909
+
910
+ seed = (
911
+ "if [ ! -d .git ]; then "
912
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
913
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
914
+ "git -c init.defaultBranch=gold init -q && "
915
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false add -A && "
916
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
917
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
918
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false commit -q --allow-empty -m gold; "
919
+ "fi"
920
+ )
921
+ try:
922
+ result["log"].append(
923
+ run_step(seed, WORKSPACE, timeout=300, step="seed_git")
924
+ )
925
+ compile_log = run_step(
926
+ "chmod +x ./compile.sh && ./compile.sh",
927
+ WORKSPACE,
928
+ timeout=compile_timeout,
929
+ step="compile",
930
+ accept_failure=True,
931
+ )
932
+ result["log"].append(compile_log)
933
+ if compile_log["returncode"]:
934
+ return fail_all("compile_failed", compile_log["output"])
935
+ executable = WORKSPACE / "executable"
936
+ if not executable.exists():
937
+ return fail_all(
938
+ "missing_executable",
939
+ "compile.sh completed but did not create ./executable",
940
+ )
941
+ STASHED_EXECUTABLE.parent.mkdir(parents=True, exist_ok=True)
942
+ # `move` (not copy) so /workspace doesn't keep a parallel copy of
943
+ # the agent's executable during the stash→restore window. Mirrors
944
+ # upstream `mv ./executable {STASHED}` (eval.py:472).
945
+ shutil.move(str(executable), STASHED_EXECUTABLE)
946
+ result["executable_hash"] = sha256(STASHED_EXECUTABLE)
947
+ result["log"].append(
948
+ run_step(
949
+ "pip3 install -q --disable-pip-version-check pytest-rerunfailures",
950
+ WORKSPACE,
951
+ timeout=120,
952
+ step="install_rerunfailures",
953
+ accept_failure=True,
954
+ )
955
+ )
956
+ has_rerunfailures = result["log"][-1]["returncode"] == 0
957
+ handoff_removed = remove_oracle_handoff_artifacts()
958
+ if handoff_removed:
959
+ result["log"].append(
960
+ {
961
+ "step": "remove_oracle_handoff",
962
+ "command": "remove oracle handoff artifacts from workspace",
963
+ "wall_time": 0.0,
964
+ "output": "".join(
965
+ f"removed '{name}'\n" for name in handoff_removed
966
+ ),
967
+ "returncode": 0,
968
+ "exception_info": "",
969
+ }
970
+ )
971
+ snapshot_workspace(compiled_snapshot)
972
+ except Exception as exc:
973
+ return fail_all(type(exc).__name__, str(exc))
974
+
975
+ try:
976
+ blob_dir = resolve_blob_dir(instance_id, metadata)
977
+ except Exception as exc:
978
+ details = f"{type(exc).__name__}: {exc}"
979
+ for branch, info in active_branch_items:
980
+ result["test_branch_errors"][branch] = [
981
+ {
982
+ "error_code": "blob_resolution_failed",
983
+ "error_details": details,
984
+ }
985
+ ]
986
+ inject_not_run(
987
+ result, branch, branch_tests(info), "blob_resolution_failed"
988
+ )
989
+ return result
990
+
991
+ for branch, info in active_branch_items:
992
+ tests = branch_tests(info)
993
+ blob = blob_dir / "tests" / f"{branch}.tar.gz"
994
+ if not blob.exists():
995
+ result["test_branch_errors"][branch] = [
996
+ {"error_code": "missing_test_blob", "error_details": blob.name}
997
+ ]
998
+ inject_not_run(result, branch, tests, "missing_test_blob")
999
+ continue
1000
+
1001
+ best_xml = ""
1002
+ best_useful = -1
1003
+ attempts_left = branch_retries_max
1004
+ serial = bool(metadata.get("force_serial_branches"))
1005
+ branch_log: list[dict[str, Any]] = []
1006
+ # (crashes, n_testcases, failures) per attempt — early-exit when two
1007
+ # consecutive attempts are identical (deterministic failure, not
1008
+ # contention). Mirrors upstream eval.py:624.
1009
+ attempt_history: list[tuple[int, int, int]] = []
1010
+ branch_ignored = {
1011
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
1012
+ }
1013
+ n_expected = len([name for name in tests if name not in branch_ignored])
1014
+
1015
+ def merge_best_xml(raw_xml: str) -> None:
1016
+ try:
1017
+ parsed, warnings = parse_junit(
1018
+ raw_xml, branch, list(info.get("tests", [])), branch_ignored
1019
+ )
1020
+ except Exception as exc:
1021
+ result["test_branch_errors"][branch] = [
1022
+ {"error_code": "xml_parse_error", "error_details": str(exc)}
1023
+ ]
1024
+ inject_not_run(result, branch, tests, "xml_parse_error")
1025
+ else:
1026
+ result["test_results"].extend(parsed)
1027
+ result["warnings"].extend(warnings)
1028
+
1029
+ while True:
1030
+ branch_log.append(cleanup_lingering_processes())
1031
+ restore_workspace(compiled_snapshot)
1032
+ extract_trusted_blob(blob, WORKSPACE)
1033
+ restore_reference_executable()
1034
+ actual_hash = sha256(WORKSPACE / "executable")
1035
+ if actual_hash != result["executable_hash"]:
1036
+ result["test_branch_errors"][branch] = [
1037
+ {
1038
+ "error_code": "executable_hash_mismatch",
1039
+ "error_details": (
1040
+ f"expected {result['executable_hash']}, got {actual_hash}"
1041
+ ),
1042
+ }
1043
+ ]
1044
+ inject_not_run(result, branch, tests, "executable_hash_mismatch")
1045
+ break
1046
+ run_sh = WORKSPACE / "eval" / "run.sh"
1047
+ if not run_sh.exists():
1048
+ result["test_branch_errors"][branch] = [
1049
+ {
1050
+ "error_code": "missing_run_sh",
1051
+ "error_details": "eval/run.sh missing",
1052
+ }
1053
+ ]
1054
+ inject_not_run(result, branch, tests, "missing_run_sh")
1055
+ break
1056
+ # Upstream rewrites thread→signal so xdist workers fail cleanly
1057
+ # instead of os._exit(1) on timeout. That works in fresh
1058
+ # containers per branch; here we reuse one container and
1059
+ # signal timeouts leave TUI/log-watcher subprocesses alive
1060
+ # (e.g. lazygit --logs + tail -f), wedging pytest for up to
1061
+ # branch_timeout. Keep the blob's thread method and rely on
1062
+ # cleanup_lingering_processes + serial fallback after crashes.
1063
+ env = branch_env(
1064
+ serial=serial,
1065
+ has_rerunfailures=has_rerunfailures,
1066
+ extras=metadata.get("branch_env"),
1067
+ )
1068
+ branch_log.append(
1069
+ run_step(
1070
+ "rm -f eval/results.xml results.xml",
1071
+ WORKSPACE,
1072
+ timeout=120,
1073
+ step="clean_stale_results",
1074
+ accept_failure=True,
1075
+ )
1076
+ )
1077
+ if serial:
1078
+ prepare_serial_run_sh(run_sh)
1079
+ run_entry = run_step(
1080
+ run_tests_command(serial=serial),
1081
+ WORKSPACE,
1082
+ timeout=branch_timeout,
1083
+ env=env,
1084
+ step="run_tests",
1085
+ accept_failure=True,
1086
+ )
1087
+ branch_log.append(run_entry)
1088
+ branch_log.append(cleanup_lingering_processes())
1089
+ xml_path = find_results_xml()
1090
+ if xml_path is None:
1091
+ if best_xml:
1092
+ merge_best_xml(best_xml)
1093
+ break
1094
+ if attempts_left <= 0:
1095
+ result["test_branch_errors"][branch] = [
1096
+ {
1097
+ "error_code": "missing_results_xml",
1098
+ "error_details": "eval/results.xml was not produced",
1099
+ }
1100
+ ]
1101
+ inject_not_run(result, branch, tests, "missing_results_xml")
1102
+ break
1103
+ attempts_left -= 1
1104
+ serial = True
1105
+ continue
1106
+ raw_xml = xml_path.read_text(errors="replace")
1107
+ crashes, n_tests, failures, missing = branch_attempt_metrics(
1108
+ raw_xml,
1109
+ run_output=run_entry.get("output", ""),
1110
+ expected_tests=n_expected,
1111
+ )
1112
+ attempt_history.append((crashes, n_tests, failures))
1113
+ useful = count_junit_passed(raw_xml)
1114
+ if useful > best_useful:
1115
+ best_xml = raw_xml
1116
+ best_useful = useful
1117
+ deterministic = (
1118
+ len(attempt_history) >= 2
1119
+ and attempt_history[-1] == attempt_history[-2]
1120
+ )
1121
+ retry = needs_serial_retry(
1122
+ serial=serial,
1123
+ crashes=crashes,
1124
+ missing=missing,
1125
+ failures=failures,
1126
+ n_tests=n_tests,
1127
+ expected_tests=n_expected,
1128
+ run_output=run_entry.get("output", ""),
1129
+ )
1130
+ if not retry or attempts_left <= 0 or deterministic:
1131
+ merge_best_xml(best_xml)
1132
+ break
1133
+ attempts_left -= 1
1134
+ serial = True
1135
+ for entry in branch_log:
1136
+ entry["branch"] = branch
1137
+ result["log"].extend(branch_log)
1138
+
1139
+ return result
1140
+
1141
+
1142
+ def write_outputs(result: dict[str, Any], metadata: dict[str, Any]) -> None:
1143
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1144
+ write_json(LOG_DIR / "programbench_eval.json", result)
1145
+ write_json(LOG_DIR / "harbor_diagnostics.json", diagnostics(result, metadata))
1146
+ rewards = summarize(result, metadata)
1147
+ write_json(LOG_DIR / "reward.json", rewards)
1148
+ (LOG_DIR / "reward.txt").write_text(str(rewards["reward"]))
1149
+
1150
+
1151
+ def main() -> None:
1152
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1153
+ log_path = LOG_DIR / "programbench_eval.log"
1154
+ metadata = json.loads(METADATA_PATH.read_text())
1155
+ branches = metadata.get("branches", {})
1156
+ try:
1157
+ result = evaluate(metadata)
1158
+ except Exception as exc:
1159
+ error_code = type(exc).__name__
1160
+ result = {
1161
+ "test_results": [],
1162
+ "error_code": error_code,
1163
+ "error_details": str(exc),
1164
+ "log": [
1165
+ {
1166
+ "step": "evaluator_exception",
1167
+ "exception_info": traceback.format_exc(),
1168
+ "returncode": 1,
1169
+ }
1170
+ ],
1171
+ "solution_branch": "submission",
1172
+ "test_branches": [
1173
+ name for name, info in branches.items() if not info.get("ignored")
1174
+ ],
1175
+ "test_branch_errors": {
1176
+ "__evaluator__": [{"error_code": error_code, "error_details": str(exc)}]
1177
+ },
1178
+ "executable_hash": None,
1179
+ "warnings": [],
1180
+ }
1181
+ for branch, info in branches.items():
1182
+ if info.get("ignored"):
1183
+ continue
1184
+ inject_not_run(result, branch, branch_tests(info), error_code)
1185
+ log_path.write_text(traceback.format_exc())
1186
+ else:
1187
+ log_path.write_text("")
1188
+ write_outputs(result, metadata)
1189
+
1190
+
1191
+ if __name__ == "__main__":
1192
+ main()