scalingX commited on
Commit
df62646
·
verified ·
1 Parent(s): fe61879

Add 10000 GitHub Trending pr_diff environments (part 77)

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/netdisco__netdisco-1681/tests/test.sh +25 -0
  2. tasks/netdisco__netdisco-1681/tests/verifier.py +737 -0
  3. tasks/netdisco__netdisco-1682/environment/Dockerfile +37 -0
  4. tasks/netdisco__netdisco-1682/instruction.md +31 -0
  5. tasks/netdisco__netdisco-1682/solution/patch.diff +102 -0
  6. tasks/netdisco__netdisco-1682/solution/solve.sh +6 -0
  7. tasks/netdisco__netdisco-1682/task.toml +68 -0
  8. tasks/netdisco__netdisco-1682/tests/capture.py +96 -0
  9. tasks/netdisco__netdisco-1682/tests/instruction.md +31 -0
  10. tasks/netdisco__netdisco-1682/tests/oracle.patch +102 -0
  11. tasks/netdisco__netdisco-1682/tests/test.sh +25 -0
  12. tasks/netdisco__netdisco-1682/tests/verifier.py +737 -0
  13. tasks/netdisco__netdisco-1683/environment/Dockerfile +37 -0
  14. tasks/netdisco__netdisco-1683/instruction.md +31 -0
  15. tasks/netdisco__netdisco-1683/solution/patch.diff +66 -0
  16. tasks/netdisco__netdisco-1683/solution/solve.sh +6 -0
  17. tasks/netdisco__netdisco-1683/task.toml +69 -0
  18. tasks/netdisco__netdisco-1683/tests/capture.py +96 -0
  19. tasks/netdisco__netdisco-1683/tests/instruction.md +31 -0
  20. tasks/netdisco__netdisco-1683/tests/oracle.patch +66 -0
  21. tasks/netdisco__netdisco-1683/tests/test.sh +25 -0
  22. tasks/netdisco__netdisco-1683/tests/verifier.py +737 -0
  23. tasks/netdisco__netdisco-1684/environment/Dockerfile +37 -0
  24. tasks/netdisco__netdisco-1684/instruction.md +176 -0
  25. tasks/netdisco__netdisco-1684/solution/patch.diff +24 -0
  26. tasks/netdisco__netdisco-1684/solution/solve.sh +6 -0
  27. tasks/netdisco__netdisco-1684/task.toml +68 -0
  28. tasks/netdisco__netdisco-1684/tests/capture.py +96 -0
  29. tasks/netdisco__netdisco-1684/tests/instruction.md +176 -0
  30. tasks/netdisco__netdisco-1684/tests/oracle.patch +24 -0
  31. tasks/netdisco__netdisco-1684/tests/test.sh +25 -0
  32. tasks/netdisco__netdisco-1684/tests/verifier.py +737 -0
  33. tasks/netdisco__netdisco-1685/environment/Dockerfile +37 -0
  34. tasks/netdisco__netdisco-1685/instruction.md +111 -0
  35. tasks/netdisco__netdisco-1685/solution/patch.diff +22 -0
  36. tasks/netdisco__netdisco-1685/solution/solve.sh +6 -0
  37. tasks/netdisco__netdisco-1685/task.toml +68 -0
  38. tasks/netdisco__netdisco-1685/tests/capture.py +96 -0
  39. tasks/netdisco__netdisco-1685/tests/instruction.md +111 -0
  40. tasks/netdisco__netdisco-1685/tests/oracle.patch +22 -0
  41. tasks/netdisco__netdisco-1685/tests/test.sh +25 -0
  42. tasks/netdisco__netdisco-1685/tests/verifier.py +737 -0
  43. tasks/netdisco__netdisco-1686/environment/Dockerfile +37 -0
  44. tasks/netdisco__netdisco-1686/instruction.md +196 -0
  45. tasks/netdisco__netdisco-1686/solution/patch.diff +32 -0
  46. tasks/netdisco__netdisco-1686/solution/solve.sh +6 -0
  47. tasks/netdisco__netdisco-1686/task.toml +68 -0
  48. tasks/netdisco__netdisco-1686/tests/capture.py +96 -0
  49. tasks/netdisco__netdisco-1686/tests/instruction.md +196 -0
  50. tasks/netdisco__netdisco-1686/tests/oracle.patch +32 -0
