scalingX commited on
Commit
3af02f2
·
verified ·
1 Parent(s): 81d0f4c

Add 10000 GitHub Trending pr_diff environments (part 105)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/ublue-os__bazzite-6216/tests/test.sh +25 -0
  2. tasks/ublue-os__bazzite-6216/tests/verifier.py +737 -0
  3. tasks/ublue-os__bazzite-6229/environment/Dockerfile +37 -0
  4. tasks/ublue-os__bazzite-6229/instruction.md +32 -0
  5. tasks/ublue-os__bazzite-6229/solution/patch.diff +176 -0
  6. tasks/ublue-os__bazzite-6229/solution/solve.sh +6 -0
  7. tasks/ublue-os__bazzite-6229/task.toml +72 -0
  8. tasks/ublue-os__bazzite-6229/tests/capture.py +96 -0
  9. tasks/ublue-os__bazzite-6229/tests/instruction.md +32 -0
  10. tasks/ublue-os__bazzite-6229/tests/oracle.patch +176 -0
  11. tasks/ublue-os__bazzite-6229/tests/test.sh +25 -0
  12. tasks/ublue-os__bazzite-6229/tests/verifier.py +737 -0
  13. tasks/ublue-os__bazzite-6231/environment/Dockerfile +37 -0
  14. tasks/ublue-os__bazzite-6231/instruction.md +41 -0
  15. tasks/ublue-os__bazzite-6231/solution/patch.diff +22 -0
  16. tasks/ublue-os__bazzite-6231/solution/solve.sh +6 -0
  17. tasks/ublue-os__bazzite-6231/task.toml +68 -0
  18. tasks/ublue-os__bazzite-6231/tests/capture.py +96 -0
  19. tasks/ublue-os__bazzite-6231/tests/instruction.md +41 -0
  20. tasks/ublue-os__bazzite-6231/tests/oracle.patch +22 -0
  21. tasks/ublue-os__bazzite-6231/tests/test.sh +25 -0
  22. tasks/ublue-os__bazzite-6231/tests/verifier.py +737 -0
  23. tasks/ublue-os__bazzite-6232/environment/Dockerfile +37 -0
  24. tasks/ublue-os__bazzite-6232/instruction.md +31 -0
  25. tasks/ublue-os__bazzite-6232/solution/patch.diff +15 -0
  26. tasks/ublue-os__bazzite-6232/solution/solve.sh +6 -0
  27. tasks/ublue-os__bazzite-6232/task.toml +68 -0
  28. tasks/ublue-os__bazzite-6232/tests/capture.py +96 -0
  29. tasks/ublue-os__bazzite-6232/tests/instruction.md +31 -0
  30. tasks/ublue-os__bazzite-6232/tests/oracle.patch +15 -0
  31. tasks/ublue-os__bazzite-6232/tests/test.sh +25 -0
  32. tasks/ublue-os__bazzite-6232/tests/verifier.py +737 -0
  33. tasks/ublue-os__bazzite-6234/environment/Dockerfile +37 -0
  34. tasks/ublue-os__bazzite-6234/instruction.md +20 -0
  35. tasks/ublue-os__bazzite-6234/solution/patch.diff +189 -0
  36. tasks/ublue-os__bazzite-6234/solution/solve.sh +6 -0
  37. tasks/ublue-os__bazzite-6234/task.toml +68 -0
  38. tasks/ublue-os__bazzite-6234/tests/capture.py +96 -0
  39. tasks/ublue-os__bazzite-6234/tests/instruction.md +20 -0
  40. tasks/ublue-os__bazzite-6234/tests/oracle.patch +189 -0
  41. tasks/ublue-os__bazzite-6234/tests/test.sh +25 -0
  42. tasks/ublue-os__bazzite-6234/tests/verifier.py +737 -0
  43. tasks/ublue-os__bazzite-6243/environment/Dockerfile +37 -0
  44. tasks/ublue-os__bazzite-6243/instruction.md +21 -0
  45. tasks/ublue-os__bazzite-6243/solution/patch.diff +38 -0
  46. tasks/ublue-os__bazzite-6243/solution/solve.sh +6 -0
  47. tasks/ublue-os__bazzite-6243/task.toml +68 -0
  48. tasks/ublue-os__bazzite-6243/tests/capture.py +96 -0
  49. tasks/ublue-os__bazzite-6243/tests/instruction.md +21 -0
  50. tasks/ublue-os__bazzite-6243/tests/oracle.patch +38 -0
tasks/ublue-os__bazzite-6216/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7e572db63e000dcd98b0c70f1c5da71f907ff358 > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/ublue-os__bazzite-6216/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/ublue-os__bazzite-6229/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin e1e1f97053a8332cdefae12e5f61d4696b0d940a 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard e1e1f97053a8332cdefae12e5f61d4696b0d940a \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base e1e1f97053a8332cdefae12e5f61d4696b0d940a \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/ublue-os__bazzite-6229/instruction.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(atlas8): sync with upstream PR
4
+
5
+ ## Description
6
+
7
+ also remove files that have previously been removed
8
+
9
+ <!---
10
+ Thank you for contributing to the Universal Blue project!
11
+ Here are some tips for you:
12
+
13
+ ## Thank you for contributing to the Universal Blue project!
14
+
15
+ Please [read the Contributor's Guide](https://universal-blue.org/contributing.html) before submitting a pull request.
16
+
17
+ In this project we follow [Semantic PRs][1] and [Conventional Commits][2] to describe features and fixes we made. It would be nice if you did too as we use this to generate changelogs with the right sections:
18
+
19
+ feat(deck): enable this deck specific feature
20
+ fix(ally): fix screen rotation on the ally
21
+ feat(gnome): Stuff that is GNOME specific
22
+
23
+ If you're unsure a generic `feat:` or `fix:` is fine! Did you already use this? Awesome, thanks again! Not sure what this all means? Here are some [more examples][3].
24
+
25
+ [1]: https://github.com/Ezard/semantic-prs
26
+ [2]: https://www.conventionalcommits.org/en/v1.0.0/#summary
27
+ [3]: https://www.conventionalcommits.org/en/v1.0.0/#examples
28
+ -->
29
+
30
+ ## Task
31
+
32
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6229/solution/patch.diff ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml
2
+ deleted file mode 100644
3
+ index d8e776ee..00000000
4
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml
5
+ +++ /dev/null
6
+ @@ -1,46 +0,0 @@
7
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
8
+ -# Schema version number
9
+ -version: 2
10
+ -
11
+ -# The type of configuration schema
12
+ -kind: CapabilityMap
13
+ -
14
+ -# Name for the device event map
15
+ -name: "Acer Atlas 8 Extra Buttons"
16
+ -
17
+ -# Unique identifier of the capability mapping
18
+ -id: acer_atlas8_hid_type2
19
+ -
20
+ -# Idle HID Report
21
+ -# Data: 9a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
22
+ -# BUF[1] = 0x02 = M1 Pressed
23
+ -# BUF[1] = 0x04 = M2 Pressed
24
+ -# BUF[1] = 0x06 = M1+M2 Pressed
25
+ -
26
+ -# This implementation is incomplete as the driver seems to currently be incapable
27
+ -# of sending a button event depending on which bit is inside the selected byte section
28
+ -# Guide button will also be included here once we have a kernel quirk in place for the button release signal that is missing
29
+ -mapping:
30
+ - - name: M1
31
+ - source_events:
32
+ - - hidraw:
33
+ - value_type: uint8
34
+ - byte_start: 1
35
+ - min_value: 255
36
+ - max_value: 255
37
+ - target_event:
38
+ - gamepad:
39
+ - button: RightPaddle1
40
+ - - name: M2
41
+ - source_events:
42
+ - - hidraw:
43
+ - value_type: uint8
44
+ - byte_start: 1
45
+ - min_value: 77
46
+ - max_value: 77
47
+ - target_event:
48
+ - gamepad:
49
+ - button: LeftPaddle1
50
+ -
51
+ -# List of events to filter from the source devices
52
+ -filtered_events: []
53
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml
54
+ deleted file mode 100644
55
+ index 289ec9af..00000000
56
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml
57
+ +++ /dev/null
58
+ @@ -1,26 +0,0 @@
59
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
60
+ -# Schema version number
61
+ -version: 2
62
+ -
63
+ -# The type of configuration schema
64
+ -kind: CapabilityMap
65
+ -
66
+ -# Name for the device event map
67
+ -name: "Acer Atlas 8 QAM"
68
+ -
69
+ -# Unique identifier of the capability mapping
70
+ -id: acer_atlas8_hid_type1
71
+ -
72
+ -# List of mapped events that are activated by a specific set of activation keys.
73
+ -mapping:
74
+ - - name: QAM
75
+ - source_events:
76
+ - - hidraw:
77
+ - value_type: bool
78
+ - byte_start: 2
79
+ - target_event:
80
+ - gamepad:
81
+ - button: QuickAccess
82
+ -
83
+ -# List of events to filter from the source devices
84
+ -filtered_events: []
85
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml
86
+ deleted file mode 100644
87
+ index 7007f850..00000000
88
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml
89
+ +++ /dev/null
90
+ @@ -1,27 +0,0 @@
91
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
92
+ -# Schema version number
93
+ -version: 1
94
+ -
95
+ -# The type of configuration schema
96
+ -kind: CapabilityMap
97
+ -
98
+ -# Name for the device event map
99
+ -name: "Acer Atlas 8"
100
+ -
101
+ -# Unique identifier of the capability mapping
102
+ -id: acer_atlas8
103
+ -
104
+ -# List of mapped events that are activated by a specific set of activation keys.
105
+ -mapping:
106
+ - # This capability map will make Guide and QAM accessible with hold actions
107
+ - # since the press/tap actions on these buttons do not work currently
108
+ - - name: Guide (hold)
109
+ - source_events:
110
+ - - keyboard: KeyLeftMeta
111
+ - - keyboard: KeyTab
112
+ - target_event:
113
+ - gamepad:
114
+ - button: Guide
115
+ -
116
+ -# List of events to filter from the source devices
117
+ -filtered_events: []
118
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
119
+ index 37541cd9..9a081290 100644
120
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
121
+ +++ b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
122
+ @@ -37,9 +37,19 @@ mapping:
123
+ - hidraw:
124
+ value_type: bool
125
+ byte_start: 3
126
+ + bit_offset: 4
127
+ target_event:
128
+ gamepad:
129
+ button: QuickAccess2
130
+ + - name: Guide (hold)
131
+ + source_events:
132
+ + - hidraw:
133
+ + value_type: bool
134
+ + byte_start: 3
135
+ + bit_offset: 1
136
+ + target_event:
137
+ + gamepad:
138
+ + button: Guide
139
+
140
+ # List of events to filter from the source devices
141
+ filtered_events: []
142
+ diff --git a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
143
+ index 6083ad26..ec5aea74 100644
144
+ --- a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
145
+ +++ b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
146
+ @@ -15,19 +15,14 @@ matches:
147
+ sys_vendor: Acer
148
+
149
+ source_devices:
150
+ - - group: gamepad
151
+ - evdev:
152
+ - name: " Xbox360 Controller for Windows Keyboard"
153
+ - vendor_id: "0502"
154
+ - product_id: "f901"
155
+ - handler: event*
156
+ + # Atlas 8 Gamepad
157
+ - group: gamepad
158
+ evdev:
159
+ name: Generic X-Box pad
160
+ vendor_id: "0502"
161
+ product_id: "f901"
162
+ handler: event*
163
+ - # Atlas 8 QAM button
164
+ + # Atlas 8 Guide and QAM buttons
165
+ - group: gamepad
166
+ hidraw:
167
+ vendor_id: 0x0502
168
+ @@ -42,8 +37,6 @@ source_devices:
169
+ interface_num: 1
170
+ capability_map_id: acer_atlas8_hid_type2
171
+
172
+ -capability_map_id: acer_atlas8
173
+ -
174
+ # The target input device(s) to emulate by default
175
+ target_devices:
176
+ - xbox-elite
tasks/ublue-os__bazzite-6229/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/ublue-os__bazzite-6229/task.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/ublue-os__bazzite-6229"
5
+ description = "feat(atlas8): sync with upstream PR"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "bazzite",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "ublue-os/bazzite"
19
+ ref = "e1e1f97053a8332cdefae12e5f61d4696b0d940a"
20
+ reference = "https://github.com/ublue-os/bazzite/pull/6229"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:50.980913+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:eb116ef92e453ba09241213f66a8aed3a0bcf1fdc8001a058adbe9b6aa4c3189"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-11-04T13:19:56Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml",
34
+ "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml",
35
+ "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml",
36
+ "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml",
37
+ "system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml",
38
+ ]
39
+ bootstrap_image = "python:3.12-slim"
40
+
41
+ [metadata.repo2env.reward_calibration]
42
+ baseline_reward = 0.0
43
+ loc_changed = 120
44
+ difficulty = "large"
45
+
46
+ [metadata.repo2env.evaluation]
47
+ schema_version = "1"
48
+ status = "unverified"
49
+ stage = "generation"
50
+ reason_codes = [
51
+ "validation_not_run",
52
+ ]
53
+ detail = "Generated task; validation has not been established."
54
+ provenance = "unknown"
55
+ evidence = []
56
+
57
+ [metadata.repo2env.reproducibility]
58
+ mode = "inline_dockerfile"
59
+ image_ref = "python:3.12-slim"
60
+ image_tag = "python:3.12-slim"
61
+ image_visibility = "public"
62
+ pushed_at = "2026-11-16T16:20:03.587263+00:00"
63
+ pushed_by = "scalingX"
64
+ inline_recipe_sha256 = "sha256:e1c72bf41c74f9342ae165a509f4de0c95f0f2f3c9693a7cc559c4b7390192fa"
65
+ inline_recipe_lines = 37
66
+ inline_recipe_source = "user_dockerfile"
67
+
68
+ [agent]
69
+ timeout_sec = 1800.0
70
+
71
+ [verifier]
72
+ timeout_sec = 300.0
tasks/ublue-os__bazzite-6229/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/ublue-os__bazzite-6229/tests/instruction.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(atlas8): sync with upstream PR
4
+
5
+ ## Description
6
+
7
+ also remove files that have previously been removed
8
+
9
+ <!---
10
+ Thank you for contributing to the Universal Blue project!
11
+ Here are some tips for you:
12
+
13
+ ## Thank you for contributing to the Universal Blue project!
14
+
15
+ Please [read the Contributor's Guide](https://universal-blue.org/contributing.html) before submitting a pull request.
16
+
17
+ In this project we follow [Semantic PRs][1] and [Conventional Commits][2] to describe features and fixes we made. It would be nice if you did too as we use this to generate changelogs with the right sections:
18
+
19
+ feat(deck): enable this deck specific feature
20
+ fix(ally): fix screen rotation on the ally
21
+ feat(gnome): Stuff that is GNOME specific
22
+
23
+ If you're unsure a generic `feat:` or `fix:` is fine! Did you already use this? Awesome, thanks again! Not sure what this all means? Here are some [more examples][3].
24
+
25
+ [1]: https://github.com/Ezard/semantic-prs
26
+ [2]: https://www.conventionalcommits.org/en/v1.0.0/#summary
27
+ [3]: https://www.conventionalcommits.org/en/v1.0.0/#examples
28
+ -->
29
+
30
+ ## Task
31
+
32
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6229/tests/oracle.patch ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml
2
+ deleted file mode 100644
3
+ index d8e776ee..00000000
4
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml
5
+ +++ /dev/null
6
+ @@ -1,46 +0,0 @@
7
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
8
+ -# Schema version number
9
+ -version: 2
10
+ -
11
+ -# The type of configuration schema
12
+ -kind: CapabilityMap
13
+ -
14
+ -# Name for the device event map
15
+ -name: "Acer Atlas 8 Extra Buttons"
16
+ -
17
+ -# Unique identifier of the capability mapping
18
+ -id: acer_atlas8_hid_type2
19
+ -
20
+ -# Idle HID Report
21
+ -# Data: 9a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
22
+ -# BUF[1] = 0x02 = M1 Pressed
23
+ -# BUF[1] = 0x04 = M2 Pressed
24
+ -# BUF[1] = 0x06 = M1+M2 Pressed
25
+ -
26
+ -# This implementation is incomplete as the driver seems to currently be incapable
27
+ -# of sending a button event depending on which bit is inside the selected byte section
28
+ -# Guide button will also be included here once we have a kernel quirk in place for the button release signal that is missing
29
+ -mapping:
30
+ - - name: M1
31
+ - source_events:
32
+ - - hidraw:
33
+ - value_type: uint8
34
+ - byte_start: 1
35
+ - min_value: 255
36
+ - max_value: 255
37
+ - target_event:
38
+ - gamepad:
39
+ - button: RightPaddle1
40
+ - - name: M2
41
+ - source_events:
42
+ - - hidraw:
43
+ - value_type: uint8
44
+ - byte_start: 1
45
+ - min_value: 77
46
+ - max_value: 77
47
+ - target_event:
48
+ - gamepad:
49
+ - button: LeftPaddle1
50
+ -
51
+ -# List of events to filter from the source devices
52
+ -filtered_events: []
53
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml
54
+ deleted file mode 100644
55
+ index 289ec9af..00000000
56
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml
57
+ +++ /dev/null
58
+ @@ -1,26 +0,0 @@
59
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
60
+ -# Schema version number
61
+ -version: 2
62
+ -
63
+ -# The type of configuration schema
64
+ -kind: CapabilityMap
65
+ -
66
+ -# Name for the device event map
67
+ -name: "Acer Atlas 8 QAM"
68
+ -
69
+ -# Unique identifier of the capability mapping
70
+ -id: acer_atlas8_hid_type1
71
+ -
72
+ -# List of mapped events that are activated by a specific set of activation keys.
73
+ -mapping:
74
+ - - name: QAM
75
+ - source_events:
76
+ - - hidraw:
77
+ - value_type: bool
78
+ - byte_start: 2
79
+ - target_event:
80
+ - gamepad:
81
+ - button: QuickAccess
82
+ -
83
+ -# List of events to filter from the source devices
84
+ -filtered_events: []
85
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml
86
+ deleted file mode 100644
87
+ index 7007f850..00000000
88
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml
89
+ +++ /dev/null
90
+ @@ -1,27 +0,0 @@
91
+ -# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json
92
+ -# Schema version number
93
+ -version: 1
94
+ -
95
+ -# The type of configuration schema
96
+ -kind: CapabilityMap
97
+ -
98
+ -# Name for the device event map
99
+ -name: "Acer Atlas 8"
100
+ -
101
+ -# Unique identifier of the capability mapping
102
+ -id: acer_atlas8
103
+ -
104
+ -# List of mapped events that are activated by a specific set of activation keys.
105
+ -mapping:
106
+ - # This capability map will make Guide and QAM accessible with hold actions
107
+ - # since the press/tap actions on these buttons do not work currently
108
+ - - name: Guide (hold)
109
+ - source_events:
110
+ - - keyboard: KeyLeftMeta
111
+ - - keyboard: KeyTab
112
+ - target_event:
113
+ - gamepad:
114
+ - button: Guide
115
+ -
116
+ -# List of events to filter from the source devices
117
+ -filtered_events: []
118
+ diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
119
+ index 37541cd9..9a081290 100644
120
+ --- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
121
+ +++ b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml
122
+ @@ -37,9 +37,19 @@ mapping:
123
+ - hidraw:
124
+ value_type: bool
125
+ byte_start: 3
126
+ + bit_offset: 4
127
+ target_event:
128
+ gamepad:
129
+ button: QuickAccess2
130
+ + - name: Guide (hold)
131
+ + source_events:
132
+ + - hidraw:
133
+ + value_type: bool
134
+ + byte_start: 3
135
+ + bit_offset: 1
136
+ + target_event:
137
+ + gamepad:
138
+ + button: Guide
139
+
140
+ # List of events to filter from the source devices
141
+ filtered_events: []
142
+ diff --git a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
143
+ index 6083ad26..ec5aea74 100644
144
+ --- a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
145
+ +++ b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml
146
+ @@ -15,19 +15,14 @@ matches:
147
+ sys_vendor: Acer
148
+
149
+ source_devices:
150
+ - - group: gamepad
151
+ - evdev:
152
+ - name: " Xbox360 Controller for Windows Keyboard"
153
+ - vendor_id: "0502"
154
+ - product_id: "f901"
155
+ - handler: event*
156
+ + # Atlas 8 Gamepad
157
+ - group: gamepad
158
+ evdev:
159
+ name: Generic X-Box pad
160
+ vendor_id: "0502"
161
+ product_id: "f901"
162
+ handler: event*
163
+ - # Atlas 8 QAM button
164
+ + # Atlas 8 Guide and QAM buttons
165
+ - group: gamepad
166
+ hidraw:
167
+ vendor_id: 0x0502
168
+ @@ -42,8 +37,6 @@ source_devices:
169
+ interface_num: 1
170
+ capability_map_id: acer_atlas8_hid_type2
171
+
172
+ -capability_map_id: acer_atlas8
173
+ -
174
+ # The target input device(s) to emulate by default
175
+ target_devices:
176
+ - xbox-elite
tasks/ublue-os__bazzite-6229/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e1e1f97053a8332cdefae12e5f61d4696b0d940a > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/ublue-os__bazzite-6229/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/ublue-os__bazzite-6231/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin e1e1f97053a8332cdefae12e5f61d4696b0d940a 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard e1e1f97053a8332cdefae12e5f61d4696b0d940a \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base e1e1f97053a8332cdefae12e5f61d4696b0d940a \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/ublue-os__bazzite-6231/instruction.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** chore(deps): update dependency ubuntu to v26
4
+
5
+ ## Description
6
+
7
+ This PR contains the following updates:
8
+
9
+ | Package | Type | Update | Change |
10
+ |---|---|---|---|
11
+ | [ubuntu](https://redirect.github.com/actions/runner-images) | github-runner | major | `24.04` → `26.04` |
12
+
13
+ ---
14
+
15
+ ### Configuration
16
+
17
+ 📅 **Schedule**: (UTC)
18
+
19
+ - Branch creation
20
+ - At any time (no schedule defined)
21
+ - Automerge
22
+ - At any time (no schedule defined)
23
+
24
+ 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
25
+
26
+ ♻ **Rebasing**: Never, or you tick the rebase/retry checkbox.
27
+
28
+ 🔕 **Ignore**: Close this PR and you won't be reminded about this update again.
29
+
30
+ ---
31
+
32
+ - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
33
+
34
+ ---
35
+
36
+ This PR has been generated by [Mend Renovate CLI](https://redirect.github.com/renovatebot/renovate).
37
+ <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMTMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIxMy4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
38
+
39
+ ## Task
40
+
41
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6231/solution/patch.diff ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
2
+ index 4ccf421b..133f55cc 100644
3
+ --- a/.github/workflows/build.yml
4
+ +++ b/.github/workflows/build.yml
5
+ @@ -448,7 +448,7 @@ jobs:
6
+
7
+ kickoff_gamemode_news:
8
+ name: Build Game Mode Announcements
9
+ - runs-on: ubuntu-24.04
10
+ + runs-on: ubuntu-26.04
11
+ needs: [generate_release]
12
+ if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request'
13
+ steps:
14
+ @@ -472,7 +472,7 @@ jobs:
15
+ client-payload: '{"branch": "${{ steps.get-target.outputs.target }}"}'
16
+
17
+ kickoff_bazzite_dx:
18
+ - runs-on: ubuntu-24.04
19
+ + runs-on: ubuntu-26.04
20
+ needs: [generate_release]
21
+ if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
22
+ steps:
tasks/ublue-os__bazzite-6231/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/ublue-os__bazzite-6231/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/ublue-os__bazzite-6231"
5
+ description = "chore(deps): update dependency ubuntu to v26"
6
+
7
+ [metadata]
8
+ difficulty = "easy"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "bazzite",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "ublue-os/bazzite"
19
+ ref = "e1e1f97053a8332cdefae12e5f61d4696b0d940a"
20
+ reference = "https://github.com/ublue-os/bazzite/pull/6231"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:50.976118+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:8735496b520936c010c54c743fefb8c0fe794be8765daaa74fe581933c430a7f"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-11-05T06:26:34Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ ".github/workflows/build.yml",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 4
40
+ difficulty = "trivial"
41
+
42
+ [metadata.repo2env.evaluation]
43
+ schema_version = "1"
44
+ status = "unverified"
45
+ stage = "generation"
46
+ reason_codes = [
47
+ "validation_not_run",
48
+ ]
49
+ detail = "Generated task; validation has not been established."
50
+ provenance = "unknown"
51
+ evidence = []
52
+
53
+ [metadata.repo2env.reproducibility]
54
+ mode = "inline_dockerfile"
55
+ image_ref = "python:3.12-slim"
56
+ image_tag = "python:3.12-slim"
57
+ image_visibility = "public"
58
+ pushed_at = "2026-11-16T16:20:03.587819+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:e1c72bf41c74f9342ae165a509f4de0c95f0f2f3c9693a7cc559c4b7390192fa"
61
+ inline_recipe_lines = 37
62
+ inline_recipe_source = "user_dockerfile"
63
+
64
+ [agent]
65
+ timeout_sec = 1800.0
66
+
67
+ [verifier]
68
+ timeout_sec = 300.0
tasks/ublue-os__bazzite-6231/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/ublue-os__bazzite-6231/tests/instruction.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** chore(deps): update dependency ubuntu to v26
4
+
5
+ ## Description
6
+
7
+ This PR contains the following updates:
8
+
9
+ | Package | Type | Update | Change |
10
+ |---|---|---|---|
11
+ | [ubuntu](https://redirect.github.com/actions/runner-images) | github-runner | major | `24.04` → `26.04` |
12
+
13
+ ---
14
+
15
+ ### Configuration
16
+
17
+ 📅 **Schedule**: (UTC)
18
+
19
+ - Branch creation
20
+ - At any time (no schedule defined)
21
+ - Automerge
22
+ - At any time (no schedule defined)
23
+
24
+ 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
25
+
26
+ ♻ **Rebasing**: Never, or you tick the rebase/retry checkbox.
27
+
28
+ 🔕 **Ignore**: Close this PR and you won't be reminded about this update again.
29
+
30
+ ---
31
+
32
+ - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
33
+
34
+ ---
35
+
36
+ This PR has been generated by [Mend Renovate CLI](https://redirect.github.com/renovatebot/renovate).
37
+ <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMTMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIxMy4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
38
+
39
+ ## Task
40
+
41
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6231/tests/oracle.patch ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
2
+ index 4ccf421b..133f55cc 100644
3
+ --- a/.github/workflows/build.yml
4
+ +++ b/.github/workflows/build.yml
5
+ @@ -448,7 +448,7 @@ jobs:
6
+
7
+ kickoff_gamemode_news:
8
+ name: Build Game Mode Announcements
9
+ - runs-on: ubuntu-24.04
10
+ + runs-on: ubuntu-26.04
11
+ needs: [generate_release]
12
+ if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request'
13
+ steps:
14
+ @@ -472,7 +472,7 @@ jobs:
15
+ client-payload: '{"branch": "${{ steps.get-target.outputs.target }}"}'
16
+
17
+ kickoff_bazzite_dx:
18
+ - runs-on: ubuntu-24.04
19
+ + runs-on: ubuntu-26.04
20
+ needs: [generate_release]
21
+ if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
22
+ steps:
tasks/ublue-os__bazzite-6231/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e1e1f97053a8332cdefae12e5f61d4696b0d940a > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/ublue-os__bazzite-6231/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/ublue-os__bazzite-6232/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 64fa640520bcbd038abb2cfdfdf725f87e7a717c 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 64fa640520bcbd038abb2cfdfdf725f87e7a717c \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 64fa640520bcbd038abb2cfdfdf725f87e7a717c \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/ublue-os__bazzite-6232/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix(steam-firstrun): show the Portuguese message for pt_BR locales
4
+
5
+ ## Description
6
+
7
+ `bazzite-steam-firstrun` reduces the locale to its language part:
8
+
9
+ ```bash
10
+ lang=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)
11
+ ```
12
+
13
+ For `LANG=pt_BR.UTF-8` this gives `pt`, so the `"pt_BR"` case added in #4750 never matched and Brazilian users got the English message. This PR changes the case to `"pt"`.
14
+
15
+ Side effect: `pt_PT` users now get this (Brazilian Portuguese) message instead of English. `ntfs-exfat-monitor-script` already uses a single `"pt"` case in the same way.
16
+
17
+ Tested by running the whole script with different `LANG` values, with `kdialog` and `curl` replaced by stubs that print what would be shown:
18
+
19
+ | `LANG` | Before | After |
20
+ |---|---|---|
21
+ | `pt_BR.UTF-8` | English | Portuguese |
22
+ | `pt_PT.UTF-8` | English | Portuguese |
23
+ | `uk_UA.UTF-8`, `de_DE.UTF-8`, `en_US.UTF-8`, `C.UTF-8` | unchanged | unchanged |
24
+
25
+ ShellCheck reports the same three pre-existing warnings before and after the change.
26
+
27
+ Written with AI assistance.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64fa640520bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6232/solution/patch.diff ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
2
+ index f1c4fb93..bcefb5a8 100755
3
+ --- a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
4
+ +++ b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
5
+ @@ -36,8 +36,8 @@ case $lang in
6
+ "it")
7
+ info_text=("Steam è in fase di download. Attendere prego. Il download del client Steam potrebbe richiedere alcuni minuti.")
8
+ ;;
9
+ -#brazilian portuguese
10
+ - "pt_BR")
11
+ +#portuguese (brazilian translation)
12
+ + "pt")
13
+ info_text=("O Steam está sendo executado pela primeira vez. Por favor, aguarde. O download do cliente Steam pode levar alguns minutos.")
14
+ ;;
15
+ #ukrainian
tasks/ublue-os__bazzite-6232/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/ublue-os__bazzite-6232/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/ublue-os__bazzite-6232"
5
+ description = "fix(steam-firstrun): show the Portuguese message for pt_BR locales"
6
+
7
+ [metadata]
8
+ difficulty = "easy"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "bazzite",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "ublue-os/bazzite"
19
+ ref = "64fa640520bcbd038abb2cfdfdf725f87e7a717c"
20
+ reference = "https://github.com/ublue-os/bazzite/pull/6232"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:50.974571+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:1d7d922c5959df60cd9f083bb5a973049f4fe35c7e7b7f2929bd637b36b64f4a"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-11-04T19:49:31Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "system_files/desktop/shared/usr/bin/bazzite-steam-firstrun",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 4
40
+ difficulty = "trivial"
41
+
42
+ [metadata.repo2env.evaluation]
43
+ schema_version = "1"
44
+ status = "unverified"
45
+ stage = "generation"
46
+ reason_codes = [
47
+ "validation_not_run",
48
+ ]
49
+ detail = "Generated task; validation has not been established."
50
+ provenance = "unknown"
51
+ evidence = []
52
+
53
+ [metadata.repo2env.reproducibility]
54
+ mode = "inline_dockerfile"
55
+ image_ref = "python:3.12-slim"
56
+ image_tag = "python:3.12-slim"
57
+ image_visibility = "public"
58
+ pushed_at = "2026-11-16T16:20:03.588387+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:8efe941f13d1b53d0d90fb06826c16145b19741305cd69c07df8ef0b6f35feb8"
61
+ inline_recipe_lines = 37
62
+ inline_recipe_source = "user_dockerfile"
63
+
64
+ [agent]
65
+ timeout_sec = 1800.0
66
+
67
+ [verifier]
68
+ timeout_sec = 300.0
tasks/ublue-os__bazzite-6232/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/ublue-os__bazzite-6232/tests/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix(steam-firstrun): show the Portuguese message for pt_BR locales
4
+
5
+ ## Description
6
+
7
+ `bazzite-steam-firstrun` reduces the locale to its language part:
8
+
9
+ ```bash
10
+ lang=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)
11
+ ```
12
+
13
+ For `LANG=pt_BR.UTF-8` this gives `pt`, so the `"pt_BR"` case added in #4750 never matched and Brazilian users got the English message. This PR changes the case to `"pt"`.
14
+
15
+ Side effect: `pt_PT` users now get this (Brazilian Portuguese) message instead of English. `ntfs-exfat-monitor-script` already uses a single `"pt"` case in the same way.
16
+
17
+ Tested by running the whole script with different `LANG` values, with `kdialog` and `curl` replaced by stubs that print what would be shown:
18
+
19
+ | `LANG` | Before | After |
20
+ |---|---|---|
21
+ | `pt_BR.UTF-8` | English | Portuguese |
22
+ | `pt_PT.UTF-8` | English | Portuguese |
23
+ | `uk_UA.UTF-8`, `de_DE.UTF-8`, `en_US.UTF-8`, `C.UTF-8` | unchanged | unchanged |
24
+
25
+ ShellCheck reports the same three pre-existing warnings before and after the change.
26
+
27
+ Written with AI assistance.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64fa640520bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6232/tests/oracle.patch ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
2
+ index f1c4fb93..bcefb5a8 100755
3
+ --- a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
4
+ +++ b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun
5
+ @@ -36,8 +36,8 @@ case $lang in
6
+ "it")
7
+ info_text=("Steam è in fase di download. Attendere prego. Il download del client Steam potrebbe richiedere alcuni minuti.")
8
+ ;;
9
+ -#brazilian portuguese
10
+ - "pt_BR")
11
+ +#portuguese (brazilian translation)
12
+ + "pt")
13
+ info_text=("O Steam está sendo executado pela primeira vez. Por favor, aguarde. O download do cliente Steam pode levar alguns minutos.")
14
+ ;;
15
+ #ukrainian
tasks/ublue-os__bazzite-6232/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 64fa640520bcbd038abb2cfdfdf725f87e7a717c > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/ublue-os__bazzite-6232/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/ublue-os__bazzite-6234/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/ublue-os__bazzite-6234/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: check MOKs aren't in use before suggesting deletion
4
+
5
+ ## Description
6
+
7
+ I got a `ujust check-anticheat` log from a user with a Ventoy key enrolled. The hint told them to delete every key that isn't well-known without checking what it signs, which could leave a system unbootable.
8
+
9
+ * Check that MOKs that aren't well-known aren't used by the kernel, the bootloader, another boot entry or a loaded driver before suggesting they be deleted
10
+ * Show why the TPM boot log couldn't be read
11
+ * Fix the IOMMU hint for passthrough on by default in the kernel, and the BPF hint when the active LSMs can't be read, which would have dropped SELinux
12
+ * Tell handheld users to hold off on kernel lockdown for now
13
+
14
+ I've tested this on my machine, and we should have people give it a whirl on unstable/testing.
15
+
16
+ This is reaching the level of complexity I like with bash, so I'm exploring a Python rewrite.
17
+
18
+ ## Task
19
+
20
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1901c6af3ce5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6234/solution/patch.diff ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
2
+ index f0a48eb3..9d460399 100644
3
+ --- a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
4
+ +++ b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
5
+ @@ -53,10 +53,12 @@ check-anticheat:
6
+ SIGNER_CN=$(sed -n 's|^ *- subject: .*/CN=\([^/]*\).*|\1|p' <<<"$SIGNERS" | head -n1)
7
+ if ! grep -q 'subject:' <<<"$SIGNERS"; then
8
+ fail "Signed kernel" "Kernel $(uname -r) is not signed"
9
+ - elif grep -Eq "$WELL_KNOWN_KEYS" <<<"$SIGNERS"; then
10
+ - pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}'"
11
+ + elif WELL_KNOWN_LINE=$(grep -Em1 "$WELL_KNOWN_KEYS" <<<"$SIGNERS"); then
12
+ + # A kernel can have several signatures, so name the well-known one
13
+ + SIGNER_CN=$(sed -n 's|.*/CN=\([^/]*\).*|\1|p' <<<"$WELL_KNOWN_LINE")
14
+ + pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}'"
15
+ else
16
+ - fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}', which is not a well-known key"
17
+ + fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}', which is not a well-known key"
18
+ fi
19
+ fi
20
+
21
+ @@ -101,14 +103,116 @@ check-anticheat:
22
+ for der in "$MOK_DIR"/MOK-*.der; do
23
+ [[ -e $der ]] || continue
24
+ CERT=$(openssl x509 -inform DER -in "$der" -noout -subject -issuer 2>/dev/null)
25
+ - if ! grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT"; then
26
+ - UNKNOWN_MOKS+=("'$(sed -n 's/^subject=.*CN *= *\([^,]*\).*/\1/p' <<<"$CERT")'")
27
+ - fi
28
+ + grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT" || UNKNOWN_MOKS+=("$der")
29
+ done
30
+ if (( MOK_STATUS )); then
31
+ fail "Only well-known Machine Owner Keys" "Couldn't read the enrolled keys (mokutil says: ${MOK_ERR//$'\n'/ })"
32
+ elif (( ${#UNKNOWN_MOKS[@]} )); then
33
+ - fail "Only well-known Machine Owner Keys" "Not well-known: ${UNKNOWN_MOKS[*]}. Export them with 'mokutil --export', then remove each with 'sudo mokutil --delete MOK-000N.der'"
34
+ + # Never suggest deleting a key that the kernel, an EFI binary or a loaded module depends on
35
+ + cert_cn() {
36
+ + openssl x509 -inform DER -in "$1" -noout "$2" -nameopt multiline,utf8,-esc_msb 2>/dev/null | sed -n 's/^ *commonName *= *//p' | head -n1
37
+ + }
38
+ + ESP_DIR=/boot/efi/EFI
39
+ + mapfile -t BOOT_FILES < <(find "$ESP_DIR" -type f -iname '*.efi' 2>/dev/null)
40
+ + BOOT_READABLE=1
41
+ + [[ ${#BOOT_FILES[@]} -gt 0 && -r $KERNEL ]] || BOOT_READABLE=0
42
+ + BOOT_FILES+=("$KERNEL")
43
+ + declare -A SIGNED_MODULES=()
44
+ + while read -r mod _; do
45
+ + SIGNER=$(modinfo -F signer "$mod" 2>/dev/null)
46
+ + [[ -n $SIGNER ]] && SIGNED_MODULES[$SIGNER]+=" $mod"
47
+ + done </proc/modules
48
+ +
49
+ + # BOOT and fedora are this system's ESP folders, plus whichever entry the firmware booted, which may chainload them.
50
+ + # If that's unknown, treat every folder as ours
51
+ + EFI_ENTRIES=$(efibootmgr 2>/dev/null)
52
+ + BOOT_CURRENT=$(sed -n 's/^BootCurrent: //p' <<<"$EFI_ENTRIES")
53
+ + CURRENT_ENTRY=""
54
+ + if [[ -n $BOOT_CURRENT ]]; then
55
+ + CURRENT_ENTRY=$(grep -E "^Boot${BOOT_CURRENT}[* ]" <<<"$EFI_ENTRIES" | grep -oiE '\\EFI\\[^\\]+' | head -n1)
56
+ + CURRENT_ENTRY=${CURRENT_ENTRY##*\\}
57
+ + fi
58
+ +
59
+ + KEY_LINES=()
60
+ + SAFE_KEYS=""
61
+ + SAFE_FILES=()
62
+ + OTHER_FILES=()
63
+ + for der in "${UNKNOWN_MOKS[@]}"; do
64
+ + FILE=${der##*/}
65
+ + NAME=$(cert_cn "$der" -subject)
66
+ + ISSUER=$(cert_cn "$der" -issuer)
67
+ + KEY="'${NAME:-unnamed}' (${FILE})"
68
+ + DN=$(openssl x509 -inform DER -in "$der" -noout -subject -nameopt compat 2>/dev/null)
69
+ + DN=${DN#subject=}
70
+ + if [[ -z $DN ]]; then
71
+ + KEY_LINES+=("${KEY}. It couldn't be read, so this system may need it to boot and it cannot be deleted.")
72
+ + continue
73
+ + fi
74
+ + SIGNS_KERNEL=0
75
+ + SIGNS_BOOTLOADER=0
76
+ + declare -A OTHER_ENTRIES=()
77
+ + for file in "${BOOT_FILES[@]}"; do
78
+ + # Not sbverify --cert, which accepts any key for binaries that embed a certificate chain, like shim
79
+ + sbverify --list "$file" 2>/dev/null | sed -E 's/^ *(- )?((subject|issuer): *)?//' | grep -Fx -- "$DN" >/dev/null || continue
80
+ + ENTRY=${file#"$ESP_DIR"/}
81
+ + ENTRY=${ENTRY%%/*}
82
+ + if [[ $file == "$KERNEL" ]]; then
83
+ + SIGNS_KERNEL=1
84
+ + elif [[ -z $CURRENT_ENTRY || ${ENTRY,,} == "${CURRENT_ENTRY,,}" || ${ENTRY,,} =~ ^(boot|fedora)$ ]]; then
85
+ + SIGNS_BOOTLOADER=1
86
+ + else
87
+ + OTHER_ENTRIES[$ENTRY]=1
88
+ + fi
89
+ + done
90
+ + # modinfo reports a module's signer by the issuer of its certificate, so check both names
91
+ + DRIVERS=""
92
+ + [[ -n $NAME ]] && DRIVERS=${SIGNED_MODULES[$NAME]:-}
93
+ + [[ -n $ISSUER && $ISSUER != "$NAME" ]] && DRIVERS+=${SIGNED_MODULES[$ISSUER]:-}
94
+ +
95
+ + if (( SIGNS_KERNEL || SIGNS_BOOTLOADER )); then
96
+ + USES=()
97
+ + (( SIGNS_KERNEL )) && USES+=("the running kernel")
98
+ + (( SIGNS_BOOTLOADER )) && USES+=("this system's bootloader")
99
+ + [[ -n $DRIVERS ]] && USES+=("these drivers:${DRIVERS}")
100
+ + SIGNS=${USES[0]}
101
+ + (( ${#USES[@]} == 3 )) && SIGNS+=", ${USES[1]}"
102
+ + (( ${#USES[@]} > 1 )) && SIGNS+=" and ${USES[-1]}"
103
+ + KEY_LINES+=("${KEY}. It signs ${SIGNS}. This system may not boot without it, so it cannot be deleted.")
104
+ + elif [[ -n $DRIVERS ]]; then
105
+ + KEY_LINES+=("${KEY}. It signs these drivers, which won't load without it, so it cannot be deleted:${DRIVERS}.")
106
+ + elif (( ! BOOT_READABLE )); then
107
+ + KEY_LINES+=("${KEY}. Couldn't read the kernel and the EFI binaries in /boot/efi, so this system may need it to boot. Check what it signs before deleting it.")
108
+ + elif (( ${#OTHER_ENTRIES[@]} )); then
109
+ + KEY_LINES+=("${KEY}. It signs the bootloader for another boot entry (${!OTHER_ENTRIES[*]}). This system doesn't need it, but only delete it if you no longer use that entry.")
110
+ + OTHER_FILES+=("$FILE")
111
+ + else
112
+ + SAFE_KEYS+="${SAFE_KEYS:+, }${KEY}"
113
+ + SAFE_FILES+=("$FILE")
114
+ + fi
115
+ + done
116
+ +
117
+ + fail "Only well-known Machine Owner Keys"
118
+ + for line in "${KEY_LINES[@]}"; do
119
+ + printf ' %s\n' "Not well-known: ${line}"
120
+ + done
121
+ + EXPORT="run 'mokutil --export' in an empty directory"
122
+ + if (( ${#SAFE_FILES[@]} )); then
123
+ + THESE="These keys are"
124
+ + IT=them
125
+ + if (( ${#SAFE_FILES[@]} == 1 )); then
126
+ + THESE="This key is"
127
+ + IT=it
128
+ + fi
129
+ + printf ' %s\n' "Not well-known: ${SAFE_KEYS}. ${THESE} not used by the running kernel, any boot entry on this drive or any loaded driver, and may be safely deleted."
130
+ + printf ' %s\n' "To delete ${IT}, ${EXPORT}, then 'sudo mokutil --delete ${SAFE_FILES[*]}'.${OTHER_FILES[*]:+ Add ${OTHER_FILES[*]} for any boot entry you no longer use.}"
131
+ + elif (( ${#OTHER_FILES[@]} == 1 )); then
132
+ + printf ' %s\n' "If you no longer use that entry, ${EXPORT}, then 'sudo mokutil --delete ${OTHER_FILES[0]}'."
133
+ + elif (( ${#OTHER_FILES[@]} )); then
134
+ + printf ' %s\n' "For any of those entries you no longer use, ${EXPORT}, then 'sudo mokutil --delete' with its key: ${OTHER_FILES[*]}."
135
+ + fi
136
+ + if (( ${#SAFE_FILES[@]} + ${#OTHER_FILES[@]} )); then
137
+ + printf ' %s\n' "If asked for a password, use 'universalblue'. At next reboot, select 'Delete MOK' in the mokutil UEFI menu and enter 'universalblue' again."
138
+ + fi
139
+ else
140
+ pass "Only well-known Machine Owner Keys"
141
+ fi
142
+ @@ -120,7 +224,8 @@ check-anticheat:
143
+ else
144
+ # GRUB measures into PCRs 8 and 9, systemd-boot and systemd-stub into 11 and 12
145
+ if ! PCRS=$(tpm2_eventlog "$EVENT_LOG" 2>/dev/null); then
146
+ - fail "Measured boot" "Couldn't read the TPM boot log"
147
+ + TPM_ERR=$(tpm2_eventlog "$EVENT_LOG" 2>&1 >/dev/null)
148
+ + fail "Measured boot" "Couldn't read the TPM boot log (tpm2_eventlog says: ${TPM_ERR//$'\n'/ })"
149
+ elif grep -Eq '^\s*PCRIndex: (8|9|11|12)$' <<<"$PCRS"; then
150
+ pass "Measured boot" "The boot manager recorded its measurements"
151
+ else
152
+ @@ -135,12 +240,14 @@ check-anticheat:
153
+ done
154
+ if [[ -z $PASSTHROUGH ]] && ! has_karg iommu.passthrough=0 &&
155
+ grep -q '^CONFIG_IOMMU_DEFAULT_PASSTHROUGH=y' "/usr/lib/modules/$(uname -r)/config" 2>/dev/null; then
156
+ - PASSTHROUGH="the kernel's default"
157
+ + PASSTHROUGH=default
158
+ fi
159
+ if compgen -G '/sys/class/iommu/*' >/dev/null && [[ -z $PASSTHROUGH ]]; then
160
+ pass "IOMMU enabled, passthrough disabled"
161
+ elif (( HANDHELD )); then
162
+ pass "IOMMU enabled, passthrough disabled" "Not required on handheld devices"
163
+ + elif [[ $PASSTHROUGH == default ]]; then
164
+ + fail "IOMMU enabled, passthrough disabled" "Passthrough is on by default in this kernel. Run 'rpm-ostree kargs --append-if-missing=iommu.passthrough=0'"
165
+ elif [[ -n $PASSTHROUGH ]]; then
166
+ fail "IOMMU enabled, passthrough disabled" "Passthrough is on (${PASSTHROUGH}). Remove it with 'rpm-ostree kargs --delete=${PASSTHROUGH}'"
167
+ elif grep -q GenuineIntel /proc/cpuinfo; then
168
+ @@ -153,6 +260,9 @@ check-anticheat:
169
+ LOCKDOWN=$(sed -n 's/.*\[\(.*\)\].*/\1/p' /sys/kernel/security/lockdown 2>/dev/null)
170
+ if [[ $LOCKDOWN == integrity || $LOCKDOWN == confidentiality ]]; then
171
+ pass "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN}'"
172
+ + elif (( HANDHELD )); then
173
+ + fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'."
174
+ + printf ' %s\n' "${bold}Note:${normal} Handheld users should hold off on enabling kernel lockdown for now. We're working on a solution."
175
+ else
176
+ fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'. Run 'rpm-ostree kargs --append-if-missing=lockdown=integrity'"
177
+ fi
178
+ @@ -169,8 +279,10 @@ check-anticheat:
179
+ LSMS=$(cat /sys/kernel/security/lsm 2>/dev/null)
180
+ if [[ ,$LSMS, == *,bpf,* ]]; then
181
+ pass "BPF LSM active"
182
+ + elif [[ -z $LSMS ]]; then
183
+ + fail "BPF LSM active" "Couldn't read the active LSMs from /sys/kernel/security/lsm"
184
+ else
185
+ - fail "BPF LSM active" "Active LSMs: ${LSMS:-unknown}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS:+$LSMS,}bpf'"
186
+ + fail "BPF LSM active" "Active LSMs: ${LSMS}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS},bpf'"
187
+ fi
188
+
189
+ echo
tasks/ublue-os__bazzite-6234/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/ublue-os__bazzite-6234/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/ublue-os__bazzite-6234"
5
+ description = "fix: check MOKs aren't in use before suggesting deletion"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "bazzite",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "ublue-os/bazzite"
19
+ ref = "1901c6af3ce5d755baf00e37bcbf1fd313ca9651"
20
+ reference = "https://github.com/ublue-os/bazzite/pull/6234"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:50.979136+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:259fac6ae377342851e02822fb244ae7b812ecef38e96e550bbaf073b8af4650"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-11-04T16:36:04Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 132
40
+ difficulty = "large"
41
+
42
+ [metadata.repo2env.evaluation]
43
+ schema_version = "1"
44
+ status = "unverified"
45
+ stage = "generation"
46
+ reason_codes = [
47
+ "validation_not_run",
48
+ ]
49
+ detail = "Generated task; validation has not been established."
50
+ provenance = "unknown"
51
+ evidence = []
52
+
53
+ [metadata.repo2env.reproducibility]
54
+ mode = "inline_dockerfile"
55
+ image_ref = "python:3.12-slim"
56
+ image_tag = "python:3.12-slim"
57
+ image_visibility = "public"
58
+ pushed_at = "2026-11-16T16:20:03.588917+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:74d93ef9d8f18d981ab4f7a0ee26af3c07662dbe889f13667c67bef70bd789cf"
61
+ inline_recipe_lines = 37
62
+ inline_recipe_source = "user_dockerfile"
63
+
64
+ [agent]
65
+ timeout_sec = 1800.0
66
+
67
+ [verifier]
68
+ timeout_sec = 300.0
tasks/ublue-os__bazzite-6234/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/ublue-os__bazzite-6234/tests/instruction.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: check MOKs aren't in use before suggesting deletion
4
+
5
+ ## Description
6
+
7
+ I got a `ujust check-anticheat` log from a user with a Ventoy key enrolled. The hint told them to delete every key that isn't well-known without checking what it signs, which could leave a system unbootable.
8
+
9
+ * Check that MOKs that aren't well-known aren't used by the kernel, the bootloader, another boot entry or a loaded driver before suggesting they be deleted
10
+ * Show why the TPM boot log couldn't be read
11
+ * Fix the IOMMU hint for passthrough on by default in the kernel, and the BPF hint when the active LSMs can't be read, which would have dropped SELinux
12
+ * Tell handheld users to hold off on kernel lockdown for now
13
+
14
+ I've tested this on my machine, and we should have people give it a whirl on unstable/testing.
15
+
16
+ This is reaching the level of complexity I like with bash, so I'm exploring a Python rewrite.
17
+
18
+ ## Task
19
+
20
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1901c6af3ce5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6234/tests/oracle.patch ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
2
+ index f0a48eb3..9d460399 100644
3
+ --- a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
4
+ +++ b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just
5
+ @@ -53,10 +53,12 @@ check-anticheat:
6
+ SIGNER_CN=$(sed -n 's|^ *- subject: .*/CN=\([^/]*\).*|\1|p' <<<"$SIGNERS" | head -n1)
7
+ if ! grep -q 'subject:' <<<"$SIGNERS"; then
8
+ fail "Signed kernel" "Kernel $(uname -r) is not signed"
9
+ - elif grep -Eq "$WELL_KNOWN_KEYS" <<<"$SIGNERS"; then
10
+ - pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}'"
11
+ + elif WELL_KNOWN_LINE=$(grep -Em1 "$WELL_KNOWN_KEYS" <<<"$SIGNERS"); then
12
+ + # A kernel can have several signatures, so name the well-known one
13
+ + SIGNER_CN=$(sed -n 's|.*/CN=\([^/]*\).*|\1|p' <<<"$WELL_KNOWN_LINE")
14
+ + pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}'"
15
+ else
16
+ - fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}', which is not a well-known key"
17
+ + fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}', which is not a well-known key"
18
+ fi
19
+ fi
20
+
21
+ @@ -101,14 +103,116 @@ check-anticheat:
22
+ for der in "$MOK_DIR"/MOK-*.der; do
23
+ [[ -e $der ]] || continue
24
+ CERT=$(openssl x509 -inform DER -in "$der" -noout -subject -issuer 2>/dev/null)
25
+ - if ! grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT"; then
26
+ - UNKNOWN_MOKS+=("'$(sed -n 's/^subject=.*CN *= *\([^,]*\).*/\1/p' <<<"$CERT")'")
27
+ - fi
28
+ + grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT" || UNKNOWN_MOKS+=("$der")
29
+ done
30
+ if (( MOK_STATUS )); then
31
+ fail "Only well-known Machine Owner Keys" "Couldn't read the enrolled keys (mokutil says: ${MOK_ERR//$'\n'/ })"
32
+ elif (( ${#UNKNOWN_MOKS[@]} )); then
33
+ - fail "Only well-known Machine Owner Keys" "Not well-known: ${UNKNOWN_MOKS[*]}. Export them with 'mokutil --export', then remove each with 'sudo mokutil --delete MOK-000N.der'"
34
+ + # Never suggest deleting a key that the kernel, an EFI binary or a loaded module depends on
35
+ + cert_cn() {
36
+ + openssl x509 -inform DER -in "$1" -noout "$2" -nameopt multiline,utf8,-esc_msb 2>/dev/null | sed -n 's/^ *commonName *= *//p' | head -n1
37
+ + }
38
+ + ESP_DIR=/boot/efi/EFI
39
+ + mapfile -t BOOT_FILES < <(find "$ESP_DIR" -type f -iname '*.efi' 2>/dev/null)
40
+ + BOOT_READABLE=1
41
+ + [[ ${#BOOT_FILES[@]} -gt 0 && -r $KERNEL ]] || BOOT_READABLE=0
42
+ + BOOT_FILES+=("$KERNEL")
43
+ + declare -A SIGNED_MODULES=()
44
+ + while read -r mod _; do
45
+ + SIGNER=$(modinfo -F signer "$mod" 2>/dev/null)
46
+ + [[ -n $SIGNER ]] && SIGNED_MODULES[$SIGNER]+=" $mod"
47
+ + done </proc/modules
48
+ +
49
+ + # BOOT and fedora are this system's ESP folders, plus whichever entry the firmware booted, which may chainload them.
50
+ + # If that's unknown, treat every folder as ours
51
+ + EFI_ENTRIES=$(efibootmgr 2>/dev/null)
52
+ + BOOT_CURRENT=$(sed -n 's/^BootCurrent: //p' <<<"$EFI_ENTRIES")
53
+ + CURRENT_ENTRY=""
54
+ + if [[ -n $BOOT_CURRENT ]]; then
55
+ + CURRENT_ENTRY=$(grep -E "^Boot${BOOT_CURRENT}[* ]" <<<"$EFI_ENTRIES" | grep -oiE '\\EFI\\[^\\]+' | head -n1)
56
+ + CURRENT_ENTRY=${CURRENT_ENTRY##*\\}
57
+ + fi
58
+ +
59
+ + KEY_LINES=()
60
+ + SAFE_KEYS=""
61
+ + SAFE_FILES=()
62
+ + OTHER_FILES=()
63
+ + for der in "${UNKNOWN_MOKS[@]}"; do
64
+ + FILE=${der##*/}
65
+ + NAME=$(cert_cn "$der" -subject)
66
+ + ISSUER=$(cert_cn "$der" -issuer)
67
+ + KEY="'${NAME:-unnamed}' (${FILE})"
68
+ + DN=$(openssl x509 -inform DER -in "$der" -noout -subject -nameopt compat 2>/dev/null)
69
+ + DN=${DN#subject=}
70
+ + if [[ -z $DN ]]; then
71
+ + KEY_LINES+=("${KEY}. It couldn't be read, so this system may need it to boot and it cannot be deleted.")
72
+ + continue
73
+ + fi
74
+ + SIGNS_KERNEL=0
75
+ + SIGNS_BOOTLOADER=0
76
+ + declare -A OTHER_ENTRIES=()
77
+ + for file in "${BOOT_FILES[@]}"; do
78
+ + # Not sbverify --cert, which accepts any key for binaries that embed a certificate chain, like shim
79
+ + sbverify --list "$file" 2>/dev/null | sed -E 's/^ *(- )?((subject|issuer): *)?//' | grep -Fx -- "$DN" >/dev/null || continue
80
+ + ENTRY=${file#"$ESP_DIR"/}
81
+ + ENTRY=${ENTRY%%/*}
82
+ + if [[ $file == "$KERNEL" ]]; then
83
+ + SIGNS_KERNEL=1
84
+ + elif [[ -z $CURRENT_ENTRY || ${ENTRY,,} == "${CURRENT_ENTRY,,}" || ${ENTRY,,} =~ ^(boot|fedora)$ ]]; then
85
+ + SIGNS_BOOTLOADER=1
86
+ + else
87
+ + OTHER_ENTRIES[$ENTRY]=1
88
+ + fi
89
+ + done
90
+ + # modinfo reports a module's signer by the issuer of its certificate, so check both names
91
+ + DRIVERS=""
92
+ + [[ -n $NAME ]] && DRIVERS=${SIGNED_MODULES[$NAME]:-}
93
+ + [[ -n $ISSUER && $ISSUER != "$NAME" ]] && DRIVERS+=${SIGNED_MODULES[$ISSUER]:-}
94
+ +
95
+ + if (( SIGNS_KERNEL || SIGNS_BOOTLOADER )); then
96
+ + USES=()
97
+ + (( SIGNS_KERNEL )) && USES+=("the running kernel")
98
+ + (( SIGNS_BOOTLOADER )) && USES+=("this system's bootloader")
99
+ + [[ -n $DRIVERS ]] && USES+=("these drivers:${DRIVERS}")
100
+ + SIGNS=${USES[0]}
101
+ + (( ${#USES[@]} == 3 )) && SIGNS+=", ${USES[1]}"
102
+ + (( ${#USES[@]} > 1 )) && SIGNS+=" and ${USES[-1]}"
103
+ + KEY_LINES+=("${KEY}. It signs ${SIGNS}. This system may not boot without it, so it cannot be deleted.")
104
+ + elif [[ -n $DRIVERS ]]; then
105
+ + KEY_LINES+=("${KEY}. It signs these drivers, which won't load without it, so it cannot be deleted:${DRIVERS}.")
106
+ + elif (( ! BOOT_READABLE )); then
107
+ + KEY_LINES+=("${KEY}. Couldn't read the kernel and the EFI binaries in /boot/efi, so this system may need it to boot. Check what it signs before deleting it.")
108
+ + elif (( ${#OTHER_ENTRIES[@]} )); then
109
+ + KEY_LINES+=("${KEY}. It signs the bootloader for another boot entry (${!OTHER_ENTRIES[*]}). This system doesn't need it, but only delete it if you no longer use that entry.")
110
+ + OTHER_FILES+=("$FILE")
111
+ + else
112
+ + SAFE_KEYS+="${SAFE_KEYS:+, }${KEY}"
113
+ + SAFE_FILES+=("$FILE")
114
+ + fi
115
+ + done
116
+ +
117
+ + fail "Only well-known Machine Owner Keys"
118
+ + for line in "${KEY_LINES[@]}"; do
119
+ + printf ' %s\n' "Not well-known: ${line}"
120
+ + done
121
+ + EXPORT="run 'mokutil --export' in an empty directory"
122
+ + if (( ${#SAFE_FILES[@]} )); then
123
+ + THESE="These keys are"
124
+ + IT=them
125
+ + if (( ${#SAFE_FILES[@]} == 1 )); then
126
+ + THESE="This key is"
127
+ + IT=it
128
+ + fi
129
+ + printf ' %s\n' "Not well-known: ${SAFE_KEYS}. ${THESE} not used by the running kernel, any boot entry on this drive or any loaded driver, and may be safely deleted."
130
+ + printf ' %s\n' "To delete ${IT}, ${EXPORT}, then 'sudo mokutil --delete ${SAFE_FILES[*]}'.${OTHER_FILES[*]:+ Add ${OTHER_FILES[*]} for any boot entry you no longer use.}"
131
+ + elif (( ${#OTHER_FILES[@]} == 1 )); then
132
+ + printf ' %s\n' "If you no longer use that entry, ${EXPORT}, then 'sudo mokutil --delete ${OTHER_FILES[0]}'."
133
+ + elif (( ${#OTHER_FILES[@]} )); then
134
+ + printf ' %s\n' "For any of those entries you no longer use, ${EXPORT}, then 'sudo mokutil --delete' with its key: ${OTHER_FILES[*]}."
135
+ + fi
136
+ + if (( ${#SAFE_FILES[@]} + ${#OTHER_FILES[@]} )); then
137
+ + printf ' %s\n' "If asked for a password, use 'universalblue'. At next reboot, select 'Delete MOK' in the mokutil UEFI menu and enter 'universalblue' again."
138
+ + fi
139
+ else
140
+ pass "Only well-known Machine Owner Keys"
141
+ fi
142
+ @@ -120,7 +224,8 @@ check-anticheat:
143
+ else
144
+ # GRUB measures into PCRs 8 and 9, systemd-boot and systemd-stub into 11 and 12
145
+ if ! PCRS=$(tpm2_eventlog "$EVENT_LOG" 2>/dev/null); then
146
+ - fail "Measured boot" "Couldn't read the TPM boot log"
147
+ + TPM_ERR=$(tpm2_eventlog "$EVENT_LOG" 2>&1 >/dev/null)
148
+ + fail "Measured boot" "Couldn't read the TPM boot log (tpm2_eventlog says: ${TPM_ERR//$'\n'/ })"
149
+ elif grep -Eq '^\s*PCRIndex: (8|9|11|12)$' <<<"$PCRS"; then
150
+ pass "Measured boot" "The boot manager recorded its measurements"
151
+ else
152
+ @@ -135,12 +240,14 @@ check-anticheat:
153
+ done
154
+ if [[ -z $PASSTHROUGH ]] && ! has_karg iommu.passthrough=0 &&
155
+ grep -q '^CONFIG_IOMMU_DEFAULT_PASSTHROUGH=y' "/usr/lib/modules/$(uname -r)/config" 2>/dev/null; then
156
+ - PASSTHROUGH="the kernel's default"
157
+ + PASSTHROUGH=default
158
+ fi
159
+ if compgen -G '/sys/class/iommu/*' >/dev/null && [[ -z $PASSTHROUGH ]]; then
160
+ pass "IOMMU enabled, passthrough disabled"
161
+ elif (( HANDHELD )); then
162
+ pass "IOMMU enabled, passthrough disabled" "Not required on handheld devices"
163
+ + elif [[ $PASSTHROUGH == default ]]; then
164
+ + fail "IOMMU enabled, passthrough disabled" "Passthrough is on by default in this kernel. Run 'rpm-ostree kargs --append-if-missing=iommu.passthrough=0'"
165
+ elif [[ -n $PASSTHROUGH ]]; then
166
+ fail "IOMMU enabled, passthrough disabled" "Passthrough is on (${PASSTHROUGH}). Remove it with 'rpm-ostree kargs --delete=${PASSTHROUGH}'"
167
+ elif grep -q GenuineIntel /proc/cpuinfo; then
168
+ @@ -153,6 +260,9 @@ check-anticheat:
169
+ LOCKDOWN=$(sed -n 's/.*\[\(.*\)\].*/\1/p' /sys/kernel/security/lockdown 2>/dev/null)
170
+ if [[ $LOCKDOWN == integrity || $LOCKDOWN == confidentiality ]]; then
171
+ pass "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN}'"
172
+ + elif (( HANDHELD )); then
173
+ + fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'."
174
+ + printf ' %s\n' "${bold}Note:${normal} Handheld users should hold off on enabling kernel lockdown for now. We're working on a solution."
175
+ else
176
+ fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'. Run 'rpm-ostree kargs --append-if-missing=lockdown=integrity'"
177
+ fi
178
+ @@ -169,8 +279,10 @@ check-anticheat:
179
+ LSMS=$(cat /sys/kernel/security/lsm 2>/dev/null)
180
+ if [[ ,$LSMS, == *,bpf,* ]]; then
181
+ pass "BPF LSM active"
182
+ + elif [[ -z $LSMS ]]; then
183
+ + fail "BPF LSM active" "Couldn't read the active LSMs from /sys/kernel/security/lsm"
184
+ else
185
+ - fail "BPF LSM active" "Active LSMs: ${LSMS:-unknown}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS:+$LSMS,}bpf'"
186
+ + fail "BPF LSM active" "Active LSMs: ${LSMS}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS},bpf'"
187
+ fi
188
+
189
+ echo
tasks/ublue-os__bazzite-6234/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/ublue-os__bazzite-6234/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/ublue-os__bazzite-6243/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 6ef839120b2a224f8aa718cc1c855be96cea50aa 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 6ef839120b2a224f8aa718cc1c855be96cea50aa \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 6ef839120b2a224f8aa718cc1c855be96cea50aa \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/ublue-os__bazzite-6243/instruction.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices.
4
+
5
+ ## Description
6
+
7
+ After the TSC patch got merged in the OGC kernel (), devices with flawed TSC will not have this clocksource enabled by default. Ideally, Bazzite shouldn't enable ```tsc=directsync``` by default for devices that already support this clocksouce and have 0 issues (And I doubt it would affect those devices too, but I can't test this theory)
8
+
9
+ So I came up with a script that checks if the CPU has support for TSC but it defaults to HPET/ACPI_PM. If the statement is true, it will run the kargs command to add ```tsc=directsync```. The reasons why this script must exist is to:
10
+ 1. Ease the debugging process for devices with buggy TSC that cause system instabilities (either because they default to HPET or they force TSC one way or another)
11
+ 2. Gives a seamless experience and less friction for affected devices. Basically an out-of-the-box experience (as it should be).
12
+
13
+ I have tested this script beforehand and it works the way I thought it should. In theory, this can be improved by checking journalctl for tsc errors (or dmesg), but I wanted to keep it simple.
14
+
15
+ Another idea I had was to have this as an ujust command, but it goes against the philosophy of OOTB experience I was aiming for.
16
+
17
+ Please let me know if there is room for improvement or if I have to fix anything.
18
+
19
+ ## Task
20
+
21
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6ef839120b2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6243/solution/patch.diff ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
2
+ index a55f4635..ac844d24 100755
3
+ --- a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
4
+ +++ b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
5
+ @@ -255,6 +255,33 @@ if [[ -f "/var/lib/waydroid/lxc/waydroid/config" ]]; then
6
+ sed -i '/lxc\.apparmor\.profile\s*=\s*unconfined/d' "/var/lib/waydroid/lxc/waydroid/config"
7
+ fi
8
+
9
+ +#Enable TSC directsync after patch
10
+ +set -eu
11
+ +if [ ! -r /proc/cpuinfo ]; then
12
+ + echo "Cannot read /proc/cpuinfo; unable to check TSC support." >&2
13
+ + exit 1
14
+ +fi
15
+ +clocksource_file=/sys/devices/system/clocksource/clocksource0/current_clocksource
16
+ +if [ -r "$clocksource_file" ]; then
17
+ + current_clocksource=$(cat "$clocksource_file")
18
+ +else
19
+ + current_clocksource=unknown
20
+ +fi
21
+ +if awk '
22
+ + /^flags[[:space:]]*:/ {
23
+ + for (i = 2; i <= NF; i++) {
24
+ + if ($i == "tsc") found = 1
25
+ + }
26
+ + }
27
+ + END { exit !found }
28
+ +' /proc/cpuinfo &&
29
+ + ! { [ "$current_clocksource" = hpet ] ||
30
+ + [ "$current_clocksource" = acpi_pm ]; }; then
31
+ + echo "CPU reports TSC support."
32
+ +else
33
+ + sudo rpm-ostree kargs --append-if-missing=tsc=directsync
34
+ +fi
35
+ +
36
+ # HIBERNATION
37
+ if /usr/libexec/hwsupport/needs-hibernation; then
38
+ if [[ ! -f /etc/bazzite/hibernation_enabled ]]; then
tasks/ublue-os__bazzite-6243/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/ublue-os__bazzite-6243/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/ublue-os__bazzite-6243"
5
+ description = "[FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices."
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "bazzite",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "ublue-os/bazzite"
19
+ ref = "6ef839120b2a224f8aa718cc1c855be96cea50aa"
20
+ reference = "https://github.com/ublue-os/bazzite/pull/6243"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:50.973122+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:a8e6adc9c3eb9c47790594eff92c0a54d264138155c4457e5217ff78507d1d60"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-11-05T17:11:52Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "system_files/desktop/shared/usr/libexec/bazzite-hardware-setup",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 27
40
+ difficulty = "medium"
41
+
42
+ [metadata.repo2env.evaluation]
43
+ schema_version = "1"
44
+ status = "unverified"
45
+ stage = "generation"
46
+ reason_codes = [
47
+ "validation_not_run",
48
+ ]
49
+ detail = "Generated task; validation has not been established."
50
+ provenance = "unknown"
51
+ evidence = []
52
+
53
+ [metadata.repo2env.reproducibility]
54
+ mode = "inline_dockerfile"
55
+ image_ref = "python:3.12-slim"
56
+ image_tag = "python:3.12-slim"
57
+ image_visibility = "public"
58
+ pushed_at = "2026-11-16T16:20:03.589542+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:eb02bdf5b9afc8d6ff630ee92be3b4e118a7d702fdb5ee49b13e7c84d4692ad3"
61
+ inline_recipe_lines = 37
62
+ inline_recipe_source = "user_dockerfile"
63
+
64
+ [agent]
65
+ timeout_sec = 1800.0
66
+
67
+ [verifier]
68
+ timeout_sec = 300.0
tasks/ublue-os__bazzite-6243/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/ublue-os__bazzite-6243/tests/instruction.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices.
4
+
5
+ ## Description
6
+
7
+ After the TSC patch got merged in the OGC kernel (), devices with flawed TSC will not have this clocksource enabled by default. Ideally, Bazzite shouldn't enable ```tsc=directsync``` by default for devices that already support this clocksouce and have 0 issues (And I doubt it would affect those devices too, but I can't test this theory)
8
+
9
+ So I came up with a script that checks if the CPU has support for TSC but it defaults to HPET/ACPI_PM. If the statement is true, it will run the kargs command to add ```tsc=directsync```. The reasons why this script must exist is to:
10
+ 1. Ease the debugging process for devices with buggy TSC that cause system instabilities (either because they default to HPET or they force TSC one way or another)
11
+ 2. Gives a seamless experience and less friction for affected devices. Basically an out-of-the-box experience (as it should be).
12
+
13
+ I have tested this script beforehand and it works the way I thought it should. In theory, this can be improved by checking journalctl for tsc errors (or dmesg), but I wanted to keep it simple.
14
+
15
+ Another idea I had was to have this as an ujust command, but it goes against the philosophy of OOTB experience I was aiming for.
16
+
17
+ Please let me know if there is room for improvement or if I have to fix anything.
18
+
19
+ ## Task
20
+
21
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6ef839120b2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/ublue-os__bazzite-6243/tests/oracle.patch ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
2
+ index a55f4635..ac844d24 100755
3
+ --- a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
4
+ +++ b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup
5
+ @@ -255,6 +255,33 @@ if [[ -f "/var/lib/waydroid/lxc/waydroid/config" ]]; then
6
+ sed -i '/lxc\.apparmor\.profile\s*=\s*unconfined/d' "/var/lib/waydroid/lxc/waydroid/config"
7
+ fi
8
+
9
+ +#Enable TSC directsync after patch
10
+ +set -eu
11
+ +if [ ! -r /proc/cpuinfo ]; then
12
+ + echo "Cannot read /proc/cpuinfo; unable to check TSC support." >&2
13
+ + exit 1
14
+ +fi
15
+ +clocksource_file=/sys/devices/system/clocksource/clocksource0/current_clocksource
16
+ +if [ -r "$clocksource_file" ]; then
17
+ + current_clocksource=$(cat "$clocksource_file")
18
+ +else
19
+ + current_clocksource=unknown
20
+ +fi
21
+ +if awk '
22
+ + /^flags[[:space:]]*:/ {
23
+ + for (i = 2; i <= NF; i++) {
24
+ + if ($i == "tsc") found = 1
25
+ + }
26
+ + }
27
+ + END { exit !found }
28
+ +' /proc/cpuinfo &&
29
+ + ! { [ "$current_clocksource" = hpet ] ||
30
+ + [ "$current_clocksource" = acpi_pm ]; }; then
31
+ + echo "CPU reports TSC support."
32
+ +else
33
+ + sudo rpm-ostree kargs --append-if-missing=tsc=directsync
34
+ +fi
35
+ +
36
+ # HIBERNATION
37
+ if /usr/libexec/hwsupport/needs-hibernation; then
38
+ if [[ ! -f /etc/bazzite/hibernation_enabled ]]; then