tasks/netdisco__netdisco-1681/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 3f24ac636c0dcc0599c6a4d18b300bc783db7c39 > "$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/netdisco__netdisco-1681/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/netdisco__netdisco-1682/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/netdisco/netdisco.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/netdisco/netdisco.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/netdisco/netdisco.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin e7324236c7256e8618679d3a4b83349983dae8e7 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard e7324236c7256e8618679d3a4b83349983dae8e7 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base e7324236c7256e8618679d3a4b83349983dae8e7 \
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/netdisco__netdisco-1682/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** embed related rows in the nodes API with an include parameter
4
+
5
+ ## Description
6
+
7
+ `/object/device/{ip}/nodes` and `/object/vlan/{vlan}/nodes` return node columns only, so there is no way to reach a node's related rows through the Objects API — not a slow way, none. `/search/node` does return them, so which half of the API you start from decides whether that data is reachable at all.
8
+
9
+ On a switch with ~150 nodes, showing the SSID or the IPs alongside them means the bulk call plus ~150 individual `/search/node` lookups, because the relation is only available one MAC at a time. At ~0.6s per lookup that is about 90 seconds of round trips for data the first query already had in reach.
10
+
11
+ This adds an opt-in `include` parameter naming relations to embed:
12
+
13
+ ```
14
+ GET /api/v1/object/device/10.0.0.1/nodes?include=wireless,ips
15
+ ```
16
+
17
+ Valid names are `wireless` (node_wireless — SSID, signal, rates), `ips` (node_ip), `netbios` (node_nbt) and `manufacturer`. Omitting it changes nothing for existing callers. An unknown name returns 400 with the valid list rather than being silently dropped.
18
+
19
+ Two implementation notes:
20
+
21
+ `TO_JSON` returns own columns only, so `prefetch` alone would not surface anything and the relations are folded into the payload explicitly. I assume that override in `App::Netdisco::DB::Result` exists precisely because relation names shadowing column names made it hand back objects and break `to_json`. For the same reason `oui` is not offered — `Node` has both a column and a relation with that name, which is exactly that collision. `manufacturer` gives the same vendor lookup without it.
22
+
23
+ Asking for two `has_many` relations at once (`wireless,ips`) makes DBIC collapse a product of the two. Correct, but not free. The caller opts into that, which seemed better than refusing the combination.
24
+
25
+ For context on how much weight this deserves: we went looking for wireless client data and then found the pattern we actually have is MAC search, which `/search/node` already serves well. So this is offered as an API gap rather than something we are waiting on — no urgency from our side.
26
+
27
+ Happy to rename the parameter if `include` does not fit the house style; `/search/device` uses `fields` for columns, so this could be `with` or folded into `fields` instead.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e7324236c725`. 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/netdisco__netdisco-1682/solution/patch.diff ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/lib/App/Netdisco/Web/API/Objects.pm b/lib/App/Netdisco/Web/API/Objects.pm
2
+ index b61a8223..f879b7d9 100644
3
+ --- a/lib/App/Netdisco/Web/API/Objects.pm
4
+ +++ b/lib/App/Netdisco/Web/API/Objects.pm
5
+ @@ -11,6 +11,45 @@ use URI::Escape 'uri_unescape';
6
+
7
+ sub _port_param { my $s = uri_unescape(shift // ''); $s =~ s/^\s+|\s+$//g; $s }
8
+
9
+ +# Node relations a caller may pull in alongside the node rows themselves.
10
+ +# The value says whether the relation yields a list. "oui" is deliberately
11
+ +# absent: Node has both a column and a relation of that name, and the
12
+ +# accessor collision is exactly what the TO_JSON override in
13
+ +# App::Netdisco::DB::Result guards against.
14
+ +my %NODE_INCLUDES = (
15
+ + wireless => 1, # node_wireless - SSID, signal, rates
16
+ + ips => 1, # node_ip
17
+ + netbios => 0, # node_nbt
18
+ + manufacturer => 0, # vendor looked up from the OUI
19
+ +);
20
+ +
21
+ +sub _node_includes {
22
+ + my $val = shift;
23
+ + return () unless defined $val and length $val;
24
+ + my @asked = grep { length } map { s/^\s+|\s+$//gr } split /,/, $val;
25
+ + if (my @bad = grep { ! exists $NODE_INCLUDES{$_} } @asked) {
26
+ + send_error((sprintf 'Bad include "%s". Valid: %s',
27
+ + (join ',', @bad), (join ',', sort keys %NODE_INCLUDES)), 400);
28
+ + }
29
+ + return @asked;
30
+ +}
31
+ +
32
+ +# TO_JSON returns own columns only, so fold in the requested relations here
33
+ +sub _node_to_json {
34
+ + my ($row, @includes) = @_;
35
+ + my $data = $row->TO_JSON;
36
+ + foreach my $rel (@includes) {
37
+ + if ($NODE_INCLUDES{$rel}) {
38
+ + $data->{$rel} = [ map { $_->TO_JSON } $row->$rel->all ];
39
+ + }
40
+ + else {
41
+ + my $one = $row->$rel;
42
+ + $data->{$rel} = $one ? $one->TO_JSON : undef;
43
+ + }
44
+ + }
45
+ + return $data;
46
+ +}
47
+ +
48
+ # query params always arrive as strings, so accept the usual spellings of a
49
+ # boolean and fall back to the default documented in the swagger_path
50
+ sub _bool_param {
51
+ @@ -296,14 +335,23 @@ swagger_path {
52
+ default => 'true',
53
+ in => 'query',
54
+ },
55
+ + include => {
56
+ + description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
57
+ + type => 'string',
58
+ + in => 'query',
59
+ + },
60
+ ],
61
+ responses => { default => {} },
62
+ }, get '/api/v1/object/device/:ip/nodes' => require_role api => sub {
63
+ my $active = _bool_param(params->{active_only}, 1);
64
+ + my @includes = _node_includes(params->{include});
65
+ + # qualified, because prefetching ips or netbios joins tables that have
66
+ + # an active column of their own
67
+ my $rows = try { schema(vars->{'tenant'})->resultset('Node')
68
+ - ->search({ switch => params->{ip}, ($active ? (-bool => 'active') : ()) }) }
69
+ + ->search({ 'me.switch' => params->{ip}, ($active ? (-bool => 'me.active') : ()) },
70
+ + (@includes ? { prefetch => [@includes] } : ())) }
71
+ or send_error('Bad Device', 404);
72
+ - return to_json [ map {$_->TO_JSON} $rows->all ];
73
+ + return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
74
+ };
75
+
76
+ swagger_path {
77
+ @@ -371,14 +419,23 @@ swagger_path {
78
+ default => 'true',
79
+ in => 'query',
80
+ },
81
+ + include => {
82
+ + description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
83
+ + type => 'string',
84
+ + in => 'query',
85
+ + },
86
+ ],
87
+ responses => { default => {} },
88
+ }, get '/api/v1/object/vlan/:vlan/nodes' => require_role api => sub {
89
+ my $active = _bool_param(params->{active_only}, 1);
90
+ + my @includes = _node_includes(params->{include});
91
+ + # qualified, because prefetching ips or netbios joins tables that have
92
+ + # an active column of their own
93
+ my $rows = try { schema(vars->{'tenant'})->resultset('Node')
94
+ - ->search({ vlan => params->{vlan}, ($active ? (-bool => 'active') : ()) }) }
95
+ + ->search({ 'me.vlan' => params->{vlan}, ($active ? (-bool => 'me.active') : ()) },
96
+ + (@includes ? { prefetch => [@includes] } : ())) }
97
+ or send_error('Bad VLAN', 404);
98
+ - return to_json [ map {$_->TO_JSON} $rows->all ];
99
+ + return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
100
+ };
101
+
102
+ swagger_path {
tasks/netdisco__netdisco-1682/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/netdisco__netdisco-1682/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/netdisco__netdisco-1682"
5
+ description = "embed related rows in the nodes API with an include parameter"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "netdisco",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "netdisco/netdisco"
19
+ ref = "e7324236c7256e8618679d3a4b83349983dae8e7"
20
+ reference = "https://github.com/netdisco/netdisco/pull/1682"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:58.478670+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:f094e95944d282624863428fd5435a1ec318a7e52ca3de408e22ef8b5a59367a"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-02T01:58:47Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "lib/App/Netdisco/Web/API/Objects.pm",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 65
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:01.772505+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:b8168e1ea8e7cbe5fa20cb5639fe954ebb8e5b786708489d9fd56888dbb5607a"
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/netdisco__netdisco-1682/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/netdisco__netdisco-1682/tests/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** embed related rows in the nodes API with an include parameter
4
+
5
+ ## Description
6
+
7
+ `/object/device/{ip}/nodes` and `/object/vlan/{vlan}/nodes` return node columns only, so there is no way to reach a node's related rows through the Objects API — not a slow way, none. `/search/node` does return them, so which half of the API you start from decides whether that data is reachable at all.
8
+
9
+ On a switch with ~150 nodes, showing the SSID or the IPs alongside them means the bulk call plus ~150 individual `/search/node` lookups, because the relation is only available one MAC at a time. At ~0.6s per lookup that is about 90 seconds of round trips for data the first query already had in reach.
10
+
11
+ This adds an opt-in `include` parameter naming relations to embed:
12
+
13
+ ```
14
+ GET /api/v1/object/device/10.0.0.1/nodes?include=wireless,ips
15
+ ```
16
+
17
+ Valid names are `wireless` (node_wireless — SSID, signal, rates), `ips` (node_ip), `netbios` (node_nbt) and `manufacturer`. Omitting it changes nothing for existing callers. An unknown name returns 400 with the valid list rather than being silently dropped.
18
+
19
+ Two implementation notes:
20
+
21
+ `TO_JSON` returns own columns only, so `prefetch` alone would not surface anything and the relations are folded into the payload explicitly. I assume that override in `App::Netdisco::DB::Result` exists precisely because relation names shadowing column names made it hand back objects and break `to_json`. For the same reason `oui` is not offered — `Node` has both a column and a relation with that name, which is exactly that collision. `manufacturer` gives the same vendor lookup without it.
22
+
23
+ Asking for two `has_many` relations at once (`wireless,ips`) makes DBIC collapse a product of the two. Correct, but not free. The caller opts into that, which seemed better than refusing the combination.
24
+
25
+ For context on how much weight this deserves: we went looking for wireless client data and then found the pattern we actually have is MAC search, which `/search/node` already serves well. So this is offered as an API gap rather than something we are waiting on — no urgency from our side.
26
+
27
+ Happy to rename the parameter if `include` does not fit the house style; `/search/device` uses `fields` for columns, so this could be `with` or folded into `fields` instead.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e7324236c725`. 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/netdisco__netdisco-1682/tests/oracle.patch ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/lib/App/Netdisco/Web/API/Objects.pm b/lib/App/Netdisco/Web/API/Objects.pm
2
+ index b61a8223..f879b7d9 100644
3
+ --- a/lib/App/Netdisco/Web/API/Objects.pm
4
+ +++ b/lib/App/Netdisco/Web/API/Objects.pm
5
+ @@ -11,6 +11,45 @@ use URI::Escape 'uri_unescape';
6
+
7
+ sub _port_param { my $s = uri_unescape(shift // ''); $s =~ s/^\s+|\s+$//g; $s }
8
+
9
+ +# Node relations a caller may pull in alongside the node rows themselves.
10
+ +# The value says whether the relation yields a list. "oui" is deliberately
11
+ +# absent: Node has both a column and a relation of that name, and the
12
+ +# accessor collision is exactly what the TO_JSON override in
13
+ +# App::Netdisco::DB::Result guards against.
14
+ +my %NODE_INCLUDES = (
15
+ + wireless => 1, # node_wireless - SSID, signal, rates
16
+ + ips => 1, # node_ip
17
+ + netbios => 0, # node_nbt
18
+ + manufacturer => 0, # vendor looked up from the OUI
19
+ +);
20
+ +
21
+ +sub _node_includes {
22
+ + my $val = shift;
23
+ + return () unless defined $val and length $val;
24
+ + my @asked = grep { length } map { s/^\s+|\s+$//gr } split /,/, $val;
25
+ + if (my @bad = grep { ! exists $NODE_INCLUDES{$_} } @asked) {
26
+ + send_error((sprintf 'Bad include "%s". Valid: %s',
27
+ + (join ',', @bad), (join ',', sort keys %NODE_INCLUDES)), 400);
28
+ + }
29
+ + return @asked;
30
+ +}
31
+ +
32
+ +# TO_JSON returns own columns only, so fold in the requested relations here
33
+ +sub _node_to_json {
34
+ + my ($row, @includes) = @_;
35
+ + my $data = $row->TO_JSON;
36
+ + foreach my $rel (@includes) {
37
+ + if ($NODE_INCLUDES{$rel}) {
38
+ + $data->{$rel} = [ map { $_->TO_JSON } $row->$rel->all ];
39
+ + }
40
+ + else {
41
+ + my $one = $row->$rel;
42
+ + $data->{$rel} = $one ? $one->TO_JSON : undef;
43
+ + }
44
+ + }
45
+ + return $data;
46
+ +}
47
+ +
48
+ # query params always arrive as strings, so accept the usual spellings of a
49
+ # boolean and fall back to the default documented in the swagger_path
50
+ sub _bool_param {
51
+ @@ -296,14 +335,23 @@ swagger_path {
52
+ default => 'true',
53
+ in => 'query',
54
+ },
55
+ + include => {
56
+ + description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
57
+ + type => 'string',
58
+ + in => 'query',
59
+ + },
60
+ ],
61
+ responses => { default => {} },
62
+ }, get '/api/v1/object/device/:ip/nodes' => require_role api => sub {
63
+ my $active = _bool_param(params->{active_only}, 1);
64
+ + my @includes = _node_includes(params->{include});
65
+ + # qualified, because prefetching ips or netbios joins tables that have
66
+ + # an active column of their own
67
+ my $rows = try { schema(vars->{'tenant'})->resultset('Node')
68
+ - ->search({ switch => params->{ip}, ($active ? (-bool => 'active') : ()) }) }
69
+ + ->search({ 'me.switch' => params->{ip}, ($active ? (-bool => 'me.active') : ()) },
70
+ + (@includes ? { prefetch => [@includes] } : ())) }
71
+ or send_error('Bad Device', 404);
72
+ - return to_json [ map {$_->TO_JSON} $rows->all ];
73
+ + return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
74
+ };
75
+
76
+ swagger_path {
77
+ @@ -371,14 +419,23 @@ swagger_path {
78
+ default => 'true',
79
+ in => 'query',
80
+ },
81
+ + include => {
82
+ + description => 'Comma-separated list of related rows to embed in each Node: wireless (node_wireless - SSID, signal, rates), ips (node_ip), netbios (node_nbt), manufacturer (vendor from the OUI). Omitted by default.',
83
+ + type => 'string',
84
+ + in => 'query',
85
+ + },
86
+ ],
87
+ responses => { default => {} },
88
+ }, get '/api/v1/object/vlan/:vlan/nodes' => require_role api => sub {
89
+ my $active = _bool_param(params->{active_only}, 1);
90
+ + my @includes = _node_includes(params->{include});
91
+ + # qualified, because prefetching ips or netbios joins tables that have
92
+ + # an active column of their own
93
+ my $rows = try { schema(vars->{'tenant'})->resultset('Node')
94
+ - ->search({ vlan => params->{vlan}, ($active ? (-bool => 'active') : ()) }) }
95
+ + ->search({ 'me.vlan' => params->{vlan}, ($active ? (-bool => 'me.active') : ()) },
96
+ + (@includes ? { prefetch => [@includes] } : ())) }
97
+ or send_error('Bad VLAN', 404);
98
+ - return to_json [ map {$_->TO_JSON} $rows->all ];
99
+ + return to_json [ map { _node_to_json($_, @includes) } $rows->all ];
100
+ };
101
+
102
+ swagger_path {
tasks/netdisco__netdisco-1682/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 e7324236c7256e8618679d3a4b83349983dae8e7 > "$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/netdisco__netdisco-1682/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/netdisco__netdisco-1683/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/netdisco/netdisco.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/netdisco/netdisco.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/netdisco/netdisco.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 58aa309e075efe3dac0f995aee67903169d14096 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 58aa309e075efe3dac0f995aee67903169d14096 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 58aa309e075efe3dac0f995aee67903169d14096 \
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/netdisco__netdisco-1683/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** stop storing wireless clients under an SSID called "unknown"
4
+
5
+ ## Description
6
+
7
+ `Macsuck::WirelessNodes` walks `cd11_txrate`, then looks up each index in `cd11_ssid`. Those are separate SNMP walks and do not always line up — as the existing comment a few lines up already notes for the rate table. When an index is missing from the SSID walk, the worker stores the client anyway:
8
+
9
+ ```perl
10
+ my $ssid = $cd11_ssid->{$idx} || 'unknown';
11
+ ```
12
+
13
+ That client is not on an SSID named "unknown", it is one we could not attribute on that pass — usually associating or roaming between the two walks. Since `node_wireless` is keyed on `(mac, ssid)`, the row becomes a second permanent identity for that client alongside its real SSID row, and nothing expires `node_wireless`, so it stays for good.
14
+
15
+ On one controller here, 46% of all `node_wireless` rows are "unknown" — more than any real SSID. Of 5807 clients holding more than one row, 5805 are a real SSID plus this artefact; exactly two are genuinely on two SSIDs. Anything joining `node` to `node_wireless` on MAC, including the web UI's own Ports tab with `n_ssid`, sees its rows roughly doubled by a value carrying no information.
16
+
17
+ This skips the client when no SSID is available, so it is picked up on a pass where the walk is complete, and reports the count so the condition is visible:
18
+
19
+ ```
20
+ [10.0.0.1] macsuck - processed 412 wireless nodes (7 skipped, no SSID reported)
21
+ ```
22
+
23
+ The check is on `defined`/`length` rather than truthiness, so an SSID that is genuinely `0` is now stored correctly instead of also becoming "unknown".
24
+
25
+ **One question I cannot answer from here:** is there gear that never populates `cd11_ssid` at all? On such a device this drops the signal and rate data stored today, unusable SSID or not. If that case is real this should be a setting defaulting to current behaviour instead, and I am happy to redo it that way.
26
+
27
+ Unrelated but noticed while in here: `node_wireless` has no expiry at all, unlike `node` with `expire_nodes`. Even with this fix, stale `(mac, ssid)` pairs accumulate indefinitely. Happy to open something separate if that is worth addressing.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `58aa309e075e`. 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/netdisco__netdisco-1683/solution/patch.diff ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/Changes b/Changes
2
+ index de117dac..209335ee 100644
3
+ --- a/Changes
4
+ +++ b/Changes
5
+ @@ -21,6 +21,7 @@
6
+ juniper, and refuses anything else before changing the MIB cache
7
+ * the Job Queue's delete-all button did nothing since 2.109000; it now
8
+ deletes the queue again
9
+ + * #1683 stop storing wireless clients under an SSID called "unknown"
10
+
11
+ 2.109001 - 2026-09-18
12
+
13
+ diff --git a/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm b/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
14
+ index 39825577..bebefb30 100644
15
+ --- a/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
16
+ +++ b/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
17
+ @@ -35,6 +35,13 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
18
+ my $cd11_txbyte = $snmp->cd11_txbyte();
19
+ my $cd11_ssid = $snmp->cd11_ssid();
20
+
21
+ + # A class that implements cd11_txrate but not cd11_ssid at all - Trapeze and
22
+ + # NWSS2300 both do - gets undef back from AUTOLOAD rather than an error, and
23
+ + # for those the old fallback is still the best available answer. Only treat a
24
+ + # missing index as unattributable when the walk returned something.
25
+ + my $have_ssids = (ref $cd11_ssid eq 'HASH' and scalar keys %$cd11_ssid);
26
+ + my $nossid = 0;
27
+ +
28
+ while (my ($idx, $txrates) = each %$cd11_txrate) {
29
+ my $rates = $cd11_rateset->{$idx};
30
+ my $mac = $cd11_mac->{$idx};
31
+ @@ -49,7 +56,22 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
32
+ ? int($rates->[$#$rates])
33
+ : undef;
34
+
35
+ - my $ssid = $cd11_ssid->{$idx} || 'unknown';
36
+ + # the SSID table is a separate walk from the rate table and, as above,
37
+ + # can have fewer rows. An index missing here is a client we cannot
38
+ + # attribute to an SSID on this pass, not a client on an SSID called
39
+ + # "unknown" - and since (mac, ssid) is the primary key, storing it under
40
+ + # that name gives the client a second identity which nothing expires.
41
+ + # Skip it and pick the client up on a pass where the walk is complete.
42
+ + my $ssid = $cd11_ssid->{$idx};
43
+ + if (! defined $ssid or ! length $ssid) {
44
+ + if (! $have_ssids) {
45
+ + $ssid = 'unknown';
46
+ + }
47
+ + else {
48
+ + ++$nossid;
49
+ + next;
50
+ + }
51
+ + }
52
+
53
+ schema('netdisco')->txn_do(sub {
54
+ schema('netdisco')->resultset('NodeWireless')
55
+ @@ -72,8 +94,9 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
56
+ });
57
+ }
58
+
59
+ - return Status->info(sprintf ' [%s] macsuck - processed %s wireless nodes',
60
+ - $device->ip, scalar keys %{ $cd11_txrate });
61
+ + return Status->info(sprintf ' [%s] macsuck - processed %s wireless nodes%s',
62
+ + $device->ip, (scalar keys %{ $cd11_txrate }),
63
+ + ($nossid ? sprintf(' (%s skipped, no SSID reported)', $nossid) : ''));
64
+ });
65
+
66
+ true;
tasks/netdisco__netdisco-1683/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/netdisco__netdisco-1683/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/netdisco__netdisco-1683"
5
+ description = "stop storing wireless clients under an SSID called \"unknown\""
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "netdisco",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "netdisco/netdisco"
19
+ ref = "58aa309e075efe3dac0f995aee67903169d14096"
20
+ reference = "https://github.com/netdisco/netdisco/pull/1683"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:58.491714+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:49ddf295f123a50d03fb33e2f2e676225b20b92756b8a62de6d59915e5d0ccc7"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-09-29T03:47:31Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "Changes",
34
+ "lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm",
35
+ ]
36
+ bootstrap_image = "python:3.12-slim"
37
+
38
+ [metadata.repo2env.reward_calibration]
39
+ baseline_reward = 0.0
40
+ loc_changed = 30
41
+ difficulty = "medium"
42
+
43
+ [metadata.repo2env.evaluation]
44
+ schema_version = "1"
45
+ status = "unverified"
46
+ stage = "generation"
47
+ reason_codes = [
48
+ "validation_not_run",
49
+ ]
50
+ detail = "Generated task; validation has not been established."
51
+ provenance = "unknown"
52
+ evidence = []
53
+
54
+ [metadata.repo2env.reproducibility]
55
+ mode = "inline_dockerfile"
56
+ image_ref = "python:3.12-slim"
57
+ image_tag = "python:3.12-slim"
58
+ image_visibility = "public"
59
+ pushed_at = "2026-11-16T16:20:01.773012+00:00"
60
+ pushed_by = "scalingX"
61
+ inline_recipe_sha256 = "sha256:9582644558832ff147d621456e46b4b9b7b7b8f7300346fa4f24b9763f058f13"
62
+ inline_recipe_lines = 37
63
+ inline_recipe_source = "user_dockerfile"
64
+
65
+ [agent]
66
+ timeout_sec = 1800.0
67
+
68
+ [verifier]
69
+ timeout_sec = 300.0
tasks/netdisco__netdisco-1683/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/netdisco__netdisco-1683/tests/instruction.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** stop storing wireless clients under an SSID called "unknown"
4
+
5
+ ## Description
6
+
7
+ `Macsuck::WirelessNodes` walks `cd11_txrate`, then looks up each index in `cd11_ssid`. Those are separate SNMP walks and do not always line up — as the existing comment a few lines up already notes for the rate table. When an index is missing from the SSID walk, the worker stores the client anyway:
8
+
9
+ ```perl
10
+ my $ssid = $cd11_ssid->{$idx} || 'unknown';
11
+ ```
12
+
13
+ That client is not on an SSID named "unknown", it is one we could not attribute on that pass — usually associating or roaming between the two walks. Since `node_wireless` is keyed on `(mac, ssid)`, the row becomes a second permanent identity for that client alongside its real SSID row, and nothing expires `node_wireless`, so it stays for good.
14
+
15
+ On one controller here, 46% of all `node_wireless` rows are "unknown" — more than any real SSID. Of 5807 clients holding more than one row, 5805 are a real SSID plus this artefact; exactly two are genuinely on two SSIDs. Anything joining `node` to `node_wireless` on MAC, including the web UI's own Ports tab with `n_ssid`, sees its rows roughly doubled by a value carrying no information.
16
+
17
+ This skips the client when no SSID is available, so it is picked up on a pass where the walk is complete, and reports the count so the condition is visible:
18
+
19
+ ```
20
+ [10.0.0.1] macsuck - processed 412 wireless nodes (7 skipped, no SSID reported)
21
+ ```
22
+
23
+ The check is on `defined`/`length` rather than truthiness, so an SSID that is genuinely `0` is now stored correctly instead of also becoming "unknown".
24
+
25
+ **One question I cannot answer from here:** is there gear that never populates `cd11_ssid` at all? On such a device this drops the signal and rate data stored today, unusable SSID or not. If that case is real this should be a setting defaulting to current behaviour instead, and I am happy to redo it that way.
26
+
27
+ Unrelated but noticed while in here: `node_wireless` has no expiry at all, unlike `node` with `expire_nodes`. Even with this fix, stale `(mac, ssid)` pairs accumulate indefinitely. Happy to open something separate if that is worth addressing.
28
+
29
+ ## Task
30
+
31
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `58aa309e075e`. 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/netdisco__netdisco-1683/tests/oracle.patch ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/Changes b/Changes
2
+ index de117dac..209335ee 100644
3
+ --- a/Changes
4
+ +++ b/Changes
5
+ @@ -21,6 +21,7 @@
6
+ juniper, and refuses anything else before changing the MIB cache
7
+ * the Job Queue's delete-all button did nothing since 2.109000; it now
8
+ deletes the queue again
9
+ + * #1683 stop storing wireless clients under an SSID called "unknown"
10
+
11
+ 2.109001 - 2026-09-18
12
+
13
+ diff --git a/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm b/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
14
+ index 39825577..bebefb30 100644
15
+ --- a/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
16
+ +++ b/lib/App/Netdisco/Worker/Plugin/Macsuck/WirelessNodes.pm
17
+ @@ -35,6 +35,13 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
18
+ my $cd11_txbyte = $snmp->cd11_txbyte();
19
+ my $cd11_ssid = $snmp->cd11_ssid();
20
+
21
+ + # A class that implements cd11_txrate but not cd11_ssid at all - Trapeze and
22
+ + # NWSS2300 both do - gets undef back from AUTOLOAD rather than an error, and
23
+ + # for those the old fallback is still the best available answer. Only treat a
24
+ + # missing index as unattributable when the walk returned something.
25
+ + my $have_ssids = (ref $cd11_ssid eq 'HASH' and scalar keys %$cd11_ssid);
26
+ + my $nossid = 0;
27
+ +
28
+ while (my ($idx, $txrates) = each %$cd11_txrate) {
29
+ my $rates = $cd11_rateset->{$idx};
30
+ my $mac = $cd11_mac->{$idx};
31
+ @@ -49,7 +56,22 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
32
+ ? int($rates->[$#$rates])
33
+ : undef;
34
+
35
+ - my $ssid = $cd11_ssid->{$idx} || 'unknown';
36
+ + # the SSID table is a separate walk from the rate table and, as above,
37
+ + # can have fewer rows. An index missing here is a client we cannot
38
+ + # attribute to an SSID on this pass, not a client on an SSID called
39
+ + # "unknown" - and since (mac, ssid) is the primary key, storing it under
40
+ + # that name gives the client a second identity which nothing expires.
41
+ + # Skip it and pick the client up on a pass where the walk is complete.
42
+ + my $ssid = $cd11_ssid->{$idx};
43
+ + if (! defined $ssid or ! length $ssid) {
44
+ + if (! $have_ssids) {
45
+ + $ssid = 'unknown';
46
+ + }
47
+ + else {
48
+ + ++$nossid;
49
+ + next;
50
+ + }
51
+ + }
52
+
53
+ schema('netdisco')->txn_do(sub {
54
+ schema('netdisco')->resultset('NodeWireless')
55
+ @@ -72,8 +94,9 @@ register_worker({ phase => 'main', driver => 'snmp' }, sub {
56
+ });
57
+ }
58
+
59
+ - return Status->info(sprintf ' [%s] macsuck - processed %s wireless nodes',
60
+ - $device->ip, scalar keys %{ $cd11_txrate });
61
+ + return Status->info(sprintf ' [%s] macsuck - processed %s wireless nodes%s',
62
+ + $device->ip, (scalar keys %{ $cd11_txrate }),
63
+ + ($nossid ? sprintf(' (%s skipped, no SSID reported)', $nossid) : ''));
64
+ });
65
+
66
+ true;
tasks/netdisco__netdisco-1683/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 58aa309e075efe3dac0f995aee67903169d14096 > "$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/netdisco__netdisco-1683/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/netdisco__netdisco-1684/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/netdisco/netdisco.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/netdisco/netdisco.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/netdisco/netdisco.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 619f07342c315f4bb5f283ad6748a3f8a465ff3e 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 619f07342c315f4bb5f283ad6748a3f8a465ff3e \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 619f07342c315f4bb5f283ad6748a3f8a465ff3e \
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/netdisco__netdisco-1684/instruction.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the python-dependencies group in /share/python/netdisco with 2 updates
4
+
5
+ ## Description
6
+
7
+ Updates the requirements on [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) and [uv-build](https://github.com/astral-sh/uv) to permit the latest version.
8
+ Updates `sqlalchemy` to 2.0.53
9
+ <details>
10
+ <summary>Release notes</summary>
11
+ <p><em>Sourced from <a href="https://github.com/sqlalchemy/sqlalchemy/releases">sqlalchemy's releases</a>.</em></p>
12
+ <blockquote>
13
+ <h1>2.0.53</h1>
14
+ <p>Released: September 14, 2026</p>
15
+ <h2>orm</h2>
16
+ <ul>
17
+ <li>
18
+ <p><strong>[orm] [bug]</strong> Fixed issue where an expression passed to <code>_orm.with_expression()</code>
19
+ that embedded a <code>_sql.select()</code>, such as a correlated
20
+ <code>_sql.exists()</code>, would fail to populate the attribute correctly on
21
+ the second and subsequent executions of an otherwise identical
22
+ statement, when the <code>_orm.query_expression()</code> attribute was loaded
23
+ by a relationship loader that emits a second query, i.e.
24
+ <code>_orm.selectinload()</code>, <code>_orm.lazyload()</code> or
25
+ <code>_orm.immediateload()</code>.</p>
26
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13560">#13560</a></p>
27
+ </li>
28
+ <li>
29
+ <p><strong>[orm] [bug]</strong> Fixed memory issue where mapped classes, along with their
30
+ <code>Table</code> and <code>_orm.Mapper</code> objects, would not be garbage
31
+ collected after the <code>_orm.registry</code> in which they were mapped had
32
+ been disposed and dereferenced. The issue would occur for mappings that
33
+ made use of <code>_orm.relationship()</code> together with constructs such as an
34
+ <code>Index</code> established against an ORM-annotated expression.</p>
35
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13566">#13566</a></p>
36
+ </li>
37
+ <li>
38
+ <p><strong>[orm] [bug]</strong> Fixed issue where pickling an ORM object that had an instance level lazy
39
+ loader established, such as when the <code>_orm.raiseload()</code> option is used,
40
+ would emit a spurious warning regarding the loader containing additional
41
+ criteria, if the object had itself been unpickled from a previous
42
+ serialization. This would occur for objects that cross more than one
43
+ serialization boundary, such as when using multiprocessing.</p>
44
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13574">#13574</a></p>
45
+ </li>
46
+ <li>
47
+ <p><strong>[orm] [bug]</strong> Fixed issue where calling <code>_orm.aliased()</code> against an existing
48
+ <code>_orm.aliased()</code> construct, without passing an explicit selectable,
49
+ would disregard the selectable of the existing construct and produce an
50
+ alias of the mapped table instead, if that selectable were anything other
51
+ than a table or a plain subquery, leading to incorrect results and/or
52
+ non-working queries.</p>
53
+ <p>This includes <code>_orm.aliased()</code> against a <code>_orm.with_polymorphic()</code>
54
+ construct, which would previously produce an alias of the base mapped
55
+ class only, discarding the polymorphic selectable and additional mappers.
56
+ The new construct now retains these, so that criteria against subclass
57
+ attributes and the <code>innerjoin</code> and <code>selectable</code> parameters of
58
+ <code>_orm.with_polymorphic()</code> take effect, and subclass columns are loaded
59
+ up front. The SQL rendered for these constructs now includes the</p>
60
+ </li>
61
+ </ul>
62
+ <!-- raw HTML omitted -->
63
+ </blockquote>
64
+ <p>... (truncated)</p>
65
+ </details>
66
+ <details>
67
+ <summary>Commits</summary>
68
+ <ul>
69
+ <li>See full diff in <a href="https://github.com/sqlalchemy/sqlalchemy/commits">compare view</a></li>
70
+ </ul>
71
+ </details>
72
+ <br />
73
+
74
+ Updates `uv-build` to 0.12.14
75
+ <details>
76
+ <summary>Release notes</summary>
77
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/releases">uv-build's releases</a>.</em></p>
78
+ <blockquote>
79
+ <h2>0.12.14</h2>
80
+ <h2>Release Notes</h2>
81
+ <p>Released on 2026-09-15.</p>
82
+ <h3>Enhancements</h3>
83
+ <ul>
84
+ <li>Resume interrupted downloads with HTTP Range requests when supported (<a href="">#21570</a>)</li>
85
+ <li>Use a consistent format for error rendering (<a href="">#17110</a>)</li>
86
+ <li>Render error and warning causes with compact <code>cause:</code> labels (<a href="">#21599</a>, <a href="">#21603</a>)</li>
87
+ <li>Show underlying causes and hints in user warnings (<a href="">#21565</a>)</li>
88
+ <li>Show resolver hints for failed <code>uv tool upgrade</code> operations (<a href="">#21566</a>)</li>
89
+ </ul>
90
+ <h3>Preview features</h3>
91
+ <ul>
92
+ <li>Export multiple dependency selections from a shared lockfile in one <code>uv export --batch</code> invocation with the <code>batch-export</code> preview feature (<a href="">#21618</a>)</li>
93
+ </ul>
94
+ <h3>Performance</h3>
95
+ <ul>
96
+ <li>Speed up dependency resolution from local wheelhouses by reading wheel metadata in a single blocking task (<a href="">#21619</a>)</li>
97
+ <li>Speed up cold resolution against large package indexes by parsing Simple API responses in bounded background workers (<a href="">#21593</a>)</li>
98
+ <li>Speed up warm-cache resolution by decoding fresh HTTP cache entries in the cache-read task (<a href="">#21621</a>)</li>
99
+ </ul>
100
+ <h3>Bug fixes</h3>
101
+ <ul>
102
+ <li>Select releases that satisfy <code>required-environments</code> within each resolver fork instead of combining incompatible wheel coverage across forks (<a href="">#21672</a>)</li>
103
+ <li>Install packages with paths longer than <code>MAX_PATH</code> on Windows systems without long-path support enabled (<a href="">#21625</a>)</li>
104
+ <li>Prevent <code>uv python install</code> from overwriting valid unmanaged Python symlinks with relative targets on Unix (<a href="">#21639</a>)</li>
105
+ <li>Redact credentials and signatures from missing-path-segment URL errors (<a href="">#21616</a>)</li>
106
+ <li>Avoid exceeding the configured retry budget when cached HTTP responses fail revalidation (<a href="">#21640</a>)</li>
107
+ <li>Prefer <code>bin/python</code> over <code>bin/python3</code> when discovering interpreters in Unix environments (<a href="">#21559</a>)</li>
108
+ <li>Classify package-operation exit codes by their underlying cause: return <code>1</code> for expected failures and <code>2</code> for recognized operational and internal failures (<a href="">#17110</a>)</li>
109
+ <li>Suppress managed-Python fallback warnings under <code>--quiet</code> (<a href="">#21565</a>)</li>
110
+ <li>Keep failed <code>uv tool upgrade</code> errors visible with <code>-q</code> while suppressing them with <code>-qq</code> (<a href="">#21566</a>)</li>
111
+ </ul>
112
+ <h2>Install uv 0.12.14</h2>
113
+ <h3>Install prebuilt binaries via shell script</h3>
114
+ <pre lang="sh"><code>curl --proto '=https' --tlsv1.2 -LsSf https://releases.astral.sh/github/uv/releases/download/0.12.14/uv-installer.sh | sh
115
+ </code></pre>
116
+ <h3>Install prebuilt binaries via powershell script</h3>
117
+ <pre lang="sh"><code>powershell -ExecutionPolicy Bypass -c &quot;irm https://releases.astral.sh/github/uv/releases/download/0.12.14/uv-installer.ps1 | iex&quot;
118
+ </code></pre>
119
+ <h2>Download uv 0.12.14</h2>
120
+ <!-- raw HTML omitted -->
121
+ </blockquote>
122
+ <p>... (truncated)</p>
123
+ </details>
124
+ <details>
125
+ <summary>Changelog</summary>
126
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/blob/main/CHANGELOG.md">uv-build's changelog</a>.</em></p>
127
+ <blockquote>
128
+ <h2>0.12.14</h2>
129
+ <p>Released on 2026-09-15.</p>
130
+ <h3>Enhancements</h3>
131
+ <ul>
132
+ <li>Resume interrupted downloads with HTTP Range requests when supported (<a href="">#21570</a>)</li>
133
+ <li>Use a consistent format for error rendering (<a href="">#17110</a>)</li>
134
+ <li>Render error and warning causes with compact <code>cause:</code> labels (<a href="">#21599</a>, <a href="">#21603</a>)</li>
135
+ <li>Show underlying causes and hints in user warnings (<a href="">#21565</a>)</li>
136
+ <li>Show resolver hints for failed <code>uv tool upgrade</code> operations (<a href="">#21566</a>)</li>
137
+ </ul>
138
+ <h3>Preview features</h3>
139
+ <ul>
140
+ <li>Export multiple dependency selections from a shared lockfile in one <code>uv export --batch</code> invocation with the <code>batch-export</code> preview feature (<a href="">#21618</a>)</li>
141
+ </ul>
142
+ <h3>Performance</h3>
143
+ <ul>
144
+ <li>Speed up dependency resolution from local wheelhouses by reading wheel metadata in a single blocking task (<a href="">#21619</a>)</li>
145
+ <li>Speed up cold resolution against large package indexes by parsing Simple API responses in bounded background workers (<a href="">#21593</a>)</li>
146
+ <li>Speed up warm-cache resolution by decoding fresh HTTP cache entries in the cache-read task (<a href="">#21621</a>)</li>
147
+ </ul>
148
+ <h3>Bug fixes</h3>
149
+ <ul>
150
+ <li>Select releases that satisfy <code>required-environments</code> within each resolver fork instead of combining incompatible wheel coverage across forks (<a href="">#21672</a>)</li>
151
+ <li>Install packages with paths longer than <code>MAX_PATH</code> on Windows systems without long-path support enabled (<a href="">#21625</a>)</li>
152
+ <li>Prevent <code>uv python install</code> from overwriting valid unmanaged Python symlinks with relative targets on Unix (<a href="">#21639</a>)</li>
153
+ <li>Redact credentials and signatures from missing-path-segment URL errors (<a href="">#21616</a>)</li>
154
+ <li>Avoid exceeding the configured retry budget when cached HTTP responses fail revalidation (<a href="">#21640</a>)</li>
155
+ <li>Prefer <code>bin/python</code> over <code>bin/python3</code> when discovering interpreters in Unix environments (<a href="">#21559</a>)</li>
156
+ <li>Classify package-operation exit codes by their underlying cause: return <code>1</code> for expected failures and <code>2</code> for recognized operational and internal failures (<a href="">#17110</a>)</li>
157
+ <li>Suppress managed-Python fallback warnings under <code>--quiet</code> (<a href="">#21565</a>)</li>
158
+ <li>Keep failed <code>uv tool upgrade</code> errors visible with <code>-q</code> while suppressing them with <code>-qq</code> (<a href="">#21566</a>)</li>
159
+ </ul>
160
+ <h2>0.12.13</h2>
161
+ <p>Released on 2026-09-10.</p>
162
+ <h3>Python</h3>
163
+ <ul>
164
+ <li>Add GraalPy 3.13.0 (<a href="">#21431</a>)</li>
165
+ </ul>
166
+ <h3>Enhancements</h3>
167
+ <ul>
168
+ <li>Verify hashes when downloading PEP 658 metadata sidecars (<a href="">#21563</a>)</li>
169
+ </ul>
170
+ <h3>Preview features</h3>
171
+ <ul>
172
+ <li>Respect <code>ty</code> exclusions when <code>uv check</code> automatica
173
+
174
+ ## Task
175
+
176
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `619f07342c31`. 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/netdisco__netdisco-1684/solution/patch.diff ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/share/python/netdisco/pyproject.toml b/share/python/netdisco/pyproject.toml
2
+ index 85fa1b29..7985b896 100644
3
+ --- a/share/python/netdisco/pyproject.toml
4
+ +++ b/share/python/netdisco/pyproject.toml
5
+ @@ -10,16 +10,16 @@ dependencies = [
6
+ "netmiko>=4.7.0,<5",
7
+ "cryptography>=50.0.1,<51",
8
+ "virtualenv>=21.7.9",
9
+ - "sqlalchemy>=2.0.52,<3",
10
+ + "sqlalchemy>=2.0.53,<3",
11
+ "psycopg>=3.3.5,<4",
12
+ - "uv-build>=0.12.13,<0.13.0",
13
+ + "uv-build>=0.12.14,<0.13.0",
14
+ ]
15
+
16
+ [project.scripts]
17
+ run_worklet = "netdisco.runner:main"
18
+
19
+ [build-system]
20
+ -requires = ["uv_build>=0.12.13,<0.13.0"]
21
+ +requires = ["uv_build>=0.12.14,<0.13.0"]
22
+ build-backend = "uv_build"
23
+
24
+ [dependency-groups]
tasks/netdisco__netdisco-1684/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/netdisco__netdisco-1684/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/netdisco__netdisco-1684"
5
+ description = "Bump the python-dependencies group in /share/python/netdisco with 2 updates"
6
+
7
+ [metadata]
8
+ difficulty = "small"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "netdisco",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "netdisco/netdisco"
19
+ ref = "619f07342c315f4bb5f283ad6748a3f8a465ff3e"
20
+ reference = "https://github.com/netdisco/netdisco/pull/1684"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:58.518047+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:e46656d8e60d008b9a62a2c4dd0a1d60d9691d7e8cc48e47e405e5a71cafffc7"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-09-18T08:17:11Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "share/python/netdisco/pyproject.toml",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 6
40
+ difficulty = "small"
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:01.773520+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:697fa98dc3f2f2e0fa865613c083f8dd272b49a0475f7db9465136cade6abe07"
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/netdisco__netdisco-1684/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/netdisco__netdisco-1684/tests/instruction.md ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the python-dependencies group in /share/python/netdisco with 2 updates
4
+
5
+ ## Description
6
+
7
+ Updates the requirements on [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy) and [uv-build](https://github.com/astral-sh/uv) to permit the latest version.
8
+ Updates `sqlalchemy` to 2.0.53
9
+ <details>
10
+ <summary>Release notes</summary>
11
+ <p><em>Sourced from <a href="https://github.com/sqlalchemy/sqlalchemy/releases">sqlalchemy's releases</a>.</em></p>
12
+ <blockquote>
13
+ <h1>2.0.53</h1>
14
+ <p>Released: September 14, 2026</p>
15
+ <h2>orm</h2>
16
+ <ul>
17
+ <li>
18
+ <p><strong>[orm] [bug]</strong> Fixed issue where an expression passed to <code>_orm.with_expression()</code>
19
+ that embedded a <code>_sql.select()</code>, such as a correlated
20
+ <code>_sql.exists()</code>, would fail to populate the attribute correctly on
21
+ the second and subsequent executions of an otherwise identical
22
+ statement, when the <code>_orm.query_expression()</code> attribute was loaded
23
+ by a relationship loader that emits a second query, i.e.
24
+ <code>_orm.selectinload()</code>, <code>_orm.lazyload()</code> or
25
+ <code>_orm.immediateload()</code>.</p>
26
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13560">#13560</a></p>
27
+ </li>
28
+ <li>
29
+ <p><strong>[orm] [bug]</strong> Fixed memory issue where mapped classes, along with their
30
+ <code>Table</code> and <code>_orm.Mapper</code> objects, would not be garbage
31
+ collected after the <code>_orm.registry</code> in which they were mapped had
32
+ been disposed and dereferenced. The issue would occur for mappings that
33
+ made use of <code>_orm.relationship()</code> together with constructs such as an
34
+ <code>Index</code> established against an ORM-annotated expression.</p>
35
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13566">#13566</a></p>
36
+ </li>
37
+ <li>
38
+ <p><strong>[orm] [bug]</strong> Fixed issue where pickling an ORM object that had an instance level lazy
39
+ loader established, such as when the <code>_orm.raiseload()</code> option is used,
40
+ would emit a spurious warning regarding the loader containing additional
41
+ criteria, if the object had itself been unpickled from a previous
42
+ serialization. This would occur for objects that cross more than one
43
+ serialization boundary, such as when using multiprocessing.</p>
44
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13574">#13574</a></p>
45
+ </li>
46
+ <li>
47
+ <p><strong>[orm] [bug]</strong> Fixed issue where calling <code>_orm.aliased()</code> against an existing
48
+ <code>_orm.aliased()</code> construct, without passing an explicit selectable,
49
+ would disregard the selectable of the existing construct and produce an
50
+ alias of the mapped table instead, if that selectable were anything other
51
+ than a table or a plain subquery, leading to incorrect results and/or
52
+ non-working queries.</p>
53
+ <p>This includes <code>_orm.aliased()</code> against a <code>_orm.with_polymorphic()</code>
54
+ construct, which would previously produce an alias of the base mapped
55
+ class only, discarding the polymorphic selectable and additional mappers.
56
+ The new construct now retains these, so that criteria against subclass
57
+ attributes and the <code>innerjoin</code> and <code>selectable</code> parameters of
58
+ <code>_orm.with_polymorphic()</code> take effect, and subclass columns are loaded
59
+ up front. The SQL rendered for these constructs now includes the</p>
60
+ </li>
61
+ </ul>
62
+ <!-- raw HTML omitted -->
63
+ </blockquote>
64
+ <p>... (truncated)</p>
65
+ </details>
66
+ <details>
67
+ <summary>Commits</summary>
68
+ <ul>
69
+ <li>See full diff in <a href="https://github.com/sqlalchemy/sqlalchemy/commits">compare view</a></li>
70
+ </ul>
71
+ </details>
72
+ <br />
73
+
74
+ Updates `uv-build` to 0.12.14
75
+ <details>
76
+ <summary>Release notes</summary>
77
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/releases">uv-build's releases</a>.</em></p>
78
+ <blockquote>
79
+ <h2>0.12.14</h2>
80
+ <h2>Release Notes</h2>
81
+ <p>Released on 2026-09-15.</p>
82
+ <h3>Enhancements</h3>
83
+ <ul>
84
+ <li>Resume interrupted downloads with HTTP Range requests when supported (<a href="">#21570</a>)</li>
85
+ <li>Use a consistent format for error rendering (<a href="">#17110</a>)</li>
86
+ <li>Render error and warning causes with compact <code>cause:</code> labels (<a href="">#21599</a>, <a href="">#21603</a>)</li>
87
+ <li>Show underlying causes and hints in user warnings (<a href="">#21565</a>)</li>
88
+ <li>Show resolver hints for failed <code>uv tool upgrade</code> operations (<a href="">#21566</a>)</li>
89
+ </ul>
90
+ <h3>Preview features</h3>
91
+ <ul>
92
+ <li>Export multiple dependency selections from a shared lockfile in one <code>uv export --batch</code> invocation with the <code>batch-export</code> preview feature (<a href="">#21618</a>)</li>
93
+ </ul>
94
+ <h3>Performance</h3>
95
+ <ul>
96
+ <li>Speed up dependency resolution from local wheelhouses by reading wheel metadata in a single blocking task (<a href="">#21619</a>)</li>
97
+ <li>Speed up cold resolution against large package indexes by parsing Simple API responses in bounded background workers (<a href="">#21593</a>)</li>
98
+ <li>Speed up warm-cache resolution by decoding fresh HTTP cache entries in the cache-read task (<a href="">#21621</a>)</li>
99
+ </ul>
100
+ <h3>Bug fixes</h3>
101
+ <ul>
102
+ <li>Select releases that satisfy <code>required-environments</code> within each resolver fork instead of combining incompatible wheel coverage across forks (<a href="">#21672</a>)</li>
103
+ <li>Install packages with paths longer than <code>MAX_PATH</code> on Windows systems without long-path support enabled (<a href="">#21625</a>)</li>
104
+ <li>Prevent <code>uv python install</code> from overwriting valid unmanaged Python symlinks with relative targets on Unix (<a href="">#21639</a>)</li>
105
+ <li>Redact credentials and signatures from missing-path-segment URL errors (<a href="">#21616</a>)</li>
106
+ <li>Avoid exceeding the configured retry budget when cached HTTP responses fail revalidation (<a href="">#21640</a>)</li>
107
+ <li>Prefer <code>bin/python</code> over <code>bin/python3</code> when discovering interpreters in Unix environments (<a href="">#21559</a>)</li>
108
+ <li>Classify package-operation exit codes by their underlying cause: return <code>1</code> for expected failures and <code>2</code> for recognized operational and internal failures (<a href="">#17110</a>)</li>
109
+ <li>Suppress managed-Python fallback warnings under <code>--quiet</code> (<a href="">#21565</a>)</li>
110
+ <li>Keep failed <code>uv tool upgrade</code> errors visible with <code>-q</code> while suppressing them with <code>-qq</code> (<a href="">#21566</a>)</li>
111
+ </ul>
112
+ <h2>Install uv 0.12.14</h2>
113
+ <h3>Install prebuilt binaries via shell script</h3>
114
+ <pre lang="sh"><code>curl --proto '=https' --tlsv1.2 -LsSf https://releases.astral.sh/github/uv/releases/download/0.12.14/uv-installer.sh | sh
115
+ </code></pre>
116
+ <h3>Install prebuilt binaries via powershell script</h3>
117
+ <pre lang="sh"><code>powershell -ExecutionPolicy Bypass -c &quot;irm https://releases.astral.sh/github/uv/releases/download/0.12.14/uv-installer.ps1 | iex&quot;
118
+ </code></pre>
119
+ <h2>Download uv 0.12.14</h2>
120
+ <!-- raw HTML omitted -->
121
+ </blockquote>
122
+ <p>... (truncated)</p>
123
+ </details>
124
+ <details>
125
+ <summary>Changelog</summary>
126
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/blob/main/CHANGELOG.md">uv-build's changelog</a>.</em></p>
127
+ <blockquote>
128
+ <h2>0.12.14</h2>
129
+ <p>Released on 2026-09-15.</p>
130
+ <h3>Enhancements</h3>
131
+ <ul>
132
+ <li>Resume interrupted downloads with HTTP Range requests when supported (<a href="">#21570</a>)</li>
133
+ <li>Use a consistent format for error rendering (<a href="">#17110</a>)</li>
134
+ <li>Render error and warning causes with compact <code>cause:</code> labels (<a href="">#21599</a>, <a href="">#21603</a>)</li>
135
+ <li>Show underlying causes and hints in user warnings (<a href="">#21565</a>)</li>
136
+ <li>Show resolver hints for failed <code>uv tool upgrade</code> operations (<a href="">#21566</a>)</li>
137
+ </ul>
138
+ <h3>Preview features</h3>
139
+ <ul>
140
+ <li>Export multiple dependency selections from a shared lockfile in one <code>uv export --batch</code> invocation with the <code>batch-export</code> preview feature (<a href="">#21618</a>)</li>
141
+ </ul>
142
+ <h3>Performance</h3>
143
+ <ul>
144
+ <li>Speed up dependency resolution from local wheelhouses by reading wheel metadata in a single blocking task (<a href="">#21619</a>)</li>
145
+ <li>Speed up cold resolution against large package indexes by parsing Simple API responses in bounded background workers (<a href="">#21593</a>)</li>
146
+ <li>Speed up warm-cache resolution by decoding fresh HTTP cache entries in the cache-read task (<a href="">#21621</a>)</li>
147
+ </ul>
148
+ <h3>Bug fixes</h3>
149
+ <ul>
150
+ <li>Select releases that satisfy <code>required-environments</code> within each resolver fork instead of combining incompatible wheel coverage across forks (<a href="">#21672</a>)</li>
151
+ <li>Install packages with paths longer than <code>MAX_PATH</code> on Windows systems without long-path support enabled (<a href="">#21625</a>)</li>
152
+ <li>Prevent <code>uv python install</code> from overwriting valid unmanaged Python symlinks with relative targets on Unix (<a href="">#21639</a>)</li>
153
+ <li>Redact credentials and signatures from missing-path-segment URL errors (<a href="">#21616</a>)</li>
154
+ <li>Avoid exceeding the configured retry budget when cached HTTP responses fail revalidation (<a href="">#21640</a>)</li>
155
+ <li>Prefer <code>bin/python</code> over <code>bin/python3</code> when discovering interpreters in Unix environments (<a href="">#21559</a>)</li>
156
+ <li>Classify package-operation exit codes by their underlying cause: return <code>1</code> for expected failures and <code>2</code> for recognized operational and internal failures (<a href="">#17110</a>)</li>
157
+ <li>Suppress managed-Python fallback warnings under <code>--quiet</code> (<a href="">#21565</a>)</li>
158
+ <li>Keep failed <code>uv tool upgrade</code> errors visible with <code>-q</code> while suppressing them with <code>-qq</code> (<a href="">#21566</a>)</li>
159
+ </ul>
160
+ <h2>0.12.13</h2>
161
+ <p>Released on 2026-09-10.</p>
162
+ <h3>Python</h3>
163
+ <ul>
164
+ <li>Add GraalPy 3.13.0 (<a href="">#21431</a>)</li>
165
+ </ul>
166
+ <h3>Enhancements</h3>
167
+ <ul>
168
+ <li>Verify hashes when downloading PEP 658 metadata sidecars (<a href="">#21563</a>)</li>
169
+ </ul>
170
+ <h3>Preview features</h3>
171
+ <ul>
172
+ <li>Respect <code>ty</code> exclusions when <code>uv check</code> automatica
173
+
174
+ ## Task
175
+
176
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `619f07342c31`. 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/netdisco__netdisco-1684/tests/oracle.patch ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/share/python/netdisco/pyproject.toml b/share/python/netdisco/pyproject.toml
2
+ index 85fa1b29..7985b896 100644
3
+ --- a/share/python/netdisco/pyproject.toml
4
+ +++ b/share/python/netdisco/pyproject.toml
5
+ @@ -10,16 +10,16 @@ dependencies = [
6
+ "netmiko>=4.7.0,<5",
7
+ "cryptography>=50.0.1,<51",
8
+ "virtualenv>=21.7.9",
9
+ - "sqlalchemy>=2.0.52,<3",
10
+ + "sqlalchemy>=2.0.53,<3",
11
+ "psycopg>=3.3.5,<4",
12
+ - "uv-build>=0.12.13,<0.13.0",
13
+ + "uv-build>=0.12.14,<0.13.0",
14
+ ]
15
+
16
+ [project.scripts]
17
+ run_worklet = "netdisco.runner:main"
18
+
19
+ [build-system]
20
+ -requires = ["uv_build>=0.12.13,<0.13.0"]
21
+ +requires = ["uv_build>=0.12.14,<0.13.0"]
22
+ build-backend = "uv_build"
23
+
24
+ [dependency-groups]
tasks/netdisco__netdisco-1684/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 619f07342c315f4bb5f283ad6748a3f8a465ff3e > "$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/netdisco__netdisco-1684/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/netdisco__netdisco-1685/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/netdisco/netdisco.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/netdisco/netdisco.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/netdisco/netdisco.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 619f07342c315f4bb5f283ad6748a3f8a465ff3e 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 619f07342c315f4bb5f283ad6748a3f8a465ff3e \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 619f07342c315f4bb5f283ad6748a3f8a465ff3e \
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/netdisco__netdisco-1685/instruction.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the github-actions-dependencies group with 2 updates
4
+
5
+ ## Description
6
+
7
+ Bumps the github-actions-dependencies group with 2 updates: [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) and [docker/bake-action](https://github.com/docker/bake-action).
8
+
9
+ Updates `docker/setup-buildx-action` from 4.3.0 to 4.4.0
10
+ <details>
11
+ <summary>Release notes</summary>
12
+ <p><em>Sourced from <a href="https://github.com/docker/setup-buildx-action/releases">docker/setup-buildx-action's releases</a>.</em></p>
13
+ <blockquote>
14
+ <h2>v4.4.0</h2>
15
+ <ul>
16
+ <li>Use official Buildx releases for cloud driver by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#606</a></li>
17
+ <li>Pull BuildKit image before builder creation by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#609</a></li>
18
+ <li>Use shared error helpers for Buildx and Docker commands by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#620</a></li>
19
+ <li>Bump <code>@​docker/actions-toolkit</code> from 0.95.0 to 0.100.0 in <a href="">docker/setup-buildx-action#610</a> <a href="">docker/setup-buildx-action#618</a> <a href="">docker/setup-buildx-action#619</a></li>
20
+ <li>Bump <code>@​humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="">docker/setup-buildx-action#614</a></li>
21
+ <li>Bump js-yaml from 5.3.0 to 5.4.2 in <a href="">docker/setup-buildx-action#608</a> <a href="">docker/setup-buildx-action#617</a></li>
22
+ <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="">docker/setup-buildx-action#611</a></li>
23
+ </ul>
24
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0">https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0</a></p>
25
+ </blockquote>
26
+ </details>
27
+ <details>
28
+ <summary>Commits</summary>
29
+ <ul>
30
+ <li><a href=""><code>594f3bf</code></a> Merge pull request <a href="">#609</a> from crazy-max/pull-buildkit-image-before-create</li>
31
+ <li><a href=""><code>bd6e702</code></a> chore: update generated content</li>
32
+ <li><a href=""><code>6268c9d</code></a> pull BuildKit image before builder creation</li>
33
+ <li><a href=""><code>e823525</code></a> Merge pull request <a href="">#621</a> from docker/dependabot/github_actions/codeql-actions-...</li>
34
+ <li><a href=""><code>533ed8e</code></a> build(deps): bump the codeql-actions group with 2 updates</li>
35
+ <li><a href=""><code>bedaf13</code></a> Merge pull request <a href="">#620</a> from crazy-max/shared-error-helpers</li>
36
+ <li><a href=""><code>d5079fb</code></a> chore: update generated content</li>
37
+ <li><a href=""><code>226a616</code></a> use shared error helpers for Buildx and Docker commands</li>
38
+ <li><a href=""><code>77ce7f4</code></a> Merge pull request <a href="">#619</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
39
+ <li><a href=""><code>0dc1dc9</code></a> [dependabot skip] chore: update generated content</li>
40
+ <li>Additional commits viewable in <a href="https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0">compare view</a></li>
41
+ </ul>
42
+ </details>
43
+ <br />
44
+
45
+ Updates `docker/bake-action` from 7.3.0 to 7.4.0
46
+ <details>
47
+ <summary>Release notes</summary>
48
+ <p><em>Sourced from <a href="https://github.com/docker/bake-action/releases">docker/bake-action's releases</a>.</em></p>
49
+ <blockquote>
50
+ <h2>v7.4.0</h2>
51
+ <ul>
52
+ <li>Use the shared error helper for Buildx commands by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/bake-action#511</a></li>
53
+ <li>Prevent workflow command injection in metadata logs by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/bake-action#509</a></li>
54
+ <li>Bump <code>@​docker/actions-toolkit</code> from 0.92.0 to 0.100.0 in <a href="">docker/bake-action#502</a> <a href="">docker/bake-action#510</a> <a href="">docker/bake-action#513</a></li>
55
+ <li>Bump <code>@​humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="">docker/bake-action#498</a></li>
56
+ <li>Bump brace-expansion from 1.1.13 to 1.1.18 in <a href="">docker/bake-action#491</a></li>
57
+ <li>Bump csv-parse from 7.0.0 to 7.0.2 in <a href="">docker/bake-action#500</a></li>
58
+ <li>Bump js-yaml from 4.3.0 to 4.3.2 in <a href="">docker/bake-action#496</a> <a href="">docker/bake-action#508</a></li>
59
+ <li>Bump nanoid from 3.3.16 to 3.3.18 in <a href="">docker/bake-action#499</a></li>
60
+ <li>Bump postcss from 8.5.10 to 8.5.25 in <a href="">docker/bake-action#489</a></li>
61
+ <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="">docker/bake-action#497</a></li>
62
+ <li>Bump sigstore from 4.1.0 to 4.1.1 in <a href="">docker/bake-action#476</a></li>
63
+ <li>Bump undici from 6.27.0 to 6.28.1 in <a href="">docker/bake-action#492</a></li>
64
+ </ul>
65
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0">https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0</a></p>
66
+ </blockquote>
67
+ </details>
68
+ <details>
69
+ <summary>Commits</summary>
70
+ <ul>
71
+ <li><a href=""><code>018cb64</code></a> Merge pull request <a href="">#512</a> from docker/dependabot/github_actions/codeql-actions-...</li>
72
+ <li><a href=""><code>68e5dfc</code></a> Merge pull request <a href="">#513</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
73
+ <li><a href=""><code>67548ed</code></a> chore(deps): Bump the codeql-actions group across 1 directory with 2 updates</li>
74
+ <li><a href=""><code>ad1760d</code></a> [dependabot skip] chore: update generated content</li>
75
+ <li><a href=""><code>a2262a0</code></a> chore(deps): Bump <code>@​docker/actions-toolkit</code> from 0.99.0 to 0.100.0</li>
76
+ <li><a href=""><code>e04a701</code></a> Merge pull request <a href="">#511</a> from crazy-max/buildx-error-message</li>
77
+ <li><a href=""><code>0b5e3e4</code></a> chore: update generated content</li>
78
+ <li><a href=""><code>b0aab10</code></a> use the shared Buildx error summary helper</li>
79
+ <li><a href=""><code>c86773a</code></a> Merge pull request <a href="">#510</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
80
+ <li><a href=""><code>70f5dd8</code></a> [dependabot skip] chore: update generated content</li>
81
+ <li>Additional commits viewable in <a href="https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0">compare view</a></li>
82
+ </ul>
83
+ </details>
84
+ <br />
85
+
86
+ Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
87
+
88
+ [//]: # (dependabot-automerge-start)
89
+ [//]: # (dependabot-automerge-end)
90
+
91
+ ---
92
+
93
+ <details>
94
+ <summary>Dependabot commands and options</summary>
95
+ <br />
96
+
97
+ You can trigger Dependabot actions by commenting on this PR:
98
+ - `@dependabot rebase` will rebase this PR
99
+ - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
100
+ - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
101
+ - `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
102
+ - `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
103
+ - `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
104
+ - `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency
105
+ - `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions
106
+
107
+ </details>
108
+
109
+ ## Task
110
+
111
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `619f07342c31`. 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/netdisco__netdisco-1685/solution/patch.diff ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.github/workflows/build-and-publish.yml b/.github/workflows/build-and-publish.yml
2
+ index 69f7c104..3ce1f10e 100644
3
+ --- a/.github/workflows/build-and-publish.yml
4
+ +++ b/.github/workflows/build-and-publish.yml
5
+ @@ -161,7 +161,7 @@ jobs:
6
+ echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_ENV
7
+
8
+ - name: Set up Docker Buildx
9
+ - uses: docker/setup-buildx-action@v4.3.0
10
+ + uses: docker/setup-buildx-action@v4.4.0
11
+
12
+ - name: Create staging area
13
+ run: |
14
+ @@ -169,7 +169,7 @@ jobs:
15
+ mkdir -p /tmp/transport-stage-${{ matrix.arch }}
16
+
17
+ - name: Build images with Bake and Cache
18
+ - uses: docker/bake-action@v7.3.0
19
+ + uses: docker/bake-action@v7.4.0
20
+ env:
21
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
22
+ COMMITTISH: ${{ env.COMMITTISH }}
tasks/netdisco__netdisco-1685/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/netdisco__netdisco-1685/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/netdisco__netdisco-1685"
5
+ description = "Bump the github-actions-dependencies group with 2 updates"
6
+
7
+ [metadata]
8
+ difficulty = "easy"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "netdisco",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "netdisco/netdisco"
19
+ ref = "619f07342c315f4bb5f283ad6748a3f8a465ff3e"
20
+ reference = "https://github.com/netdisco/netdisco/pull/1685"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:58.514495+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:bd7f85a1cd90e646c5b38bc6e3300ace11ccbf9396505872b9fc101d71659fbd"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-09-18T08:18:05Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ ".github/workflows/build-and-publish.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:01.774023+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:697fa98dc3f2f2e0fa865613c083f8dd272b49a0475f7db9465136cade6abe07"
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/netdisco__netdisco-1685/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/netdisco__netdisco-1685/tests/instruction.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the github-actions-dependencies group with 2 updates
4
+
5
+ ## Description
6
+
7
+ Bumps the github-actions-dependencies group with 2 updates: [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) and [docker/bake-action](https://github.com/docker/bake-action).
8
+
9
+ Updates `docker/setup-buildx-action` from 4.3.0 to 4.4.0
10
+ <details>
11
+ <summary>Release notes</summary>
12
+ <p><em>Sourced from <a href="https://github.com/docker/setup-buildx-action/releases">docker/setup-buildx-action's releases</a>.</em></p>
13
+ <blockquote>
14
+ <h2>v4.4.0</h2>
15
+ <ul>
16
+ <li>Use official Buildx releases for cloud driver by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#606</a></li>
17
+ <li>Pull BuildKit image before builder creation by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#609</a></li>
18
+ <li>Use shared error helpers for Buildx and Docker commands by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/setup-buildx-action#620</a></li>
19
+ <li>Bump <code>@​docker/actions-toolkit</code> from 0.95.0 to 0.100.0 in <a href="">docker/setup-buildx-action#610</a> <a href="">docker/setup-buildx-action#618</a> <a href="">docker/setup-buildx-action#619</a></li>
20
+ <li>Bump <code>@​humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="">docker/setup-buildx-action#614</a></li>
21
+ <li>Bump js-yaml from 5.3.0 to 5.4.2 in <a href="">docker/setup-buildx-action#608</a> <a href="">docker/setup-buildx-action#617</a></li>
22
+ <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="">docker/setup-buildx-action#611</a></li>
23
+ </ul>
24
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0">https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0</a></p>
25
+ </blockquote>
26
+ </details>
27
+ <details>
28
+ <summary>Commits</summary>
29
+ <ul>
30
+ <li><a href=""><code>594f3bf</code></a> Merge pull request <a href="">#609</a> from crazy-max/pull-buildkit-image-before-create</li>
31
+ <li><a href=""><code>bd6e702</code></a> chore: update generated content</li>
32
+ <li><a href=""><code>6268c9d</code></a> pull BuildKit image before builder creation</li>
33
+ <li><a href=""><code>e823525</code></a> Merge pull request <a href="">#621</a> from docker/dependabot/github_actions/codeql-actions-...</li>
34
+ <li><a href=""><code>533ed8e</code></a> build(deps): bump the codeql-actions group with 2 updates</li>
35
+ <li><a href=""><code>bedaf13</code></a> Merge pull request <a href="">#620</a> from crazy-max/shared-error-helpers</li>
36
+ <li><a href=""><code>d5079fb</code></a> chore: update generated content</li>
37
+ <li><a href=""><code>226a616</code></a> use shared error helpers for Buildx and Docker commands</li>
38
+ <li><a href=""><code>77ce7f4</code></a> Merge pull request <a href="">#619</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
39
+ <li><a href=""><code>0dc1dc9</code></a> [dependabot skip] chore: update generated content</li>
40
+ <li>Additional commits viewable in <a href="https://github.com/docker/setup-buildx-action/compare/v4.3.0...v4.4.0">compare view</a></li>
41
+ </ul>
42
+ </details>
43
+ <br />
44
+
45
+ Updates `docker/bake-action` from 7.3.0 to 7.4.0
46
+ <details>
47
+ <summary>Release notes</summary>
48
+ <p><em>Sourced from <a href="https://github.com/docker/bake-action/releases">docker/bake-action's releases</a>.</em></p>
49
+ <blockquote>
50
+ <h2>v7.4.0</h2>
51
+ <ul>
52
+ <li>Use the shared error helper for Buildx commands by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/bake-action#511</a></li>
53
+ <li>Prevent workflow command injection in metadata logs by <a href="https://github.com/crazy-max"><code>@​crazy-max</code></a> in <a href="">docker/bake-action#509</a></li>
54
+ <li>Bump <code>@​docker/actions-toolkit</code> from 0.92.0 to 0.100.0 in <a href="">docker/bake-action#502</a> <a href="">docker/bake-action#510</a> <a href="">docker/bake-action#513</a></li>
55
+ <li>Bump <code>@​humanfs/node</code> from 0.16.7 to 0.16.8 in <a href="">docker/bake-action#498</a></li>
56
+ <li>Bump brace-expansion from 1.1.13 to 1.1.18 in <a href="">docker/bake-action#491</a></li>
57
+ <li>Bump csv-parse from 7.0.0 to 7.0.2 in <a href="">docker/bake-action#500</a></li>
58
+ <li>Bump js-yaml from 4.3.0 to 4.3.2 in <a href="">docker/bake-action#496</a> <a href="">docker/bake-action#508</a></li>
59
+ <li>Bump nanoid from 3.3.16 to 3.3.18 in <a href="">docker/bake-action#499</a></li>
60
+ <li>Bump postcss from 8.5.10 to 8.5.25 in <a href="">docker/bake-action#489</a></li>
61
+ <li>Bump postcss-selector-parser from 7.1.1 to 7.1.5 in <a href="">docker/bake-action#497</a></li>
62
+ <li>Bump sigstore from 4.1.0 to 4.1.1 in <a href="">docker/bake-action#476</a></li>
63
+ <li>Bump undici from 6.27.0 to 6.28.1 in <a href="">docker/bake-action#492</a></li>
64
+ </ul>
65
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0">https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0</a></p>
66
+ </blockquote>
67
+ </details>
68
+ <details>
69
+ <summary>Commits</summary>
70
+ <ul>
71
+ <li><a href=""><code>018cb64</code></a> Merge pull request <a href="">#512</a> from docker/dependabot/github_actions/codeql-actions-...</li>
72
+ <li><a href=""><code>68e5dfc</code></a> Merge pull request <a href="">#513</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
73
+ <li><a href=""><code>67548ed</code></a> chore(deps): Bump the codeql-actions group across 1 directory with 2 updates</li>
74
+ <li><a href=""><code>ad1760d</code></a> [dependabot skip] chore: update generated content</li>
75
+ <li><a href=""><code>a2262a0</code></a> chore(deps): Bump <code>@​docker/actions-toolkit</code> from 0.99.0 to 0.100.0</li>
76
+ <li><a href=""><code>e04a701</code></a> Merge pull request <a href="">#511</a> from crazy-max/buildx-error-message</li>
77
+ <li><a href=""><code>0b5e3e4</code></a> chore: update generated content</li>
78
+ <li><a href=""><code>b0aab10</code></a> use the shared Buildx error summary helper</li>
79
+ <li><a href=""><code>c86773a</code></a> Merge pull request <a href="">#510</a> from docker/dependabot/npm_and_yarn/docker/actions-to...</li>
80
+ <li><a href=""><code>70f5dd8</code></a> [dependabot skip] chore: update generated content</li>
81
+ <li>Additional commits viewable in <a href="https://github.com/docker/bake-action/compare/v7.3.0...v7.4.0">compare view</a></li>
82
+ </ul>
83
+ </details>
84
+ <br />
85
+
86
+ Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
87
+
88
+ [//]: # (dependabot-automerge-start)
89
+ [//]: # (dependabot-automerge-end)
90
+
91
+ ---
92
+
93
+ <details>
94
+ <summary>Dependabot commands and options</summary>
95
+ <br />
96
+
97
+ You can trigger Dependabot actions by commenting on this PR:
98
+ - `@dependabot rebase` will rebase this PR
99
+ - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
100
+ - `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
101
+ - `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
102
+ - `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
103
+ - `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
104
+ - `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency
105
+ - `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions
106
+
107
+ </details>
108
+
109
+ ## Task
110
+
111
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `619f07342c31`. 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/netdisco__netdisco-1685/tests/oracle.patch ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.github/workflows/build-and-publish.yml b/.github/workflows/build-and-publish.yml
2
+ index 69f7c104..3ce1f10e 100644
3
+ --- a/.github/workflows/build-and-publish.yml
4
+ +++ b/.github/workflows/build-and-publish.yml
5
+ @@ -161,7 +161,7 @@ jobs:
6
+ echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_ENV
7
+
8
+ - name: Set up Docker Buildx
9
+ - uses: docker/setup-buildx-action@v4.3.0
10
+ + uses: docker/setup-buildx-action@v4.4.0
11
+
12
+ - name: Create staging area
13
+ run: |
14
+ @@ -169,7 +169,7 @@ jobs:
15
+ mkdir -p /tmp/transport-stage-${{ matrix.arch }}
16
+
17
+ - name: Build images with Bake and Cache
18
+ - uses: docker/bake-action@v7.3.0
19
+ + uses: docker/bake-action@v7.4.0
20
+ env:
21
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
22
+ COMMITTISH: ${{ env.COMMITTISH }}
tasks/netdisco__netdisco-1685/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 619f07342c315f4bb5f283ad6748a3f8a465ff3e > "$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/netdisco__netdisco-1685/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/netdisco__netdisco-1686/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/netdisco/netdisco.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/netdisco/netdisco.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/netdisco/netdisco.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin d412d93b3f3d1f85f3feb87f7077dc83cb148402 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard d412d93b3f3d1f85f3feb87f7077dc83cb148402 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base d412d93b3f3d1f85f3feb87f7077dc83cb148402 \
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/netdisco__netdisco-1686/instruction.md ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the python-dependencies group in /share/python/netdisco with 4 updates
4
+
5
+ ## Description
6
+
7
+ Updates the requirements on [virtualenv](https://github.com/pypa/virtualenv), [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy), [uv-build](https://github.com/astral-sh/uv) and [ruff](https://github.com/astral-sh/ruff) to permit the latest version.
8
+ Updates `virtualenv` to 21.7.14
9
+ <details>
10
+ <summary>Release notes</summary>
11
+ <p><em>Sourced from <a href="https://github.com/pypa/virtualenv/releases">virtualenv's releases</a>.</em></p>
12
+ <blockquote>
13
+ <h2>21.7.14</h2>
14
+ <!-- raw HTML omitted -->
15
+ <h2>What's Changed</h2>
16
+ <ul>
17
+ <li>🐛 fix(activation): escape ! for csh history expansion by <a href="https://github.com/gaborbernat"><code>@​gaborbernat</code></a> in <a href="">pypa/virtualenv#3256</a></li>
18
+ </ul>
19
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/pypa/virtualenv/compare/21.7.13...21.7.14">https://github.com/pypa/virtualenv/compare/21.7.13...21.7.14</a></p>
20
+ </blockquote>
21
+ </details>
22
+ <details>
23
+ <summary>Changelog</summary>
24
+ <p><em>Sourced from <a href="https://github.com/pypa/virtualenv/blob/main/docs/changelog.rst">virtualenv's changelog</a>.</em></p>
25
+ <blockquote>
26
+ <h1>Bugfixes - 21.7.14</h1>
27
+ <ul>
28
+ <li>Fix <code>activate.csh</code> failing with <code>Event not found</code> when the virtual environment path contains <code>!</code>.
29
+ (:issue:<code>3256</code>)</li>
30
+ </ul>
31
+ <hr />
32
+ <p>v21.7.13 (2026-09-18)</p>
33
+ <hr />
34
+ <h1>Bugfixes - 21.7.13</h1>
35
+ <ul>
36
+ <li>Fix <code>activate</code> and <code>activate.fish</code> running commands embedded in the virtual environment path or in the
37
+ interpreter's Tcl/Tk library paths. (:issue:<code>3252</code>)</li>
38
+ </ul>
39
+ <hr />
40
+ <p>v21.7.12 (2026-09-18)</p>
41
+ <hr />
42
+ <h1>Bugfixes - 21.7.12</h1>
43
+ <ul>
44
+ <li>Fix <code>activate.bat</code> running arbitrary commands from a crafted <code>--prompt</code>, <code>VIRTUALENV_PROMPT</code>, or config file
45
+ value. (:issue:<code>3250</code>)</li>
46
+ <li>Verify a downloaded seed wheel's sha256 against PyPI before seeding it into a virtual environment, skipped when a
47
+ custom pip index is configured. (:issue:<code>3251</code>)</li>
48
+ </ul>
49
+ <hr />
50
+ <p>v21.7.11 (2026-09-17)</p>
51
+ <hr />
52
+ <h1>Bugfixes - 21.7.11</h1>
53
+ <ul>
54
+ <li>Running <code>activate.bat</code> again before <code>deactivate</code> no longer makes <code>deactivate</code> leave the environment's
55
+ <code>PKG_CONFIG_PATH</code>, <code>TCL_LIBRARY</code> and <code>TK_LIBRARY</code> behind, or lose values the user had set before the first
56
+ activation - by :user:<code>darrenhuai</code>. (:issue:<code>3245</code>)</li>
57
+ <li>Write <code>pyvenv.cfg</code> values on a single line, so a prompt carrying a line boundary can no longer inject configuration.
58
+ <code>--prompt</code>, the <code>VIRTUALENV_PROMPT</code> environment variable and the config file all set the prompt, and
59
+ <code>pyvenv.cfg</code> has no escape syntax, so a newline, a carriage return, or any other boundary <code>str.splitlines</code>
60
+ recognizes, such as <code>U+2028</code>, started a new configuration line. Reading the file back picked up those lines as keys,
61
+ and since the last value for a key wins, they replaced anything written earlier, including <code>home</code>. (:issue:<code>3247</code>)</li>
62
+ </ul>
63
+ <h1>Improved Documentation - 21.7.11</h1>
64
+ <ul>
65
+ <li>Document the policy for AI-assisted contributions and the licensing rules for dependencies. (:issue:<code>3239</code>)</li>
66
+ </ul>
67
+ <p>Misc - 21.7.11</p>
68
+ <!-- raw HTML omitted -->
69
+ </blockquote>
70
+ <p>... (truncated)</p>
71
+ </details>
72
+ <details>
73
+ <summary>Commits</summary>
74
+ <ul>
75
+ <li><a href=""><code>9baea3c</code></a> release 21.7.14</li>
76
+ <li><a href=""><code>ab3dcff</code></a> 🐛 fix(activation): escape ! for csh history expansion (<a href="">#3256</a>)</li>
77
+ <li><a href=""><code>0c295ff</code></a> release 21.7.13</li>
78
+ <li><a href=""><code>4d5a105</code></a> 🐛 fix(activation): stop path command injection in bash and fish (<a href="">#3252</a>)</li>
79
+ <li><a href=""><code>0525dce</code></a> 👷 ci: scope the nushell apt key to its own repo (<a href="">#3253</a>)</li>
80
+ <li><a href=""><code>aa8323a</code></a> 🔧 chore: drop misc as a changelog fragment type (<a href="">#3255</a>)</li>
81
+ <li><a href=""><code>a435477</code></a> 👷 ci: correct a stale checkout pin comment (<a href="">#3254</a>)</li>
82
+ <li><a href=""><code>9666b42</code></a> release 21.7.12</li>
83
+ <li><a href=""><code>a01ed3e</code></a> 🐛 fix(seed): verify downloaded wheel digests (<a href="">#3251</a>)</li>
84
+ <li><a href=""><code>d721ff1</code></a> 🐛 fix(activation): escape batch quote() against injection (<a href="">#3250</a>)</li>
85
+ <li>Additional commits viewable in <a href="https://github.com/pypa/virtualenv/compare/21.7.9...21.7.14">compare view</a></li>
86
+ </ul>
87
+ </details>
88
+ <br />
89
+
90
+ Updates `sqlalchemy` to 2.0.54
91
+ <details>
92
+ <summary>Release notes</summary>
93
+ <p><em>Sourced from <a href="https://github.com/sqlalchemy/sqlalchemy/releases">sqlalchemy's releases</a>.</em></p>
94
+ <blockquote>
95
+ <h1>2.0.54</h1>
96
+ <p>Released: September 15, 2026</p>
97
+ <h2>platform</h2>
98
+ <ul>
99
+ <li>
100
+ <p><strong>[platform] [change]</strong> Binary wheels are no longer built for Python 3.7. PyPI now rejects wheel
101
+ files whose filename does not begin with the normalized project name, and
102
+ the packaging tools that can be installed on Python 3.7 do not produce
103
+ such a filename. As a result, SQLAlchemy 2.0.44 was the last release to
104
+ publish Python 3.7 wheels to PyPI, and releases 2.0.45 and later have
105
+ been available on Python 3.7 only as a source distribution; the wheel
106
+ builds for Python 3.7 are now removed. Python 3.7 remains supported by
107
+ the 2.0 series.</p>
108
+ </li>
109
+ <li>
110
+ <p><strong>[platform] [bug]</strong> Fixed issue where the Cython extensions were compiled without the
111
+ <code>freethreading_compatible</code> directive, so that they did not declare
112
+ themselves as safe to run without the GIL. On a free-threaded Python
113
+ interpreter such as Python 3.13t or 3.14t, importing SQLAlchemy would
114
+ cause the interpreter to re-enable the GIL, emitting a
115
+ <code>RuntimeWarning</code>. The directive is now set when building for Python
116
+ 3.13 and above, and a test has been added which confirms that importing
117
+ SQLAlchemy on a free-threaded build does not enable the GIL.</p>
118
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13592">#13592</a></p>
119
+ </li>
120
+ </ul>
121
+ </blockquote>
122
+ </details>
123
+ <details>
124
+ <summary>Commits</summary>
125
+ <ul>
126
+ <li>See full diff in <a href="https://github.com/sqlalchemy/sqlalchemy/commits">compare view</a></li>
127
+ </ul>
128
+ </details>
129
+ <br />
130
+
131
+ Updates `uv-build` to 0.12.16
132
+ <details>
133
+ <summary>Release notes</summary>
134
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/releases">uv-build's releases</a>.</em></p>
135
+ <blockquote>
136
+ <h2>0.12.16</h2>
137
+ <h2>Release Notes</h2>
138
+ <p>Released on 2026-09-17.</p>
139
+ <h3>Python</h3>
140
+ <ul>
141
+ <li>Add Pyodide 314.0.7, 0.29.5, and 0.27.8 (<a href="">#21741</a>)</li>
142
+ </ul>
143
+ <h3>Enhancements</h3>
144
+ <ul>
145
+ <li>Verify downloaded wheels and source distributions against hashes supplied by package indexes (<a href="">#21562</a>)</li>
146
+ <li>Allow <code>build-constraint-dependencies</code> entries to include hashes for verifying downloaded build dependencies (<a href="">#21467</a>)</li>
147
+ <li>Honor Darwin <code>platform_release</code> markers in <code>required-environments</code> using macOS wheel deployment targets (<a href="">#21766</a>)</li>
148
+ <li>Reject unsupported Git URL schemes while parsing lockfiles instead of panicking during frozen exports (<a href="">#21779</a>)</li>
149
+ </ul>
150
+ <h3>Preview features</h3>
151
+ <ul>
152
+ <li>Support <code>lock-without-metadata</code> across all dependency types while retaining <code>package.metadata</code> for remote URL dependencies to enable offline validation (<a href="">#21163</a>)</li>
153
+ <li>Honor configured and command-line index settings, including credentials, in <code>uv upgrade</code> (<a href="">#21776</a>)</li>
154
+ <li>Allow <code>uv check</code> to run in projects that are not managed by uv and outside workspaces (<a href="">#21777</a>)</li>
155
+ <li>Respect <code>--python</code> and <code>UV_PYTHON</code> when selecting the Python version for <code>uv check</code> (<a href="">#21744</a>)</li>
156
+ </ul>
157
+ <h3>Bug fixes</h3>
158
+ <ul>
159
+ <li>Redact Azure shared access signatures from displayed and logged URLs (<a href="">#21755</a>)</li>
160
+ <li>Check archive sizes from <code>pylock.toml</code> before reusing cached distributions (<a href="">#21609</a>)</li>
161
+ <li>Keep user-authored local dependency paths relative in lockfiles when backend metadata reports absolute paths (<a href="">#20631</a>)</li>
162
+ <li>Use the bundled <code>uv_build</code> backend only when its version matches active version pins (<a href="">#21742</a>)</li>
163
+ <li>Handle malformed index URLs without panicking when credentials are configured (<a href="">#21784</a>)</li>
164
+ <li>Report a configuration error instead of panicking for proxy URLs without a host (<a href="">#21781</a>)</li>
165
+ <li>Return a credential-redacted error instead of panicking when a URL cannot be converted to a path (<a href="">#21783</a>)</li>
166
+ </ul>
167
+ <h2>Install uv 0.12.16</h2>
168
+ <h3>Install prebuilt binaries via shell script</h3>
169
+ <pre lang="sh"><code>curl --proto '=https' --tlsv1.2 -LsSf https://releases.astral.sh/github/uv/releases/download/0.12.16/uv-installer.sh | sh
170
+ </code></pre>
171
+ <h3>Install prebuilt binaries via powershell script</h3>
172
+ <pre lang="sh"><code>powershell -ExecutionPolicy Bypass -c &quot;irm https://releases.astral.sh/github/uv/releases/download/0.12.16/uv-installer.ps1 | iex&quot;
173
+ </code></pre>
174
+ <h2>Download uv 0.12.16</h2>
175
+ <p>| File | Platform | Checksum |</p>
176
+ <!-- raw HTML omitted -->
177
+ </blockquote>
178
+ <p>... (truncated)</p>
179
+ </details>
180
+ <details>
181
+ <summary>Changelog</summary>
182
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/blob/main/CHANGELOG.md">uv-build's changelog</a>.</em></p>
183
+ <blockquote>
184
+ <h2>0.12.16</h2>
185
+ <p>Released on 2026-09-17.</p>
186
+ <h3>Python</h3>
187
+ <ul>
188
+ <li>Add Pyodide 314.0.7, 0.29.5, and 0.27.8 (<a href="">#21741</a>)</li>
189
+ </ul>
190
+ <h3>Enhancements</h3>
191
+ <ul>
192
+ <li>Verify downloaded wheels and source distributions against has
193
+
194
+ ## Task
195
+
196
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d412d93b3f3d`. 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/netdisco__netdisco-1686/solution/patch.diff ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/share/python/netdisco/pyproject.toml b/share/python/netdisco/pyproject.toml
2
+ index 7985b896..6748bfe2 100644
3
+ --- a/share/python/netdisco/pyproject.toml
4
+ +++ b/share/python/netdisco/pyproject.toml
5
+ @@ -9,22 +9,22 @@ dependencies = [
6
+ "yamale>=6.1.0,<7",
7
+ "netmiko>=4.7.0,<5",
8
+ "cryptography>=50.0.1,<51",
9
+ - "virtualenv>=21.7.9",
10
+ - "sqlalchemy>=2.0.53,<3",
11
+ + "virtualenv>=21.7.14",
12
+ + "sqlalchemy>=2.0.54,<3",
13
+ "psycopg>=3.3.5,<4",
14
+ - "uv-build>=0.12.14,<0.13.0",
15
+ + "uv-build>=0.12.16,<0.13.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ run_worklet = "netdisco.runner:main"
20
+
21
+ [build-system]
22
+ -requires = ["uv_build>=0.12.14,<0.13.0"]
23
+ +requires = ["uv_build>=0.12.16,<0.13.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [dependency-groups]
27
+ develop = ["pre-commit>=4.6.2,<5"]
28
+ -test = ["ruff>=0.16.7,<0.17"]
29
+ +test = ["ruff>=0.16.8,<0.17"]
30
+
31
+ [tool.uv]
32
+ default-groups = [
tasks/netdisco__netdisco-1686/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/netdisco__netdisco-1686/task.toml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/netdisco__netdisco-1686"
5
+ description = "Bump the python-dependencies group in /share/python/netdisco with 4 updates"
6
+
7
+ [metadata]
8
+ difficulty = "small"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "netdisco",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "netdisco/netdisco"
19
+ ref = "d412d93b3f3d1f85f3feb87f7077dc83cb148402"
20
+ reference = "https://github.com/netdisco/netdisco/pull/1686"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:58.511041+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:3479287fd43872b8df5d6c84572577669d2e46090b3d7ffe82f789da3848783c"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-09-21T08:19:03Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "share/python/netdisco/pyproject.toml",
34
+ ]
35
+ bootstrap_image = "python:3.12-slim"
36
+
37
+ [metadata.repo2env.reward_calibration]
38
+ baseline_reward = 0.0
39
+ loc_changed = 10
40
+ difficulty = "small"
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:01.774519+00:00"
59
+ pushed_by = "scalingX"
60
+ inline_recipe_sha256 = "sha256:5b06d273ef7ebfda1cec47eb2719c048e441c68caa4b27ba369ee0ab9450fb5b"
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/netdisco__netdisco-1686/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/netdisco__netdisco-1686/tests/instruction.md ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Bump the python-dependencies group in /share/python/netdisco with 4 updates
4
+
5
+ ## Description
6
+
7
+ Updates the requirements on [virtualenv](https://github.com/pypa/virtualenv), [sqlalchemy](https://github.com/sqlalchemy/sqlalchemy), [uv-build](https://github.com/astral-sh/uv) and [ruff](https://github.com/astral-sh/ruff) to permit the latest version.
8
+ Updates `virtualenv` to 21.7.14
9
+ <details>
10
+ <summary>Release notes</summary>
11
+ <p><em>Sourced from <a href="https://github.com/pypa/virtualenv/releases">virtualenv's releases</a>.</em></p>
12
+ <blockquote>
13
+ <h2>21.7.14</h2>
14
+ <!-- raw HTML omitted -->
15
+ <h2>What's Changed</h2>
16
+ <ul>
17
+ <li>🐛 fix(activation): escape ! for csh history expansion by <a href="https://github.com/gaborbernat"><code>@​gaborbernat</code></a> in <a href="">pypa/virtualenv#3256</a></li>
18
+ </ul>
19
+ <p><strong>Full Changelog</strong>: <a href="https://github.com/pypa/virtualenv/compare/21.7.13...21.7.14">https://github.com/pypa/virtualenv/compare/21.7.13...21.7.14</a></p>
20
+ </blockquote>
21
+ </details>
22
+ <details>
23
+ <summary>Changelog</summary>
24
+ <p><em>Sourced from <a href="https://github.com/pypa/virtualenv/blob/main/docs/changelog.rst">virtualenv's changelog</a>.</em></p>
25
+ <blockquote>
26
+ <h1>Bugfixes - 21.7.14</h1>
27
+ <ul>
28
+ <li>Fix <code>activate.csh</code> failing with <code>Event not found</code> when the virtual environment path contains <code>!</code>.
29
+ (:issue:<code>3256</code>)</li>
30
+ </ul>
31
+ <hr />
32
+ <p>v21.7.13 (2026-09-18)</p>
33
+ <hr />
34
+ <h1>Bugfixes - 21.7.13</h1>
35
+ <ul>
36
+ <li>Fix <code>activate</code> and <code>activate.fish</code> running commands embedded in the virtual environment path or in the
37
+ interpreter's Tcl/Tk library paths. (:issue:<code>3252</code>)</li>
38
+ </ul>
39
+ <hr />
40
+ <p>v21.7.12 (2026-09-18)</p>
41
+ <hr />
42
+ <h1>Bugfixes - 21.7.12</h1>
43
+ <ul>
44
+ <li>Fix <code>activate.bat</code> running arbitrary commands from a crafted <code>--prompt</code>, <code>VIRTUALENV_PROMPT</code>, or config file
45
+ value. (:issue:<code>3250</code>)</li>
46
+ <li>Verify a downloaded seed wheel's sha256 against PyPI before seeding it into a virtual environment, skipped when a
47
+ custom pip index is configured. (:issue:<code>3251</code>)</li>
48
+ </ul>
49
+ <hr />
50
+ <p>v21.7.11 (2026-09-17)</p>
51
+ <hr />
52
+ <h1>Bugfixes - 21.7.11</h1>
53
+ <ul>
54
+ <li>Running <code>activate.bat</code> again before <code>deactivate</code> no longer makes <code>deactivate</code> leave the environment's
55
+ <code>PKG_CONFIG_PATH</code>, <code>TCL_LIBRARY</code> and <code>TK_LIBRARY</code> behind, or lose values the user had set before the first
56
+ activation - by :user:<code>darrenhuai</code>. (:issue:<code>3245</code>)</li>
57
+ <li>Write <code>pyvenv.cfg</code> values on a single line, so a prompt carrying a line boundary can no longer inject configuration.
58
+ <code>--prompt</code>, the <code>VIRTUALENV_PROMPT</code> environment variable and the config file all set the prompt, and
59
+ <code>pyvenv.cfg</code> has no escape syntax, so a newline, a carriage return, or any other boundary <code>str.splitlines</code>
60
+ recognizes, such as <code>U+2028</code>, started a new configuration line. Reading the file back picked up those lines as keys,
61
+ and since the last value for a key wins, they replaced anything written earlier, including <code>home</code>. (:issue:<code>3247</code>)</li>
62
+ </ul>
63
+ <h1>Improved Documentation - 21.7.11</h1>
64
+ <ul>
65
+ <li>Document the policy for AI-assisted contributions and the licensing rules for dependencies. (:issue:<code>3239</code>)</li>
66
+ </ul>
67
+ <p>Misc - 21.7.11</p>
68
+ <!-- raw HTML omitted -->
69
+ </blockquote>
70
+ <p>... (truncated)</p>
71
+ </details>
72
+ <details>
73
+ <summary>Commits</summary>
74
+ <ul>
75
+ <li><a href=""><code>9baea3c</code></a> release 21.7.14</li>
76
+ <li><a href=""><code>ab3dcff</code></a> 🐛 fix(activation): escape ! for csh history expansion (<a href="">#3256</a>)</li>
77
+ <li><a href=""><code>0c295ff</code></a> release 21.7.13</li>
78
+ <li><a href=""><code>4d5a105</code></a> 🐛 fix(activation): stop path command injection in bash and fish (<a href="">#3252</a>)</li>
79
+ <li><a href=""><code>0525dce</code></a> 👷 ci: scope the nushell apt key to its own repo (<a href="">#3253</a>)</li>
80
+ <li><a href=""><code>aa8323a</code></a> 🔧 chore: drop misc as a changelog fragment type (<a href="">#3255</a>)</li>
81
+ <li><a href=""><code>a435477</code></a> 👷 ci: correct a stale checkout pin comment (<a href="">#3254</a>)</li>
82
+ <li><a href=""><code>9666b42</code></a> release 21.7.12</li>
83
+ <li><a href=""><code>a01ed3e</code></a> 🐛 fix(seed): verify downloaded wheel digests (<a href="">#3251</a>)</li>
84
+ <li><a href=""><code>d721ff1</code></a> 🐛 fix(activation): escape batch quote() against injection (<a href="">#3250</a>)</li>
85
+ <li>Additional commits viewable in <a href="https://github.com/pypa/virtualenv/compare/21.7.9...21.7.14">compare view</a></li>
86
+ </ul>
87
+ </details>
88
+ <br />
89
+
90
+ Updates `sqlalchemy` to 2.0.54
91
+ <details>
92
+ <summary>Release notes</summary>
93
+ <p><em>Sourced from <a href="https://github.com/sqlalchemy/sqlalchemy/releases">sqlalchemy's releases</a>.</em></p>
94
+ <blockquote>
95
+ <h1>2.0.54</h1>
96
+ <p>Released: September 15, 2026</p>
97
+ <h2>platform</h2>
98
+ <ul>
99
+ <li>
100
+ <p><strong>[platform] [change]</strong> Binary wheels are no longer built for Python 3.7. PyPI now rejects wheel
101
+ files whose filename does not begin with the normalized project name, and
102
+ the packaging tools that can be installed on Python 3.7 do not produce
103
+ such a filename. As a result, SQLAlchemy 2.0.44 was the last release to
104
+ publish Python 3.7 wheels to PyPI, and releases 2.0.45 and later have
105
+ been available on Python 3.7 only as a source distribution; the wheel
106
+ builds for Python 3.7 are now removed. Python 3.7 remains supported by
107
+ the 2.0 series.</p>
108
+ </li>
109
+ <li>
110
+ <p><strong>[platform] [bug]</strong> Fixed issue where the Cython extensions were compiled without the
111
+ <code>freethreading_compatible</code> directive, so that they did not declare
112
+ themselves as safe to run without the GIL. On a free-threaded Python
113
+ interpreter such as Python 3.13t or 3.14t, importing SQLAlchemy would
114
+ cause the interpreter to re-enable the GIL, emitting a
115
+ <code>RuntimeWarning</code>. The directive is now set when building for Python
116
+ 3.13 and above, and a test has been added which confirms that importing
117
+ SQLAlchemy on a free-threaded build does not enable the GIL.</p>
118
+ <p>References: <a href="https://www.sqlalchemy.org/trac/ticket/13592">#13592</a></p>
119
+ </li>
120
+ </ul>
121
+ </blockquote>
122
+ </details>
123
+ <details>
124
+ <summary>Commits</summary>
125
+ <ul>
126
+ <li>See full diff in <a href="https://github.com/sqlalchemy/sqlalchemy/commits">compare view</a></li>
127
+ </ul>
128
+ </details>
129
+ <br />
130
+
131
+ Updates `uv-build` to 0.12.16
132
+ <details>
133
+ <summary>Release notes</summary>
134
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/releases">uv-build's releases</a>.</em></p>
135
+ <blockquote>
136
+ <h2>0.12.16</h2>
137
+ <h2>Release Notes</h2>
138
+ <p>Released on 2026-09-17.</p>
139
+ <h3>Python</h3>
140
+ <ul>
141
+ <li>Add Pyodide 314.0.7, 0.29.5, and 0.27.8 (<a href="">#21741</a>)</li>
142
+ </ul>
143
+ <h3>Enhancements</h3>
144
+ <ul>
145
+ <li>Verify downloaded wheels and source distributions against hashes supplied by package indexes (<a href="">#21562</a>)</li>
146
+ <li>Allow <code>build-constraint-dependencies</code> entries to include hashes for verifying downloaded build dependencies (<a href="">#21467</a>)</li>
147
+ <li>Honor Darwin <code>platform_release</code> markers in <code>required-environments</code> using macOS wheel deployment targets (<a href="">#21766</a>)</li>
148
+ <li>Reject unsupported Git URL schemes while parsing lockfiles instead of panicking during frozen exports (<a href="">#21779</a>)</li>
149
+ </ul>
150
+ <h3>Preview features</h3>
151
+ <ul>
152
+ <li>Support <code>lock-without-metadata</code> across all dependency types while retaining <code>package.metadata</code> for remote URL dependencies to enable offline validation (<a href="">#21163</a>)</li>
153
+ <li>Honor configured and command-line index settings, including credentials, in <code>uv upgrade</code> (<a href="">#21776</a>)</li>
154
+ <li>Allow <code>uv check</code> to run in projects that are not managed by uv and outside workspaces (<a href="">#21777</a>)</li>
155
+ <li>Respect <code>--python</code> and <code>UV_PYTHON</code> when selecting the Python version for <code>uv check</code> (<a href="">#21744</a>)</li>
156
+ </ul>
157
+ <h3>Bug fixes</h3>
158
+ <ul>
159
+ <li>Redact Azure shared access signatures from displayed and logged URLs (<a href="">#21755</a>)</li>
160
+ <li>Check archive sizes from <code>pylock.toml</code> before reusing cached distributions (<a href="">#21609</a>)</li>
161
+ <li>Keep user-authored local dependency paths relative in lockfiles when backend metadata reports absolute paths (<a href="">#20631</a>)</li>
162
+ <li>Use the bundled <code>uv_build</code> backend only when its version matches active version pins (<a href="">#21742</a>)</li>
163
+ <li>Handle malformed index URLs without panicking when credentials are configured (<a href="">#21784</a>)</li>
164
+ <li>Report a configuration error instead of panicking for proxy URLs without a host (<a href="">#21781</a>)</li>
165
+ <li>Return a credential-redacted error instead of panicking when a URL cannot be converted to a path (<a href="">#21783</a>)</li>
166
+ </ul>
167
+ <h2>Install uv 0.12.16</h2>
168
+ <h3>Install prebuilt binaries via shell script</h3>
169
+ <pre lang="sh"><code>curl --proto '=https' --tlsv1.2 -LsSf https://releases.astral.sh/github/uv/releases/download/0.12.16/uv-installer.sh | sh
170
+ </code></pre>
171
+ <h3>Install prebuilt binaries via powershell script</h3>
172
+ <pre lang="sh"><code>powershell -ExecutionPolicy Bypass -c &quot;irm https://releases.astral.sh/github/uv/releases/download/0.12.16/uv-installer.ps1 | iex&quot;
173
+ </code></pre>
174
+ <h2>Download uv 0.12.16</h2>
175
+ <p>| File | Platform | Checksum |</p>
176
+ <!-- raw HTML omitted -->
177
+ </blockquote>
178
+ <p>... (truncated)</p>
179
+ </details>
180
+ <details>
181
+ <summary>Changelog</summary>
182
+ <p><em>Sourced from <a href="https://github.com/astral-sh/uv/blob/main/CHANGELOG.md">uv-build's changelog</a>.</em></p>
183
+ <blockquote>
184
+ <h2>0.12.16</h2>
185
+ <p>Released on 2026-09-17.</p>
186
+ <h3>Python</h3>
187
+ <ul>
188
+ <li>Add Pyodide 314.0.7, 0.29.5, and 0.27.8 (<a href="">#21741</a>)</li>
189
+ </ul>
190
+ <h3>Enhancements</h3>
191
+ <ul>
192
+ <li>Verify downloaded wheels and source distributions against has
193
+
194
+ ## Task
195
+
196
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d412d93b3f3d`. 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/netdisco__netdisco-1686/tests/oracle.patch ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/share/python/netdisco/pyproject.toml b/share/python/netdisco/pyproject.toml
2
+ index 7985b896..6748bfe2 100644
3
+ --- a/share/python/netdisco/pyproject.toml
4
+ +++ b/share/python/netdisco/pyproject.toml
5
+ @@ -9,22 +9,22 @@ dependencies = [
6
+ "yamale>=6.1.0,<7",
7
+ "netmiko>=4.7.0,<5",
8
+ "cryptography>=50.0.1,<51",
9
+ - "virtualenv>=21.7.9",
10
+ - "sqlalchemy>=2.0.53,<3",
11
+ + "virtualenv>=21.7.14",
12
+ + "sqlalchemy>=2.0.54,<3",
13
+ "psycopg>=3.3.5,<4",
14
+ - "uv-build>=0.12.14,<0.13.0",
15
+ + "uv-build>=0.12.16,<0.13.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ run_worklet = "netdisco.runner:main"
20
+
21
+ [build-system]
22
+ -requires = ["uv_build>=0.12.14,<0.13.0"]
23
+ +requires = ["uv_build>=0.12.16,<0.13.0"]
24
+ build-backend = "uv_build"
25
+
26
+ [dependency-groups]
27
+ develop = ["pre-commit>=4.6.2,<5"]
28
+ -test = ["ruff>=0.16.7,<0.17"]
29
+ +test = ["ruff>=0.16.8,<0.17"]
30
+
31
+ [tool.uv]
32
+ default-groups = [