Datasets:
Add 10000 GitHub Trending pr_diff environments (part 104)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/traccar__traccar-6051/tests/test.sh +25 -0
- tasks/traccar__traccar-6051/tests/verifier.py +737 -0
- tasks/traccar__traccar-6054/environment/Dockerfile +37 -0
- tasks/traccar__traccar-6054/instruction.md +28 -0
- tasks/traccar__traccar-6054/solution/patch.diff +30 -0
- tasks/traccar__traccar-6054/solution/solve.sh +6 -0
- tasks/traccar__traccar-6054/task.toml +69 -0
- tasks/traccar__traccar-6054/tests/capture.py +96 -0
- tasks/traccar__traccar-6054/tests/instruction.md +28 -0
- tasks/traccar__traccar-6054/tests/oracle.patch +30 -0
- tasks/traccar__traccar-6054/tests/test.sh +25 -0
- tasks/traccar__traccar-6054/tests/verifier.py +737 -0
- tasks/traccar__traccar-6058/environment/Dockerfile +37 -0
- tasks/traccar__traccar-6058/instruction.md +11 -0
- tasks/traccar__traccar-6058/solution/patch.diff +112 -0
- tasks/traccar__traccar-6058/solution/solve.sh +6 -0
- tasks/traccar__traccar-6058/task.toml +70 -0
- tasks/traccar__traccar-6058/tests/capture.py +96 -0
- tasks/traccar__traccar-6058/tests/instruction.md +11 -0
- tasks/traccar__traccar-6058/tests/oracle.patch +112 -0
- tasks/traccar__traccar-6058/tests/test.sh +25 -0
- tasks/traccar__traccar-6058/tests/verifier.py +737 -0
- tasks/traccar__traccar-6059/environment/Dockerfile +37 -0
- tasks/traccar__traccar-6059/instruction.md +87 -0
- tasks/traccar__traccar-6059/solution/patch.diff +37 -0
- tasks/traccar__traccar-6059/solution/solve.sh +6 -0
- tasks/traccar__traccar-6059/task.toml +68 -0
- tasks/traccar__traccar-6059/tests/capture.py +96 -0
- tasks/traccar__traccar-6059/tests/instruction.md +87 -0
- tasks/traccar__traccar-6059/tests/oracle.patch +37 -0
- tasks/traccar__traccar-6059/tests/test.sh +25 -0
- tasks/traccar__traccar-6059/tests/verifier.py +737 -0
- tasks/traccar__traccar-6060/environment/Dockerfile +37 -0
- tasks/traccar__traccar-6060/instruction.md +21 -0
- tasks/traccar__traccar-6060/solution/patch.diff +23 -0
- tasks/traccar__traccar-6060/solution/solve.sh +6 -0
- tasks/traccar__traccar-6060/task.toml +68 -0
- tasks/traccar__traccar-6060/tests/capture.py +96 -0
- tasks/traccar__traccar-6060/tests/instruction.md +21 -0
- tasks/traccar__traccar-6060/tests/oracle.patch +23 -0
- tasks/traccar__traccar-6060/tests/test.sh +25 -0
- tasks/traccar__traccar-6060/tests/verifier.py +737 -0
- tasks/traccar__traccar-6064/environment/Dockerfile +37 -0
- tasks/traccar__traccar-6064/instruction.md +40 -0
- tasks/traccar__traccar-6064/solution/patch.diff +51 -0
- tasks/traccar__traccar-6064/solution/solve.sh +6 -0
- tasks/traccar__traccar-6064/task.toml +69 -0
- tasks/traccar__traccar-6064/tests/capture.py +96 -0
- tasks/traccar__traccar-6064/tests/instruction.md +40 -0
- tasks/traccar__traccar-6064/tests/oracle.patch +51 -0
tasks/traccar__traccar-6051/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 f9bd485b4a6e576de0c167b8f93651d3a8a64c9e > "$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/traccar__traccar-6051/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/traccar__traccar-6054/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/traccar/traccar.git /workspace; \
|
| 16 |
+
else \
|
| 17 |
+
git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \
|
| 18 |
+
fi \
|
| 19 |
+
&& git -C /workspace remote set-url origin https://github.com/traccar/traccar.git
|
| 20 |
+
WORKDIR /workspace
|
| 21 |
+
RUN git fetch --depth 1 origin 1ea97a3c6828851043786297bd826b7096aa2043 2>/dev/null \
|
| 22 |
+
|| git fetch --unshallow origin 2>/dev/null || true
|
| 23 |
+
RUN git reset --hard 1ea97a3c6828851043786297bd826b7096aa2043 \
|
| 24 |
+
&& git clean -fdx -e .venv -e venv -e __pycache__
|
| 25 |
+
RUN git checkout -q -B base 1ea97a3c6828851043786297bd826b7096aa2043 \
|
| 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/traccar__traccar-6054/instruction.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Fix Xexun3 status-only frame decoding by parsing 0x6A timestamp
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
**Summary**
|
| 8 |
+
|
| 9 |
+
The 0x6A status submessage contains 24 bytes of device status data (battery, RSSI, motion, steps, temperature, heart rate, fuel level), but the decoder only read 16 bytes and ignored the trailing 4-byte timestamp. Without a deviceTime set, the decoder returned null and the entire status frame was silently dropped.
|
| 10 |
+
|
| 11 |
+
We now parse the timestamp from the remaining bytes and call `setDeviceTime` so that status-only frames (without a 0x64 GPS submessage) produce a valid position with `getLastLocation` fallback.
|
| 12 |
+
|
| 13 |
+
The test frame (device-info report) contains no GPS record, so the decoder only set `deviceTime` and left `fixTime` null, which `position().deviceTime(...)` (Checks.ALL) requires. I also added the established Traccar fallback `position.setFixTime(position.getDeviceTime()` (same as Orbcomm/Gps103/Mobilogix) when a data frame has a device timestamp but no fix time.
|
| 14 |
+
|
| 15 |
+
All Xexun3 tests and checkstyle now pass.
|
| 16 |
+
|
| 17 |
+
**Test case added**
|
| 18 |
+
|
| 19 |
+
I added a test case with a fresh captured frame containing no `0x64` but a `0x6A` submessage with timestamp.
|
| 20 |
+
|
| 21 |
+
**Evidence**
|
| 22 |
+
[Xexun API 260921 EN.docx](https://github.com/user-attachments/files/32875152/Xexun.API.260921.EN.docx)
|
| 23 |
+
|
| 24 |
+
-- Cheers, Nils
|
| 25 |
+
|
| 26 |
+
## Task
|
| 27 |
+
|
| 28 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ea97a3c6828`. 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/traccar__traccar-6054/solution/patch.diff
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 2 |
+
index 3475860ce..f73194ca7 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 5 |
+
@@ -199,6 +199,10 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
if (fuel != 0xFF) {
|
| 7 |
+
position.set(Position.KEY_FUEL_LEVEL, fuel);
|
| 8 |
+
}
|
| 9 |
+
+ long deviceTime = buf.readUnsignedInt();
|
| 10 |
+
+ if (deviceTime != 0xFFFFFFFFL) {
|
| 11 |
+
+ position.setDeviceTime(new Date(deviceTime * 1000));
|
| 12 |
+
+ }
|
| 13 |
+
}
|
| 14 |
+
default -> {}
|
| 15 |
+
}
|
| 16 |
+
diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 17 |
+
index 14f5788b7..b086b13ff 100644
|
| 18 |
+
--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 19 |
+
+++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 20 |
+
@@ -21,6 +21,10 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest {
|
| 21 |
+
"fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf"),
|
| 22 |
+
position().location("2026-09-15T11:43:30.000Z", true, 51.37597, 7.14792));
|
| 23 |
+
|
| 24 |
+
+ verifyDecode(decoder, binary(
|
| 25 |
+
+ "fc00d003200108625960809262016a1863001120ff000006daffffff020000ff6abeacda000000006ea91341414132363039323330337c41414132363039323330327c5030320000000000898830300001364674357d4141412c4137363730452d4c4153435f4131323442303241373637304d362c415436353538522d354e2d33322d31433538303930315f5552414e5553352056352e332e322e302c747261636361722e63727970746f6e6f64652e64653a3532363440322c2c3239353035303930383031313338392c2c302c3236323033795acf"),
|
| 26 |
+
+ position(Checks.ATTRIBUTES).deviceTime("2026-10-01T18:56:26.000Z"));
|
| 27 |
+
+
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
tasks/traccar__traccar-6054/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/traccar__traccar-6054/task.toml
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "trending/traccar__traccar-6054"
|
| 5 |
+
description = "Fix Xexun3 status-only frame decoding by parsing 0x6A timestamp"
|
| 6 |
+
|
| 7 |
+
[metadata]
|
| 8 |
+
difficulty = "small"
|
| 9 |
+
category = "bugfix"
|
| 10 |
+
keywords = [
|
| 11 |
+
"traccar",
|
| 12 |
+
"pr_diff",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
[metadata.repo2env]
|
| 16 |
+
pipeline = "pr_diff"
|
| 17 |
+
pipeline_version = "0.3.0"
|
| 18 |
+
repo = "traccar/traccar"
|
| 19 |
+
ref = "1ea97a3c6828851043786297bd826b7096aa2043"
|
| 20 |
+
reference = "https://github.com/traccar/traccar/pull/6054"
|
| 21 |
+
source_access = "auto"
|
| 22 |
+
built_at = "2026-11-16T16:09:42.521637+00:00"
|
| 23 |
+
reward_kinds = [
|
| 24 |
+
"diff_similarity",
|
| 25 |
+
]
|
| 26 |
+
spec_version = "0.2.0"
|
| 27 |
+
content_hash = "sha256:6778b449f80f700f081004900ea1e28415c2da082d2d24e1fe766e92058c83ec"
|
| 28 |
+
|
| 29 |
+
[metadata.repo2env.pr_diff]
|
| 30 |
+
pr_merged_at = "2026-10-03T14:48:21Z"
|
| 31 |
+
diff_format = "unified"
|
| 32 |
+
context_files = [
|
| 33 |
+
"src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java",
|
| 34 |
+
"src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java",
|
| 35 |
+
]
|
| 36 |
+
bootstrap_image = "python:3.12-slim"
|
| 37 |
+
|
| 38 |
+
[metadata.repo2env.reward_calibration]
|
| 39 |
+
baseline_reward = 0.0
|
| 40 |
+
loc_changed = 8
|
| 41 |
+
difficulty = "small"
|
| 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:03.527887+00:00"
|
| 60 |
+
pushed_by = "scalingX"
|
| 61 |
+
inline_recipe_sha256 = "sha256:1c59b0d2a8e6f466983acc9540f2ea1be476bf0891f3309998c28d0cb9170e5f"
|
| 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/traccar__traccar-6054/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/traccar__traccar-6054/tests/instruction.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Fix Xexun3 status-only frame decoding by parsing 0x6A timestamp
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
**Summary**
|
| 8 |
+
|
| 9 |
+
The 0x6A status submessage contains 24 bytes of device status data (battery, RSSI, motion, steps, temperature, heart rate, fuel level), but the decoder only read 16 bytes and ignored the trailing 4-byte timestamp. Without a deviceTime set, the decoder returned null and the entire status frame was silently dropped.
|
| 10 |
+
|
| 11 |
+
We now parse the timestamp from the remaining bytes and call `setDeviceTime` so that status-only frames (without a 0x64 GPS submessage) produce a valid position with `getLastLocation` fallback.
|
| 12 |
+
|
| 13 |
+
The test frame (device-info report) contains no GPS record, so the decoder only set `deviceTime` and left `fixTime` null, which `position().deviceTime(...)` (Checks.ALL) requires. I also added the established Traccar fallback `position.setFixTime(position.getDeviceTime()` (same as Orbcomm/Gps103/Mobilogix) when a data frame has a device timestamp but no fix time.
|
| 14 |
+
|
| 15 |
+
All Xexun3 tests and checkstyle now pass.
|
| 16 |
+
|
| 17 |
+
**Test case added**
|
| 18 |
+
|
| 19 |
+
I added a test case with a fresh captured frame containing no `0x64` but a `0x6A` submessage with timestamp.
|
| 20 |
+
|
| 21 |
+
**Evidence**
|
| 22 |
+
[Xexun API 260921 EN.docx](https://github.com/user-attachments/files/32875152/Xexun.API.260921.EN.docx)
|
| 23 |
+
|
| 24 |
+
-- Cheers, Nils
|
| 25 |
+
|
| 26 |
+
## Task
|
| 27 |
+
|
| 28 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ea97a3c6828`. 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/traccar__traccar-6054/tests/oracle.patch
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 2 |
+
index 3475860ce..f73194ca7 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 5 |
+
@@ -199,6 +199,10 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
if (fuel != 0xFF) {
|
| 7 |
+
position.set(Position.KEY_FUEL_LEVEL, fuel);
|
| 8 |
+
}
|
| 9 |
+
+ long deviceTime = buf.readUnsignedInt();
|
| 10 |
+
+ if (deviceTime != 0xFFFFFFFFL) {
|
| 11 |
+
+ position.setDeviceTime(new Date(deviceTime * 1000));
|
| 12 |
+
+ }
|
| 13 |
+
}
|
| 14 |
+
default -> {}
|
| 15 |
+
}
|
| 16 |
+
diff --git a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 17 |
+
index 14f5788b7..b086b13ff 100644
|
| 18 |
+
--- a/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 19 |
+
+++ b/src/test/java/org/traccar/protocol/Xexun3ProtocolDecoderTest.java
|
| 20 |
+
@@ -21,6 +21,10 @@ public class Xexun3ProtocolDecoderTest extends ProtocolTest {
|
| 21 |
+
"fc00490320e8086259608092620164226aa92f624049b01fff79c842401c97788f16414443084ccd400e19001c009f000e006a18630000173a2f0001a3ffffffffffffff6aa92f622101000030f4cf"),
|
| 22 |
+
position().location("2026-09-15T11:43:30.000Z", true, 51.37597, 7.14792));
|
| 23 |
+
|
| 24 |
+
+ verifyDecode(decoder, binary(
|
| 25 |
+
+ "fc00d003200108625960809262016a1863001120ff000006daffffff020000ff6abeacda000000006ea91341414132363039323330337c41414132363039323330327c5030320000000000898830300001364674357d4141412c4137363730452d4c4153435f4131323442303241373637304d362c415436353538522d354e2d33322d31433538303930315f5552414e5553352056352e332e322e302c747261636361722e63727970746f6e6f64652e64653a3532363440322c2c3239353035303930383031313338392c2c302c3236323033795acf"),
|
| 26 |
+
+ position(Checks.ATTRIBUTES).deviceTime("2026-10-01T18:56:26.000Z"));
|
| 27 |
+
+
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
}
|
tasks/traccar__traccar-6054/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 1ea97a3c6828851043786297bd826b7096aa2043 > "$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/traccar__traccar-6054/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/traccar__traccar-6058/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/traccar/traccar.git /workspace; \
|
| 16 |
+
else \
|
| 17 |
+
git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \
|
| 18 |
+
fi \
|
| 19 |
+
&& git -C /workspace remote set-url origin https://github.com/traccar/traccar.git
|
| 20 |
+
WORKDIR /workspace
|
| 21 |
+
RUN git fetch --depth 1 origin a9f7725f9150ec0ed3f8d4e82ce5c9a56dc09019 2>/dev/null \
|
| 22 |
+
|| git fetch --unshallow origin 2>/dev/null || true
|
| 23 |
+
RUN git reset --hard a9f7725f9150ec0ed3f8d4e82ce5c9a56dc09019 \
|
| 24 |
+
&& git clean -fdx -e .venv -e venv -e __pycache__
|
| 25 |
+
RUN git checkout -q -B base a9f7725f9150ec0ed3f8d4e82ce5c9a56dc09019 \
|
| 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/traccar__traccar-6058/instruction.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Add My Geocode
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Code added for adding MyGeocode (https://www.mygeocode.com) to the available Geocoder APIs.
|
| 8 |
+
|
| 9 |
+
## Task
|
| 10 |
+
|
| 11 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9f7725f9150`. 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/traccar__traccar-6058/solution/patch.diff
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java
|
| 2 |
+
index 12b183d4a..524430e2a 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/MainModule.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/MainModule.java
|
| 5 |
+
@@ -71,6 +71,7 @@ import org.traccar.geocoder.MapQuestGeocoder;
|
| 6 |
+
import org.traccar.geocoder.MapTilerGeocoder;
|
| 7 |
+
import org.traccar.geocoder.MapboxGeocoder;
|
| 8 |
+
import org.traccar.geocoder.MapmyIndiaGeocoder;
|
| 9 |
+
+import org.traccar.geocoder.MyGeocodeGeocoder;
|
| 10 |
+
import org.traccar.geocoder.NominatimGeocoder;
|
| 11 |
+
import org.traccar.geocoder.OpenCageGeocoder;
|
| 12 |
+
import org.traccar.geocoder.PlusCodesGeocoder;
|
| 13 |
+
@@ -258,6 +259,7 @@ public class MainModule extends AbstractModule {
|
| 14 |
+
case "autonavi" -> new AutoNaviGeocoder(client, key, cacheSize, addressFormat);
|
| 15 |
+
case "baidu" -> new BaiduGeocoder(client, key, language, cacheSize, addressFormat);
|
| 16 |
+
case "tencent" -> new TencentGeocoder(client, key, cacheSize, addressFormat);
|
| 17 |
+
+ case "mygeocode" -> new MyGeocodeGeocoder(client, url, key, language, cacheSize, addressFormat);
|
| 18 |
+
default -> new GoogleGeocoder(client, url, key, language, cacheSize, addressFormat);
|
| 19 |
+
};
|
| 20 |
+
geocoder.setStatisticsManager(statisticsManager);
|
| 21 |
+
diff --git a/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java b/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java
|
| 22 |
+
new file mode 100644
|
| 23 |
+
index 000000000..8d440eaf1
|
| 24 |
+
--- /dev/null
|
| 25 |
+
+++ b/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java
|
| 26 |
+
@@ -0,0 +1,69 @@
|
| 27 |
+
+/*
|
| 28 |
+
+ * Copyright 2026 Anton Tananaev (anton@traccar.org)
|
| 29 |
+
+ *
|
| 30 |
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
|
| 31 |
+
+ * you may not use this file except in compliance with the License.
|
| 32 |
+
+ * You may obtain a copy of the License at
|
| 33 |
+
+ *
|
| 34 |
+
+ * http://www.apache.org/licenses/LICENSE-2.0
|
| 35 |
+
+ *
|
| 36 |
+
+ * Unless required by applicable law or agreed to in writing, software
|
| 37 |
+
+ * distributed under the License is distributed on an "AS IS" BASIS,
|
| 38 |
+
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 39 |
+
+ * See the License for the specific language governing permissions and
|
| 40 |
+
+ * limitations under the License.
|
| 41 |
+
+ */
|
| 42 |
+
+package org.traccar.geocoder;
|
| 43 |
+
+
|
| 44 |
+
+import jakarta.json.JsonObject;
|
| 45 |
+
+import jakarta.ws.rs.client.Client;
|
| 46 |
+
+import java.util.Locale;
|
| 47 |
+
+
|
| 48 |
+
+public class MyGeocodeGeocoder extends JsonGeocoder {
|
| 49 |
+
+
|
| 50 |
+
+ private static String formatUrl(String url, String key, String language) {
|
| 51 |
+
+ if (url == null) {
|
| 52 |
+
+ url = "https://api.mygeocode.com/v1/reverse";
|
| 53 |
+
+ }
|
| 54 |
+
+ url += "?lat=%f&lon=%f";
|
| 55 |
+
+ if (key != null && !key.isEmpty()) {
|
| 56 |
+
+ url += "&key=" + key;
|
| 57 |
+
+ }
|
| 58 |
+
+ if (language != null && !language.isEmpty()) {
|
| 59 |
+
+ url += "&lang=" + language;
|
| 60 |
+
+ }
|
| 61 |
+
+ return url;
|
| 62 |
+
+ }
|
| 63 |
+
+
|
| 64 |
+
+ public MyGeocodeGeocoder(
|
| 65 |
+
+ Client client, String url, String key, String language, int cacheSize, AddressFormat addressFormat) {
|
| 66 |
+
+ super(client, formatUrl(url, key, language), cacheSize, addressFormat);
|
| 67 |
+
+ }
|
| 68 |
+
+
|
| 69 |
+
+ @Override
|
| 70 |
+
+ public Address parseAddress(JsonObject json) {
|
| 71 |
+
+ JsonObject result = readObject(json, "result");
|
| 72 |
+
+ if (result == null) {
|
| 73 |
+
+ return null;
|
| 74 |
+
+ }
|
| 75 |
+
+ Address address = new Address();
|
| 76 |
+
+ address.setFormattedAddress(readValue(result, "formatted"));
|
| 77 |
+
+
|
| 78 |
+
+ JsonObject components = readObject(result, "components");
|
| 79 |
+
+ if (components != null) {
|
| 80 |
+
+ address.setHouse(readValue(components, "house_number"));
|
| 81 |
+
+ address.setStreet(readValue(components, "road"));
|
| 82 |
+
+ address.setSuburb(readValue(components, "suburb"));
|
| 83 |
+
+ address.setSettlement(readValue(components, "city"));
|
| 84 |
+
+ address.setDistrict(readValue(components, "county"));
|
| 85 |
+
+ address.setState(readValue(components, "state"));
|
| 86 |
+
+ address.setPostcode(readValue(components, "postcode"));
|
| 87 |
+
+ String countryCode = readValue(components, "country_code");
|
| 88 |
+
+ if (countryCode != null) {
|
| 89 |
+
+ address.setCountry(countryCode.toUpperCase(Locale.ROOT));
|
| 90 |
+
+ }
|
| 91 |
+
+ }
|
| 92 |
+
+ return address;
|
| 93 |
+
+ }
|
| 94 |
+
+
|
| 95 |
+
+}
|
| 96 |
+
diff --git a/src/test/java/org/traccar/geocoder/GeocoderTest.java b/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 97 |
+
index d2c5e2ff8..b62e1c86f 100644
|
| 98 |
+
--- a/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 99 |
+
+++ b/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 100 |
+
@@ -153,4 +153,12 @@ public class GeocoderTest {
|
| 101 |
+
String address = geocoder.getAddress(22.944354, 113.375930, null);
|
| 102 |
+
assertEquals("东荟创新园 云山大街, 广州市, 广东省, 中国", address);
|
| 103 |
+
}
|
| 104 |
+
+
|
| 105 |
+
+ @Disabled
|
| 106 |
+
+ @Test
|
| 107 |
+
+ public void testMyGeocode() {
|
| 108 |
+
+ Geocoder geocoder = new MyGeocodeGeocoder(client, null, null, null, 0, new AddressFormat());
|
| 109 |
+
+ String address = geocoder.getAddress(40.733, -73.989, null);
|
| 110 |
+
+ assertEquals("118 E 13th St, New York, New York, US", address);
|
| 111 |
+
+ }
|
| 112 |
+
}
|
tasks/traccar__traccar-6058/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/traccar__traccar-6058/task.toml
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "trending/traccar__traccar-6058"
|
| 5 |
+
description = "Add My Geocode"
|
| 6 |
+
|
| 7 |
+
[metadata]
|
| 8 |
+
difficulty = "medium"
|
| 9 |
+
category = "bugfix"
|
| 10 |
+
keywords = [
|
| 11 |
+
"traccar",
|
| 12 |
+
"pr_diff",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
[metadata.repo2env]
|
| 16 |
+
pipeline = "pr_diff"
|
| 17 |
+
pipeline_version = "0.3.0"
|
| 18 |
+
repo = "traccar/traccar"
|
| 19 |
+
ref = "a9f7725f9150ec0ed3f8d4e82ce5c9a56dc09019"
|
| 20 |
+
reference = "https://github.com/traccar/traccar/pull/6058"
|
| 21 |
+
source_access = "auto"
|
| 22 |
+
built_at = "2026-11-16T16:09:42.520161+00:00"
|
| 23 |
+
reward_kinds = [
|
| 24 |
+
"diff_similarity",
|
| 25 |
+
]
|
| 26 |
+
spec_version = "0.2.0"
|
| 27 |
+
content_hash = "sha256:258dbe75110660417e58dff8b11e2f8732b6df13b93acb170596481714cb85b5"
|
| 28 |
+
|
| 29 |
+
[metadata.repo2env.pr_diff]
|
| 30 |
+
pr_merged_at = "2026-10-06T00:40:32Z"
|
| 31 |
+
diff_format = "unified"
|
| 32 |
+
context_files = [
|
| 33 |
+
"src/main/java/org/traccar/MainModule.java",
|
| 34 |
+
"src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java",
|
| 35 |
+
"src/test/java/org/traccar/geocoder/GeocoderTest.java",
|
| 36 |
+
]
|
| 37 |
+
bootstrap_image = "python:3.12-slim"
|
| 38 |
+
|
| 39 |
+
[metadata.repo2env.reward_calibration]
|
| 40 |
+
baseline_reward = 0.0
|
| 41 |
+
loc_changed = 79
|
| 42 |
+
difficulty = "medium"
|
| 43 |
+
|
| 44 |
+
[metadata.repo2env.evaluation]
|
| 45 |
+
schema_version = "1"
|
| 46 |
+
status = "unverified"
|
| 47 |
+
stage = "generation"
|
| 48 |
+
reason_codes = [
|
| 49 |
+
"validation_not_run",
|
| 50 |
+
]
|
| 51 |
+
detail = "Generated task; validation has not been established."
|
| 52 |
+
provenance = "unknown"
|
| 53 |
+
evidence = []
|
| 54 |
+
|
| 55 |
+
[metadata.repo2env.reproducibility]
|
| 56 |
+
mode = "inline_dockerfile"
|
| 57 |
+
image_ref = "python:3.12-slim"
|
| 58 |
+
image_tag = "python:3.12-slim"
|
| 59 |
+
image_visibility = "public"
|
| 60 |
+
pushed_at = "2026-11-16T16:20:03.528432+00:00"
|
| 61 |
+
pushed_by = "scalingX"
|
| 62 |
+
inline_recipe_sha256 = "sha256:edb7914c06c0b47c96d2e74e501f2812a2ee5de5ce6abdaa3afd87632ecd91ef"
|
| 63 |
+
inline_recipe_lines = 37
|
| 64 |
+
inline_recipe_source = "user_dockerfile"
|
| 65 |
+
|
| 66 |
+
[agent]
|
| 67 |
+
timeout_sec = 1800.0
|
| 68 |
+
|
| 69 |
+
[verifier]
|
| 70 |
+
timeout_sec = 300.0
|
tasks/traccar__traccar-6058/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/traccar__traccar-6058/tests/instruction.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Add My Geocode
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Code added for adding MyGeocode (https://www.mygeocode.com) to the available Geocoder APIs.
|
| 8 |
+
|
| 9 |
+
## Task
|
| 10 |
+
|
| 11 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9f7725f9150`. 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/traccar__traccar-6058/tests/oracle.patch
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java
|
| 2 |
+
index 12b183d4a..524430e2a 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/MainModule.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/MainModule.java
|
| 5 |
+
@@ -71,6 +71,7 @@ import org.traccar.geocoder.MapQuestGeocoder;
|
| 6 |
+
import org.traccar.geocoder.MapTilerGeocoder;
|
| 7 |
+
import org.traccar.geocoder.MapboxGeocoder;
|
| 8 |
+
import org.traccar.geocoder.MapmyIndiaGeocoder;
|
| 9 |
+
+import org.traccar.geocoder.MyGeocodeGeocoder;
|
| 10 |
+
import org.traccar.geocoder.NominatimGeocoder;
|
| 11 |
+
import org.traccar.geocoder.OpenCageGeocoder;
|
| 12 |
+
import org.traccar.geocoder.PlusCodesGeocoder;
|
| 13 |
+
@@ -258,6 +259,7 @@ public class MainModule extends AbstractModule {
|
| 14 |
+
case "autonavi" -> new AutoNaviGeocoder(client, key, cacheSize, addressFormat);
|
| 15 |
+
case "baidu" -> new BaiduGeocoder(client, key, language, cacheSize, addressFormat);
|
| 16 |
+
case "tencent" -> new TencentGeocoder(client, key, cacheSize, addressFormat);
|
| 17 |
+
+ case "mygeocode" -> new MyGeocodeGeocoder(client, url, key, language, cacheSize, addressFormat);
|
| 18 |
+
default -> new GoogleGeocoder(client, url, key, language, cacheSize, addressFormat);
|
| 19 |
+
};
|
| 20 |
+
geocoder.setStatisticsManager(statisticsManager);
|
| 21 |
+
diff --git a/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java b/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java
|
| 22 |
+
new file mode 100644
|
| 23 |
+
index 000000000..8d440eaf1
|
| 24 |
+
--- /dev/null
|
| 25 |
+
+++ b/src/main/java/org/traccar/geocoder/MyGeocodeGeocoder.java
|
| 26 |
+
@@ -0,0 +1,69 @@
|
| 27 |
+
+/*
|
| 28 |
+
+ * Copyright 2026 Anton Tananaev (anton@traccar.org)
|
| 29 |
+
+ *
|
| 30 |
+
+ * Licensed under the Apache License, Version 2.0 (the "License");
|
| 31 |
+
+ * you may not use this file except in compliance with the License.
|
| 32 |
+
+ * You may obtain a copy of the License at
|
| 33 |
+
+ *
|
| 34 |
+
+ * http://www.apache.org/licenses/LICENSE-2.0
|
| 35 |
+
+ *
|
| 36 |
+
+ * Unless required by applicable law or agreed to in writing, software
|
| 37 |
+
+ * distributed under the License is distributed on an "AS IS" BASIS,
|
| 38 |
+
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 39 |
+
+ * See the License for the specific language governing permissions and
|
| 40 |
+
+ * limitations under the License.
|
| 41 |
+
+ */
|
| 42 |
+
+package org.traccar.geocoder;
|
| 43 |
+
+
|
| 44 |
+
+import jakarta.json.JsonObject;
|
| 45 |
+
+import jakarta.ws.rs.client.Client;
|
| 46 |
+
+import java.util.Locale;
|
| 47 |
+
+
|
| 48 |
+
+public class MyGeocodeGeocoder extends JsonGeocoder {
|
| 49 |
+
+
|
| 50 |
+
+ private static String formatUrl(String url, String key, String language) {
|
| 51 |
+
+ if (url == null) {
|
| 52 |
+
+ url = "https://api.mygeocode.com/v1/reverse";
|
| 53 |
+
+ }
|
| 54 |
+
+ url += "?lat=%f&lon=%f";
|
| 55 |
+
+ if (key != null && !key.isEmpty()) {
|
| 56 |
+
+ url += "&key=" + key;
|
| 57 |
+
+ }
|
| 58 |
+
+ if (language != null && !language.isEmpty()) {
|
| 59 |
+
+ url += "&lang=" + language;
|
| 60 |
+
+ }
|
| 61 |
+
+ return url;
|
| 62 |
+
+ }
|
| 63 |
+
+
|
| 64 |
+
+ public MyGeocodeGeocoder(
|
| 65 |
+
+ Client client, String url, String key, String language, int cacheSize, AddressFormat addressFormat) {
|
| 66 |
+
+ super(client, formatUrl(url, key, language), cacheSize, addressFormat);
|
| 67 |
+
+ }
|
| 68 |
+
+
|
| 69 |
+
+ @Override
|
| 70 |
+
+ public Address parseAddress(JsonObject json) {
|
| 71 |
+
+ JsonObject result = readObject(json, "result");
|
| 72 |
+
+ if (result == null) {
|
| 73 |
+
+ return null;
|
| 74 |
+
+ }
|
| 75 |
+
+ Address address = new Address();
|
| 76 |
+
+ address.setFormattedAddress(readValue(result, "formatted"));
|
| 77 |
+
+
|
| 78 |
+
+ JsonObject components = readObject(result, "components");
|
| 79 |
+
+ if (components != null) {
|
| 80 |
+
+ address.setHouse(readValue(components, "house_number"));
|
| 81 |
+
+ address.setStreet(readValue(components, "road"));
|
| 82 |
+
+ address.setSuburb(readValue(components, "suburb"));
|
| 83 |
+
+ address.setSettlement(readValue(components, "city"));
|
| 84 |
+
+ address.setDistrict(readValue(components, "county"));
|
| 85 |
+
+ address.setState(readValue(components, "state"));
|
| 86 |
+
+ address.setPostcode(readValue(components, "postcode"));
|
| 87 |
+
+ String countryCode = readValue(components, "country_code");
|
| 88 |
+
+ if (countryCode != null) {
|
| 89 |
+
+ address.setCountry(countryCode.toUpperCase(Locale.ROOT));
|
| 90 |
+
+ }
|
| 91 |
+
+ }
|
| 92 |
+
+ return address;
|
| 93 |
+
+ }
|
| 94 |
+
+
|
| 95 |
+
+}
|
| 96 |
+
diff --git a/src/test/java/org/traccar/geocoder/GeocoderTest.java b/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 97 |
+
index d2c5e2ff8..b62e1c86f 100644
|
| 98 |
+
--- a/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 99 |
+
+++ b/src/test/java/org/traccar/geocoder/GeocoderTest.java
|
| 100 |
+
@@ -153,4 +153,12 @@ public class GeocoderTest {
|
| 101 |
+
String address = geocoder.getAddress(22.944354, 113.375930, null);
|
| 102 |
+
assertEquals("东荟创新园 云山大街, 广州市, 广东省, 中国", address);
|
| 103 |
+
}
|
| 104 |
+
+
|
| 105 |
+
+ @Disabled
|
| 106 |
+
+ @Test
|
| 107 |
+
+ public void testMyGeocode() {
|
| 108 |
+
+ Geocoder geocoder = new MyGeocodeGeocoder(client, null, null, null, 0, new AddressFormat());
|
| 109 |
+
+ String address = geocoder.getAddress(40.733, -73.989, null);
|
| 110 |
+
+ assertEquals("118 E 13th St, New York, New York, US", address);
|
| 111 |
+
+ }
|
| 112 |
+
}
|
tasks/traccar__traccar-6058/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 a9f7725f9150ec0ed3f8d4e82ce5c9a56dc09019 > "$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/traccar__traccar-6058/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/traccar__traccar-6059/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/traccar/traccar.git /workspace; \
|
| 16 |
+
else \
|
| 17 |
+
git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \
|
| 18 |
+
fi \
|
| 19 |
+
&& git -C /workspace remote set-url origin https://github.com/traccar/traccar.git
|
| 20 |
+
WORKDIR /workspace
|
| 21 |
+
RUN git fetch --depth 1 origin d0c0ac7bea6ee752ee091fef6a6c3f794ae4d2bf 2>/dev/null \
|
| 22 |
+
|| git fetch --unshallow origin 2>/dev/null || true
|
| 23 |
+
RUN git reset --hard d0c0ac7bea6ee752ee091fef6a6c3f794ae4d2bf \
|
| 24 |
+
&& git clean -fdx -e .venv -e venv -e __pycache__
|
| 25 |
+
RUN git checkout -q -B base d0c0ac7bea6ee752ee091fef6a6c3f794ae4d2bf \
|
| 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/traccar__traccar-6059/instruction.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Fix `0x20` packet response format in Xexun3 protocol
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
**Summary**
|
| 8 |
+
|
| 9 |
+
This fixes `0x20` packet response format in Xexun3 protocol decoder.
|
| 10 |
+
The PR corrects the behavior of the response to an Xexun3 terminal data packet with message type 0x20.
|
| 11 |
+
|
| 12 |
+
The technical basis for this is Xexun API 260921 EN.
|
| 13 |
+
[Xexun API 260921 EN.docx](https://github.com/user-attachments/files/33027914/Xexun.API.260921.EN.docx)
|
| 14 |
+
|
| 15 |
+
**Problem**
|
| 16 |
+
|
| 17 |
+
The terminal regularly sends 0x20-type heartbeat/data packets. The server responds to these, after which the terminal reports a disconnection after approximately 80 seconds and reconnects. The terminal does not accept the current server response as a complete or valid acknowledgment.
|
| 18 |
+
|
| 19 |
+
**Log Evidence**
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
2026-10-04 14:57:24 INFO: [T50218945: xexun3 < 185.57.216.190] fc000e0320f608625960809262016b0101d5a2cf
|
| 23 |
+
2026-10-04 14:57:24 INFO: [T50218945: xexun3 > 185.57.216.190] fc000c0320f608625960809262010019a9cf
|
| 24 |
+
2026-10-04 14:57:24 INFO: Event id: 862596080926201, time: 2026-10-04 14:57:24, type: deviceOnline, notifications: 0
|
| 25 |
+
|
| 26 |
+
... ~ 80 seconds ...
|
| 27 |
+
|
| 28 |
+
2026-10-04 14:58:45 INFO: Event id: 862596080926201, time: 2026-10-04 14:58:45, type: deviceOffline, notifications: 0
|
| 29 |
+
|
| 30 |
+
... device re-connects:
|
| 31 |
+
2026-10-04 14:58:45 INFO: [Ta3104673: xexun3 < 185.57.216.190] fc000e0320f708625960809262016b0101d6d7cf
|
| 32 |
+
|
| 33 |
+
... incorrect server response
|
| 34 |
+
2026-10-04 14:58:45 INFO: [Ta3104673: xexun3 > 185.57.216.190] fc000c0320f708625960809262010076eccf
|
| 35 |
+
2026-10-04 14:58:45 INFO: Event id: 862596080926201, time: 2026-10-04 14:58:45, type: deviceOnline, notifications: 0
|
| 36 |
+
|
| 37 |
+
... ~ 80 seconds ...
|
| 38 |
+
|
| 39 |
+
... device dis-connects:
|
| 40 |
+
2026-10-04 15:00:06 INFO: Event id: 862596080926201, time: 2026-10-04 15:00:06, type: deviceOffline, notifications: 0
|
| 41 |
+
|
| 42 |
+
... device re-connects:
|
| 43 |
+
2026-10-04 15:00:06 INFO: [Tb4f576b4: xexun3 < 185.57.216.190] fc000e0320f808625960809262016b0101c534cf
|
| 44 |
+
|
| 45 |
+
... and so on ...
|
| 46 |
+
2026-10-04 15:00:06 INFO: [Tb4f576b4: xexun3 > 185.57.216.190] fc000c0320f8086259608092620100205dcf
|
| 47 |
+
2026-10-04 15:00:06 INFO: Event id: 862596080926201, time: 2026-10-04 15:00:06, type: deviceOnline, notifications: 0
|
| 48 |
+
|
| 49 |
+
2026-10-04 15:01:27 INFO: Event id: 862596080926201, time: 2026-10-04 15:01:27, type: deviceOffline, notifications: 0
|
| 50 |
+
2026-10-04 15:01:28 INFO: [Tbe45d11d: xexun3 < 185.57.216.190] fc000e0320f908625960809262016b0101c641cf
|
| 51 |
+
2026-10-04 15:01:28 INFO: [Tbe45d11d: xexun3 > 185.57.216.190] fc000c0320f90862596080926201004f18cf
|
| 52 |
+
2026-10-04 15:01:28 INFO: Event id: 862596080926201, time: 2026-10-04 15:01:28, type: deviceOnline, notifications: 0
|
| 53 |
+
|
| 54 |
+
2026-10-04 15:02:49 INFO: Event id: 862596080926201, time: 2026-10-04 15:02:49, type: deviceOffline, notifications: 0
|
| 55 |
+
2026-10-04 15:02:49 INFO: [Tbfc4289f: xexun3 < 185.57.216.190] fc000e0320fc08625960809262016b0101c8e0cf
|
| 56 |
+
2026-10-04 15:02:49 INFO: [Tbfc4289f: xexun3 > 185.57.216.190] fc000c0320fc0862596080926201008d68cf
|
| 57 |
+
2026-10-04 15:02:49 INFO: Event id: 862596080926201, time: 2026-10-04 15:02:49, type: deviceOnline, notifications: 0
|
| 58 |
+
|
| 59 |
+
2026-10-04 15:04:10 INFO: Event id: 862596080926201, time: 2026-10-04 15:04:10, type: deviceOffline, notifications: 0
|
| 60 |
+
2026-10-04 15:04:10 INFO: [T309a1392: xexun3 < 185.57.216.190] fc000e0320fd08625960809262016b0101cb95cf
|
| 61 |
+
2026-10-04 15:04:10 INFO: [T309a1392: xexun3 > 185.57.216.190] fc000c0320fd086259608092620100e22dcf
|
| 62 |
+
2026-10-04 15:04:10 INFO: Event id: 862596080926201, time: 2026-10-04 15:04:10, type: deviceOnline, notifications: 0
|
| 63 |
+
|
| 64 |
+
2026-10-04 15:05:31 INFO: Event id: 862596080926201, time: 2026-10-04 15:05:31, type: deviceOffline, notifications: 0
|
| 65 |
+
2026-10-04 15:05:32 INFO: [T982db761: xexun3 < 185.57.216.190] fc000e0320fe08625960809262016b0101ce0acf
|
| 66 |
+
2026-10-04 15:05:32 INFO: [T982db761: xexun3 > 185.57.216.190] fc000c0320fe08625960809262010053e2cf
|
| 67 |
+
2026-10-04 15:05:32 INFO: Event id: 862596080926201, time: 2026-10-04 15:05:32, type: deviceOnline, notifications: 0
|
| 68 |
+
|
| 69 |
+
2026-10-04 15:06:53 INFO: Event id: 862596080926201, time: 2026-10-04 15:06:53, type: deviceOffline, notifications: 0
|
| 70 |
+
2026-10-04 15:06:54 INFO: [T764d9279: xexun3 < 185.57.216.190] fc000e0320ff08625960809262016b0101cd7fcf
|
| 71 |
+
2026-10-04 15:06:54 INFO: [T764d9279: xexun3 > 185.57.216.190] fc000c0320ff0862596080926201003ca7cf
|
| 72 |
+
2026-10-04 15:06:54 INFO: Event id: 862596080926201, time: 2026-10-04 15:06:54, type: deviceOnline, notifications: 0
|
| 73 |
+
|
| 74 |
+
2026-10-04 15:08:15 INFO: Event id: 862596080926201, time: 2026-10-04 15:08:15, type: deviceOffline, notifications: 0
|
| 75 |
+
2026-10-04 15:08:15 INFO: [Taa89b29c: xexun3 < 185.57.216.190] fc000e03200008625960809262016b0101f08dcf
|
| 76 |
+
2026-10-04 15:08:15 INFO: [Taa89b29c: xexun3 > 185.57.216.190] fc000c03200008625960809262010051a3cf
|
| 77 |
+
2026-10-04 15:08:15 INFO: Event id: 862596080926201, time: 2026-10-04 15:08:15, type: deviceOnline, notifications: 0
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
I didn't add or change any tests because I couldn't find an option to test the response.
|
| 82 |
+
|
| 83 |
+
-- Cheers, Nils
|
| 84 |
+
|
| 85 |
+
## Task
|
| 86 |
+
|
| 87 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0c0ac7bea6e`. 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/traccar__traccar-6059/solution/patch.diff
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 2 |
+
index f73194ca7..1eac865ab 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 5 |
+
@@ -46,14 +46,15 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
if (channel != null) {
|
| 7 |
+
ByteBuf response = Unpooled.buffer();
|
| 8 |
+
response.writeByte(0xFC);
|
| 9 |
+
- response.writeShort(12); // length
|
| 10 |
+
+ response.writeShort(16); // length
|
| 11 |
+
response.writeByte(0x03); // version
|
| 12 |
+
response.writeByte(type);
|
| 13 |
+
response.writeByte(index);
|
| 14 |
+
response.writeBytes(imei, imei.readerIndex(), 8);
|
| 15 |
+
response.writeByte(0); // result
|
| 16 |
+
+ response.writeInt((int) (System.currentTimeMillis() / 1000));
|
| 17 |
+
response.writeShort(Checksum.crc16(
|
| 18 |
+
- Checksum.CRC16_CCITT_FALSE, response.nioBuffer(3, 12)));
|
| 19 |
+
+ Checksum.CRC16_CCITT_FALSE, response.nioBuffer(3, 16)));
|
| 20 |
+
response.writeByte(0xCF);
|
| 21 |
+
channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress()));
|
| 22 |
+
}
|
| 23 |
+
@@ -199,9 +200,11 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 24 |
+
if (fuel != 0xFF) {
|
| 25 |
+
position.set(Position.KEY_FUEL_LEVEL, fuel);
|
| 26 |
+
}
|
| 27 |
+
- long deviceTime = buf.readUnsignedInt();
|
| 28 |
+
- if (deviceTime != 0xFFFFFFFFL) {
|
| 29 |
+
- position.setDeviceTime(new Date(deviceTime * 1000));
|
| 30 |
+
+ if (subEnd - buf.readerIndex() >= 4) {
|
| 31 |
+
+ long deviceTime = buf.readUnsignedInt();
|
| 32 |
+
+ if (deviceTime != 0xFFFFFFFFL) {
|
| 33 |
+
+ position.setDeviceTime(new Date(deviceTime * 1000));
|
| 34 |
+
+ }
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
default -> {}
|
tasks/traccar__traccar-6059/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/traccar__traccar-6059/task.toml
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "trending/traccar__traccar-6059"
|
| 5 |
+
description = "Fix `0x20` packet response format in Xexun3 protocol"
|
| 6 |
+
|
| 7 |
+
[metadata]
|
| 8 |
+
difficulty = "small"
|
| 9 |
+
category = "bugfix"
|
| 10 |
+
keywords = [
|
| 11 |
+
"traccar",
|
| 12 |
+
"pr_diff",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
[metadata.repo2env]
|
| 16 |
+
pipeline = "pr_diff"
|
| 17 |
+
pipeline_version = "0.3.0"
|
| 18 |
+
repo = "traccar/traccar"
|
| 19 |
+
ref = "d0c0ac7bea6ee752ee091fef6a6c3f794ae4d2bf"
|
| 20 |
+
reference = "https://github.com/traccar/traccar/pull/6059"
|
| 21 |
+
source_access = "auto"
|
| 22 |
+
built_at = "2026-11-16T16:09:42.518418+00:00"
|
| 23 |
+
reward_kinds = [
|
| 24 |
+
"diff_similarity",
|
| 25 |
+
]
|
| 26 |
+
spec_version = "0.2.0"
|
| 27 |
+
content_hash = "sha256:ca9789085a9721a4e6eadb8c5cd8954b10b77218a00100432ef095e2a86fcb86"
|
| 28 |
+
|
| 29 |
+
[metadata.repo2env.pr_diff]
|
| 30 |
+
pr_merged_at = "2026-10-09T13:56:30Z"
|
| 31 |
+
diff_format = "unified"
|
| 32 |
+
context_files = [
|
| 33 |
+
"src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java",
|
| 34 |
+
]
|
| 35 |
+
bootstrap_image = "python:3.12-slim"
|
| 36 |
+
|
| 37 |
+
[metadata.repo2env.reward_calibration]
|
| 38 |
+
baseline_reward = 0.0
|
| 39 |
+
loc_changed = 13
|
| 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:03.528957+00:00"
|
| 59 |
+
pushed_by = "scalingX"
|
| 60 |
+
inline_recipe_sha256 = "sha256:e2241055e37786666dd148864a5e7f3269cefd566962dbdca91360a8f7b61f94"
|
| 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/traccar__traccar-6059/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/traccar__traccar-6059/tests/instruction.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Fix `0x20` packet response format in Xexun3 protocol
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
**Summary**
|
| 8 |
+
|
| 9 |
+
This fixes `0x20` packet response format in Xexun3 protocol decoder.
|
| 10 |
+
The PR corrects the behavior of the response to an Xexun3 terminal data packet with message type 0x20.
|
| 11 |
+
|
| 12 |
+
The technical basis for this is Xexun API 260921 EN.
|
| 13 |
+
[Xexun API 260921 EN.docx](https://github.com/user-attachments/files/33027914/Xexun.API.260921.EN.docx)
|
| 14 |
+
|
| 15 |
+
**Problem**
|
| 16 |
+
|
| 17 |
+
The terminal regularly sends 0x20-type heartbeat/data packets. The server responds to these, after which the terminal reports a disconnection after approximately 80 seconds and reconnects. The terminal does not accept the current server response as a complete or valid acknowledgment.
|
| 18 |
+
|
| 19 |
+
**Log Evidence**
|
| 20 |
+
|
| 21 |
+
```
|
| 22 |
+
2026-10-04 14:57:24 INFO: [T50218945: xexun3 < 185.57.216.190] fc000e0320f608625960809262016b0101d5a2cf
|
| 23 |
+
2026-10-04 14:57:24 INFO: [T50218945: xexun3 > 185.57.216.190] fc000c0320f608625960809262010019a9cf
|
| 24 |
+
2026-10-04 14:57:24 INFO: Event id: 862596080926201, time: 2026-10-04 14:57:24, type: deviceOnline, notifications: 0
|
| 25 |
+
|
| 26 |
+
... ~ 80 seconds ...
|
| 27 |
+
|
| 28 |
+
2026-10-04 14:58:45 INFO: Event id: 862596080926201, time: 2026-10-04 14:58:45, type: deviceOffline, notifications: 0
|
| 29 |
+
|
| 30 |
+
... device re-connects:
|
| 31 |
+
2026-10-04 14:58:45 INFO: [Ta3104673: xexun3 < 185.57.216.190] fc000e0320f708625960809262016b0101d6d7cf
|
| 32 |
+
|
| 33 |
+
... incorrect server response
|
| 34 |
+
2026-10-04 14:58:45 INFO: [Ta3104673: xexun3 > 185.57.216.190] fc000c0320f708625960809262010076eccf
|
| 35 |
+
2026-10-04 14:58:45 INFO: Event id: 862596080926201, time: 2026-10-04 14:58:45, type: deviceOnline, notifications: 0
|
| 36 |
+
|
| 37 |
+
... ~ 80 seconds ...
|
| 38 |
+
|
| 39 |
+
... device dis-connects:
|
| 40 |
+
2026-10-04 15:00:06 INFO: Event id: 862596080926201, time: 2026-10-04 15:00:06, type: deviceOffline, notifications: 0
|
| 41 |
+
|
| 42 |
+
... device re-connects:
|
| 43 |
+
2026-10-04 15:00:06 INFO: [Tb4f576b4: xexun3 < 185.57.216.190] fc000e0320f808625960809262016b0101c534cf
|
| 44 |
+
|
| 45 |
+
... and so on ...
|
| 46 |
+
2026-10-04 15:00:06 INFO: [Tb4f576b4: xexun3 > 185.57.216.190] fc000c0320f8086259608092620100205dcf
|
| 47 |
+
2026-10-04 15:00:06 INFO: Event id: 862596080926201, time: 2026-10-04 15:00:06, type: deviceOnline, notifications: 0
|
| 48 |
+
|
| 49 |
+
2026-10-04 15:01:27 INFO: Event id: 862596080926201, time: 2026-10-04 15:01:27, type: deviceOffline, notifications: 0
|
| 50 |
+
2026-10-04 15:01:28 INFO: [Tbe45d11d: xexun3 < 185.57.216.190] fc000e0320f908625960809262016b0101c641cf
|
| 51 |
+
2026-10-04 15:01:28 INFO: [Tbe45d11d: xexun3 > 185.57.216.190] fc000c0320f90862596080926201004f18cf
|
| 52 |
+
2026-10-04 15:01:28 INFO: Event id: 862596080926201, time: 2026-10-04 15:01:28, type: deviceOnline, notifications: 0
|
| 53 |
+
|
| 54 |
+
2026-10-04 15:02:49 INFO: Event id: 862596080926201, time: 2026-10-04 15:02:49, type: deviceOffline, notifications: 0
|
| 55 |
+
2026-10-04 15:02:49 INFO: [Tbfc4289f: xexun3 < 185.57.216.190] fc000e0320fc08625960809262016b0101c8e0cf
|
| 56 |
+
2026-10-04 15:02:49 INFO: [Tbfc4289f: xexun3 > 185.57.216.190] fc000c0320fc0862596080926201008d68cf
|
| 57 |
+
2026-10-04 15:02:49 INFO: Event id: 862596080926201, time: 2026-10-04 15:02:49, type: deviceOnline, notifications: 0
|
| 58 |
+
|
| 59 |
+
2026-10-04 15:04:10 INFO: Event id: 862596080926201, time: 2026-10-04 15:04:10, type: deviceOffline, notifications: 0
|
| 60 |
+
2026-10-04 15:04:10 INFO: [T309a1392: xexun3 < 185.57.216.190] fc000e0320fd08625960809262016b0101cb95cf
|
| 61 |
+
2026-10-04 15:04:10 INFO: [T309a1392: xexun3 > 185.57.216.190] fc000c0320fd086259608092620100e22dcf
|
| 62 |
+
2026-10-04 15:04:10 INFO: Event id: 862596080926201, time: 2026-10-04 15:04:10, type: deviceOnline, notifications: 0
|
| 63 |
+
|
| 64 |
+
2026-10-04 15:05:31 INFO: Event id: 862596080926201, time: 2026-10-04 15:05:31, type: deviceOffline, notifications: 0
|
| 65 |
+
2026-10-04 15:05:32 INFO: [T982db761: xexun3 < 185.57.216.190] fc000e0320fe08625960809262016b0101ce0acf
|
| 66 |
+
2026-10-04 15:05:32 INFO: [T982db761: xexun3 > 185.57.216.190] fc000c0320fe08625960809262010053e2cf
|
| 67 |
+
2026-10-04 15:05:32 INFO: Event id: 862596080926201, time: 2026-10-04 15:05:32, type: deviceOnline, notifications: 0
|
| 68 |
+
|
| 69 |
+
2026-10-04 15:06:53 INFO: Event id: 862596080926201, time: 2026-10-04 15:06:53, type: deviceOffline, notifications: 0
|
| 70 |
+
2026-10-04 15:06:54 INFO: [T764d9279: xexun3 < 185.57.216.190] fc000e0320ff08625960809262016b0101cd7fcf
|
| 71 |
+
2026-10-04 15:06:54 INFO: [T764d9279: xexun3 > 185.57.216.190] fc000c0320ff0862596080926201003ca7cf
|
| 72 |
+
2026-10-04 15:06:54 INFO: Event id: 862596080926201, time: 2026-10-04 15:06:54, type: deviceOnline, notifications: 0
|
| 73 |
+
|
| 74 |
+
2026-10-04 15:08:15 INFO: Event id: 862596080926201, time: 2026-10-04 15:08:15, type: deviceOffline, notifications: 0
|
| 75 |
+
2026-10-04 15:08:15 INFO: [Taa89b29c: xexun3 < 185.57.216.190] fc000e03200008625960809262016b0101f08dcf
|
| 76 |
+
2026-10-04 15:08:15 INFO: [Taa89b29c: xexun3 > 185.57.216.190] fc000c03200008625960809262010051a3cf
|
| 77 |
+
2026-10-04 15:08:15 INFO: Event id: 862596080926201, time: 2026-10-04 15:08:15, type: deviceOnline, notifications: 0
|
| 78 |
+
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
I didn't add or change any tests because I couldn't find an option to test the response.
|
| 82 |
+
|
| 83 |
+
-- Cheers, Nils
|
| 84 |
+
|
| 85 |
+
## Task
|
| 86 |
+
|
| 87 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0c0ac7bea6e`. 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/traccar__traccar-6059/tests/oracle.patch
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 2 |
+
index f73194ca7..1eac865ab 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/Xexun3ProtocolDecoder.java
|
| 5 |
+
@@ -46,14 +46,15 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
if (channel != null) {
|
| 7 |
+
ByteBuf response = Unpooled.buffer();
|
| 8 |
+
response.writeByte(0xFC);
|
| 9 |
+
- response.writeShort(12); // length
|
| 10 |
+
+ response.writeShort(16); // length
|
| 11 |
+
response.writeByte(0x03); // version
|
| 12 |
+
response.writeByte(type);
|
| 13 |
+
response.writeByte(index);
|
| 14 |
+
response.writeBytes(imei, imei.readerIndex(), 8);
|
| 15 |
+
response.writeByte(0); // result
|
| 16 |
+
+ response.writeInt((int) (System.currentTimeMillis() / 1000));
|
| 17 |
+
response.writeShort(Checksum.crc16(
|
| 18 |
+
- Checksum.CRC16_CCITT_FALSE, response.nioBuffer(3, 12)));
|
| 19 |
+
+ Checksum.CRC16_CCITT_FALSE, response.nioBuffer(3, 16)));
|
| 20 |
+
response.writeByte(0xCF);
|
| 21 |
+
channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress()));
|
| 22 |
+
}
|
| 23 |
+
@@ -199,9 +200,11 @@ public class Xexun3ProtocolDecoder extends BaseProtocolDecoder {
|
| 24 |
+
if (fuel != 0xFF) {
|
| 25 |
+
position.set(Position.KEY_FUEL_LEVEL, fuel);
|
| 26 |
+
}
|
| 27 |
+
- long deviceTime = buf.readUnsignedInt();
|
| 28 |
+
- if (deviceTime != 0xFFFFFFFFL) {
|
| 29 |
+
- position.setDeviceTime(new Date(deviceTime * 1000));
|
| 30 |
+
+ if (subEnd - buf.readerIndex() >= 4) {
|
| 31 |
+
+ long deviceTime = buf.readUnsignedInt();
|
| 32 |
+
+ if (deviceTime != 0xFFFFFFFFL) {
|
| 33 |
+
+ position.setDeviceTime(new Date(deviceTime * 1000));
|
| 34 |
+
+ }
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
default -> {}
|
tasks/traccar__traccar-6059/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 d0c0ac7bea6ee752ee091fef6a6c3f794ae4d2bf > "$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/traccar__traccar-6059/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/traccar__traccar-6060/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/traccar/traccar.git /workspace; \
|
| 16 |
+
else \
|
| 17 |
+
git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \
|
| 18 |
+
fi \
|
| 19 |
+
&& git -C /workspace remote set-url origin https://github.com/traccar/traccar.git
|
| 20 |
+
WORKDIR /workspace
|
| 21 |
+
RUN git fetch --depth 1 origin bdb7f6335cb4a75ec88fdcdc1a9de063b5497511 2>/dev/null \
|
| 22 |
+
|| git fetch --unshallow origin 2>/dev/null || true
|
| 23 |
+
RUN git reset --hard bdb7f6335cb4a75ec88fdcdc1a9de063b5497511 \
|
| 24 |
+
&& git clean -fdx -e .venv -e venv -e __pycache__
|
| 25 |
+
RUN git checkout -q -B base bdb7f6335cb4a75ec88fdcdc1a9de063b5497511 \
|
| 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/traccar__traccar-6060/instruction.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Reject repeated share of the same object
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Reject repeated share of the same object
|
| 8 |
+
|
| 9 |
+
with the second option from the issue thread.
|
| 10 |
+
|
| 11 |
+
A share creates one temporary user per device or group, and that user keeps the expiration it was created with. A second share request for the same object skipped user creation but still returned a new token. Once the first share expired, that token failed at login with "User has expired".
|
| 12 |
+
|
| 13 |
+
Now the second request returns 409 Conflict with "Already shared", so the client gets an error instead of a token that can't be used. The first share works as before.
|
| 14 |
+
|
| 15 |
+
Added ShareResourceTest with two cases. The first checks that a first share creates the user and returns a token. The second checks that sharing again after the first share expired returns 409 and generates no token. The second case fails without the change.
|
| 16 |
+
|
| 17 |
+
Ran ShareResourceTest plus checkstyleMain and checkstyleTest locally. All pass.
|
| 18 |
+
|
| 19 |
+
## Task
|
| 20 |
+
|
| 21 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bdb7f6335cb4`. 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/traccar__traccar-6060/solution/patch.diff
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/api/resource/ShareResource.java b/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 2 |
+
index 14b352a68..818ecd86b 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 5 |
+
@@ -35,7 +35,9 @@ import jakarta.ws.rs.FormParam;
|
| 6 |
+
import jakarta.ws.rs.POST;
|
| 7 |
+
import jakarta.ws.rs.Path;
|
| 8 |
+
import jakarta.ws.rs.Produces;
|
| 9 |
+
+import jakarta.ws.rs.WebApplicationException;
|
| 10 |
+
import jakarta.ws.rs.core.MediaType;
|
| 11 |
+
+import jakarta.ws.rs.core.Response;
|
| 12 |
+
import java.io.IOException;
|
| 13 |
+
import java.security.GeneralSecurityException;
|
| 14 |
+
import java.util.Date;
|
| 15 |
+
@@ -94,6 +96,8 @@ public class ShareResource extends BaseResource {
|
| 16 |
+
share.setId(storage.addObject(share, new Request(new Columns.Exclude("id"))));
|
| 17 |
+
|
| 18 |
+
storage.addPermission(new Permission(User.class, share.getId(), clazz, id));
|
| 19 |
+
+ } else {
|
| 20 |
+
+ throw new WebApplicationException(Response.Status.CONFLICT);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
return tokenManager.generateToken(share.getId(), expiration);
|
tasks/traccar__traccar-6060/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/traccar__traccar-6060/task.toml
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "trending/traccar__traccar-6060"
|
| 5 |
+
description = "Reject repeated share of the same object"
|
| 6 |
+
|
| 7 |
+
[metadata]
|
| 8 |
+
difficulty = "easy"
|
| 9 |
+
category = "bugfix"
|
| 10 |
+
keywords = [
|
| 11 |
+
"traccar",
|
| 12 |
+
"pr_diff",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
[metadata.repo2env]
|
| 16 |
+
pipeline = "pr_diff"
|
| 17 |
+
pipeline_version = "0.3.0"
|
| 18 |
+
repo = "traccar/traccar"
|
| 19 |
+
ref = "bdb7f6335cb4a75ec88fdcdc1a9de063b5497511"
|
| 20 |
+
reference = "https://github.com/traccar/traccar/pull/6060"
|
| 21 |
+
source_access = "auto"
|
| 22 |
+
built_at = "2026-11-16T16:09:42.516497+00:00"
|
| 23 |
+
reward_kinds = [
|
| 24 |
+
"diff_similarity",
|
| 25 |
+
]
|
| 26 |
+
spec_version = "0.2.0"
|
| 27 |
+
content_hash = "sha256:12c0be590b586dd51b4c65da15591e3dc63ada500d725701fae81ef03eba0085"
|
| 28 |
+
|
| 29 |
+
[metadata.repo2env.pr_diff]
|
| 30 |
+
pr_merged_at = "2026-10-06T13:03:56Z"
|
| 31 |
+
diff_format = "unified"
|
| 32 |
+
context_files = [
|
| 33 |
+
"src/main/java/org/traccar/api/resource/ShareResource.java",
|
| 34 |
+
]
|
| 35 |
+
bootstrap_image = "python:3.12-slim"
|
| 36 |
+
|
| 37 |
+
[metadata.repo2env.reward_calibration]
|
| 38 |
+
baseline_reward = 0.0
|
| 39 |
+
loc_changed = 4
|
| 40 |
+
difficulty = "trivial"
|
| 41 |
+
|
| 42 |
+
[metadata.repo2env.evaluation]
|
| 43 |
+
schema_version = "1"
|
| 44 |
+
status = "unverified"
|
| 45 |
+
stage = "generation"
|
| 46 |
+
reason_codes = [
|
| 47 |
+
"validation_not_run",
|
| 48 |
+
]
|
| 49 |
+
detail = "Generated task; validation has not been established."
|
| 50 |
+
provenance = "unknown"
|
| 51 |
+
evidence = []
|
| 52 |
+
|
| 53 |
+
[metadata.repo2env.reproducibility]
|
| 54 |
+
mode = "inline_dockerfile"
|
| 55 |
+
image_ref = "python:3.12-slim"
|
| 56 |
+
image_tag = "python:3.12-slim"
|
| 57 |
+
image_visibility = "public"
|
| 58 |
+
pushed_at = "2026-11-16T16:20:03.529551+00:00"
|
| 59 |
+
pushed_by = "scalingX"
|
| 60 |
+
inline_recipe_sha256 = "sha256:7180a886cf0aeed8bb0a746baf8fe3b8ea25e967d642e91302034d8b2c01025a"
|
| 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/traccar__traccar-6060/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/traccar__traccar-6060/tests/instruction.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Reject repeated share of the same object
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Reject repeated share of the same object
|
| 8 |
+
|
| 9 |
+
with the second option from the issue thread.
|
| 10 |
+
|
| 11 |
+
A share creates one temporary user per device or group, and that user keeps the expiration it was created with. A second share request for the same object skipped user creation but still returned a new token. Once the first share expired, that token failed at login with "User has expired".
|
| 12 |
+
|
| 13 |
+
Now the second request returns 409 Conflict with "Already shared", so the client gets an error instead of a token that can't be used. The first share works as before.
|
| 14 |
+
|
| 15 |
+
Added ShareResourceTest with two cases. The first checks that a first share creates the user and returns a token. The second checks that sharing again after the first share expired returns 409 and generates no token. The second case fails without the change.
|
| 16 |
+
|
| 17 |
+
Ran ShareResourceTest plus checkstyleMain and checkstyleTest locally. All pass.
|
| 18 |
+
|
| 19 |
+
## Task
|
| 20 |
+
|
| 21 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bdb7f6335cb4`. 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/traccar__traccar-6060/tests/oracle.patch
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/api/resource/ShareResource.java b/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 2 |
+
index 14b352a68..818ecd86b 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/api/resource/ShareResource.java
|
| 5 |
+
@@ -35,7 +35,9 @@ import jakarta.ws.rs.FormParam;
|
| 6 |
+
import jakarta.ws.rs.POST;
|
| 7 |
+
import jakarta.ws.rs.Path;
|
| 8 |
+
import jakarta.ws.rs.Produces;
|
| 9 |
+
+import jakarta.ws.rs.WebApplicationException;
|
| 10 |
+
import jakarta.ws.rs.core.MediaType;
|
| 11 |
+
+import jakarta.ws.rs.core.Response;
|
| 12 |
+
import java.io.IOException;
|
| 13 |
+
import java.security.GeneralSecurityException;
|
| 14 |
+
import java.util.Date;
|
| 15 |
+
@@ -94,6 +96,8 @@ public class ShareResource extends BaseResource {
|
| 16 |
+
share.setId(storage.addObject(share, new Request(new Columns.Exclude("id"))));
|
| 17 |
+
|
| 18 |
+
storage.addPermission(new Permission(User.class, share.getId(), clazz, id));
|
| 19 |
+
+ } else {
|
| 20 |
+
+ throw new WebApplicationException(Response.Status.CONFLICT);
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
return tokenManager.generateToken(share.getId(), expiration);
|
tasks/traccar__traccar-6060/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 bdb7f6335cb4a75ec88fdcdc1a9de063b5497511 > "$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/traccar__traccar-6060/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/traccar__traccar-6064/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/traccar/traccar.git /workspace; \
|
| 16 |
+
else \
|
| 17 |
+
git clone --filter=blob:none https://github.com/traccar/traccar.git /workspace; \
|
| 18 |
+
fi \
|
| 19 |
+
&& git -C /workspace remote set-url origin https://github.com/traccar/traccar.git
|
| 20 |
+
WORKDIR /workspace
|
| 21 |
+
RUN git fetch --depth 1 origin cbe020f7f2362dbc5f7ac1be44977ffce5731916 2>/dev/null \
|
| 22 |
+
|| git fetch --unshallow origin 2>/dev/null || true
|
| 23 |
+
RUN git reset --hard cbe020f7f2362dbc5f7ac1be44977ffce5731916 \
|
| 24 |
+
&& git clean -fdx -e .venv -e venv -e __pycache__
|
| 25 |
+
RUN git checkout -q -B base cbe020f7f2362dbc5f7ac1be44977ffce5731916 \
|
| 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/traccar__traccar-6064/instruction.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Support Teltonika ATC/ATM parameters
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Teltonika's asset trackers (ATC700, ATM700, ATC704, ATC774, ATM774) use the FT platform protocol (Codec 8 Extended). Their model names don't match any of the existing model predicates in `TeltonikaProtocolDecoder` (`fmbXXX`, `fmb6XX`, `tatXXX`, `ftXXX`). As a result, the model-specific AVL IDs come through as raw `ioXXX` attributes. For example, battery level arrives as `io113` instead of `batteryLevel`.
|
| 8 |
+
|
| 9 |
+
This adds an `atXXX` predicate (`AT[CM]\d{3}`) that covers all five models and enables it for three parameters. `ftXXX` isn't reused because these trackers send an undocumented AVL 800 (value 0) that `ftXXX` would decode as 0 V `power`.
|
| 10 |
+
|
| 11 |
+
EDIT: also added device temperature parameter (KEY_DEVICE_TEMP), that was missing also for the FT* trackers.
|
| 12 |
+
|
| 13 |
+
IDs 68, 80 and 113 match what Traccar already decodes for FMB/FT; ID 70 is newly decoded for both ATC/ATM and FT:
|
| 14 |
+
|
| 15 |
+
| AVL ID | Name | ATC/ATM spec | Decoded as |
|
| 16 |
+
|---|---|---|---|
|
| 17 |
+
| 68 | Battery current | 2 B unsigned, mA | `batteryCurrent` (A, same as FMB/FT) |
|
| 18 |
+
| 80 | Data acquisition mode | 1 B, 0–3 (bit 0 = moving, bit 1 = roaming) | `dataMode` (same values as FMB 0–3) |
|
| 19 |
+
| 113 | Battery level | 1 B, % | `batteryLevel` (same as FMB/FT) |
|
| 20 |
+
| 70 | PCB temperature | 2 B signed, −550 to 1150 (0.1 °C) | `deviceTemp` (°C, new, also enabled for FT; not FMB, where 70 is Geofence zone 11) |
|
| 21 |
+
|
| 22 |
+
IDs 80 and 113 are documented identically for all five models. ID 68 is documented for ATC700, ATM700 and ATC704 (ATC774 and ATM774 don't list it, so the handler only applies if a device actually sends it).
|
| 23 |
+
|
| 24 |
+
### Test
|
| 25 |
+
|
| 26 |
+
I have one ATC700 tracker, so I captured one packet from it (with coordinates replaced with a public location, CRC was recalculated) and used it as a test. It also checks that `power` is not set. The other models are covered based on their documentation only; I don't have packets from them.
|
| 27 |
+
|
| 28 |
+
### References
|
| 29 |
+
|
| 30 |
+
- [ATC700 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC700_Teltonika_Data_Sending_Parameters_ID)
|
| 31 |
+
- [ATM700 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATM700_Teltonika_Data_Sending_Parameters_ID)
|
| 32 |
+
- [ATC704 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC704_Teltonika_Data_Sending_Parameters_ID)
|
| 33 |
+
- [ATC774 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC774_Teltonika_Data_Sending_Parameters_ID)
|
| 34 |
+
- [ATM774 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATM774_Teltonika_Data_Sending_Parameters_ID)
|
| 35 |
+
- [AVL ID differences between FMB and FT platforms](https://wiki.teltonika-gps.com/view/AVL_ID_differences_between_FMB_and_FT_platforms)
|
| 36 |
+
- #6016: Support Teltonika FT platform parameters
|
| 37 |
+
|
| 38 |
+
## Task
|
| 39 |
+
|
| 40 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cbe020f7f236`. 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/traccar__traccar-6064/solution/patch.diff
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 2 |
+
index b1106021b..ba5653d30 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 5 |
+
@@ -190,7 +190,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
Predicate<String> fmbXXX = (m) -> m != null && m.matches("FM[B-Z]...|MTB100|MSP500");
|
| 7 |
+
Predicate<String> fmb6XX = (m) -> m != null && m.matches("FM.6..");
|
| 8 |
+
Predicate<String> tatXXX = (m) -> m != null && m.matches("T.T...");
|
| 9 |
+
- Predicate<String> ftXXX = (m) -> m != null && m.matches("FT[A-Z]\\d{3}");
|
| 10 |
+
+ Predicate<String> ftXXX = (m) -> m != null && m.matches("(FT[A-Z]|AT[CM])\\d{3}");
|
| 11 |
+
|
| 12 |
+
register(1, any, (p, b) -> p.set(Position.PREFIX_IN + 1, b.readUnsignedByte() > 0));
|
| 13 |
+
register(2, any, (p, b) -> p.set(Position.PREFIX_IN + 2, b.readUnsignedByte() > 0));
|
| 14 |
+
@@ -220,6 +220,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 15 |
+
register(66, any, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() / 1000.0));
|
| 16 |
+
register(67, any, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() / 1000.0));
|
| 17 |
+
register(68, fmbXXX.or(ftXXX), (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0));
|
| 18 |
+
+ register(70, ftXXX, (p, b) -> p.set(Position.KEY_DEVICE_TEMP, b.readShort() / 10.0));
|
| 19 |
+
register(72, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 1, b.readInt() / 10.0));
|
| 20 |
+
register(73, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 2, b.readInt() / 10.0));
|
| 21 |
+
register(74, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 3, b.readInt() / 10.0));
|
| 22 |
+
@@ -230,7 +231,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 23 |
+
p.set(Position.KEY_DRIVER_UNIQUE_ID, String.format("%016X", driverUniqueId));
|
| 24 |
+
}
|
| 25 |
+
});
|
| 26 |
+
- register(80, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set("dataMode", b.readUnsignedByte()));
|
| 27 |
+
+ register(80, fmbXXX.and(fmb6XX.negate()).or(ftXXX), (p, b) -> p.set("dataMode", b.readUnsignedByte()));
|
| 28 |
+
register(81, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_OBD_SPEED, b.readUnsignedByte()));
|
| 29 |
+
register(82, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_THROTTLE, b.readUnsignedByte()));
|
| 30 |
+
register(83, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_FUEL_USED, b.readUnsignedInt() / 10.0));
|
| 31 |
+
diff --git a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 32 |
+
index c1b03c99b..c1b30907a 100644
|
| 33 |
+
--- a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 34 |
+
+++ b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 35 |
+
@@ -221,6 +221,16 @@ public class TeltonikaProtocolDecoderTest extends ProtocolTest {
|
| 36 |
+
"00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"),
|
| 37 |
+
position().attribute(Position.KEY_BATTERY_LEVEL, 100));
|
| 38 |
+
|
| 39 |
+
+ decoder.setModelOverride("ATC700");
|
| 40 |
+
+
|
| 41 |
+
+ verifyDecode(decoder, binary(
|
| 42 |
+
+ "00000000000000528e01000001a11df939f8010898823c1ddabd9a00fc00260800000000000b000500150300450000715f00f000064000000500430f9200440000004600f800b503e800b603e8000103200000000000000000010000418f"),
|
| 43 |
+
+ position().attribute(Position.KEY_BATTERY_LEVEL, 95));
|
| 44 |
+
+
|
| 45 |
+
+ verifyDecode(decoder, binary(
|
| 46 |
+
+ "00000000000000528e01000001a11df939f8010898823c1ddabd9a00fc00260800000000000b000500150300450000715f00f000064000000500430f9200440000004600f800b503e800b603e8000103200000000000000000010000418f"),
|
| 47 |
+
+ position().attribute(Position.KEY_DEVICE_TEMP, 24.8));
|
| 48 |
+
+
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
@Test
|
tasks/traccar__traccar-6064/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/traccar__traccar-6064/task.toml
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "trending/traccar__traccar-6064"
|
| 5 |
+
description = "Support Teltonika ATC/ATM parameters"
|
| 6 |
+
|
| 7 |
+
[metadata]
|
| 8 |
+
difficulty = "small"
|
| 9 |
+
category = "bugfix"
|
| 10 |
+
keywords = [
|
| 11 |
+
"traccar",
|
| 12 |
+
"pr_diff",
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
[metadata.repo2env]
|
| 16 |
+
pipeline = "pr_diff"
|
| 17 |
+
pipeline_version = "0.3.0"
|
| 18 |
+
repo = "traccar/traccar"
|
| 19 |
+
ref = "cbe020f7f2362dbc5f7ac1be44977ffce5731916"
|
| 20 |
+
reference = "https://github.com/traccar/traccar/pull/6064"
|
| 21 |
+
source_access = "auto"
|
| 22 |
+
built_at = "2026-11-16T16:09:42.500770+00:00"
|
| 23 |
+
reward_kinds = [
|
| 24 |
+
"diff_similarity",
|
| 25 |
+
]
|
| 26 |
+
spec_version = "0.2.0"
|
| 27 |
+
content_hash = "sha256:bec61d6d5eb6cee1ece6f34a96e57c5841c5428033524eb9a20dc2f436a67852"
|
| 28 |
+
|
| 29 |
+
[metadata.repo2env.pr_diff]
|
| 30 |
+
pr_merged_at = "2026-10-15T14:14:16Z"
|
| 31 |
+
diff_format = "unified"
|
| 32 |
+
context_files = [
|
| 33 |
+
"src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java",
|
| 34 |
+
"src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java",
|
| 35 |
+
]
|
| 36 |
+
bootstrap_image = "python:3.12-slim"
|
| 37 |
+
|
| 38 |
+
[metadata.repo2env.reward_calibration]
|
| 39 |
+
baseline_reward = 0.0
|
| 40 |
+
loc_changed = 15
|
| 41 |
+
difficulty = "small"
|
| 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:03.530067+00:00"
|
| 60 |
+
pushed_by = "scalingX"
|
| 61 |
+
inline_recipe_sha256 = "sha256:de8db5ab41eae2755bde21a738a2032c22a879b9cd529451cbae3018cdfde6ab"
|
| 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/traccar__traccar-6064/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/traccar__traccar-6064/tests/instruction.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Issue
|
| 2 |
+
|
| 3 |
+
**Title:** Support Teltonika ATC/ATM parameters
|
| 4 |
+
|
| 5 |
+
## Description
|
| 6 |
+
|
| 7 |
+
Teltonika's asset trackers (ATC700, ATM700, ATC704, ATC774, ATM774) use the FT platform protocol (Codec 8 Extended). Their model names don't match any of the existing model predicates in `TeltonikaProtocolDecoder` (`fmbXXX`, `fmb6XX`, `tatXXX`, `ftXXX`). As a result, the model-specific AVL IDs come through as raw `ioXXX` attributes. For example, battery level arrives as `io113` instead of `batteryLevel`.
|
| 8 |
+
|
| 9 |
+
This adds an `atXXX` predicate (`AT[CM]\d{3}`) that covers all five models and enables it for three parameters. `ftXXX` isn't reused because these trackers send an undocumented AVL 800 (value 0) that `ftXXX` would decode as 0 V `power`.
|
| 10 |
+
|
| 11 |
+
EDIT: also added device temperature parameter (KEY_DEVICE_TEMP), that was missing also for the FT* trackers.
|
| 12 |
+
|
| 13 |
+
IDs 68, 80 and 113 match what Traccar already decodes for FMB/FT; ID 70 is newly decoded for both ATC/ATM and FT:
|
| 14 |
+
|
| 15 |
+
| AVL ID | Name | ATC/ATM spec | Decoded as |
|
| 16 |
+
|---|---|---|---|
|
| 17 |
+
| 68 | Battery current | 2 B unsigned, mA | `batteryCurrent` (A, same as FMB/FT) |
|
| 18 |
+
| 80 | Data acquisition mode | 1 B, 0–3 (bit 0 = moving, bit 1 = roaming) | `dataMode` (same values as FMB 0–3) |
|
| 19 |
+
| 113 | Battery level | 1 B, % | `batteryLevel` (same as FMB/FT) |
|
| 20 |
+
| 70 | PCB temperature | 2 B signed, −550 to 1150 (0.1 °C) | `deviceTemp` (°C, new, also enabled for FT; not FMB, where 70 is Geofence zone 11) |
|
| 21 |
+
|
| 22 |
+
IDs 80 and 113 are documented identically for all five models. ID 68 is documented for ATC700, ATM700 and ATC704 (ATC774 and ATM774 don't list it, so the handler only applies if a device actually sends it).
|
| 23 |
+
|
| 24 |
+
### Test
|
| 25 |
+
|
| 26 |
+
I have one ATC700 tracker, so I captured one packet from it (with coordinates replaced with a public location, CRC was recalculated) and used it as a test. It also checks that `power` is not set. The other models are covered based on their documentation only; I don't have packets from them.
|
| 27 |
+
|
| 28 |
+
### References
|
| 29 |
+
|
| 30 |
+
- [ATC700 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC700_Teltonika_Data_Sending_Parameters_ID)
|
| 31 |
+
- [ATM700 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATM700_Teltonika_Data_Sending_Parameters_ID)
|
| 32 |
+
- [ATC704 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC704_Teltonika_Data_Sending_Parameters_ID)
|
| 33 |
+
- [ATC774 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATC774_Teltonika_Data_Sending_Parameters_ID)
|
| 34 |
+
- [ATM774 Data Sending Parameters ID](https://wiki.teltonika-gps.com/view/ATM774_Teltonika_Data_Sending_Parameters_ID)
|
| 35 |
+
- [AVL ID differences between FMB and FT platforms](https://wiki.teltonika-gps.com/view/AVL_ID_differences_between_FMB_and_FT_platforms)
|
| 36 |
+
- #6016: Support Teltonika FT platform parameters
|
| 37 |
+
|
| 38 |
+
## Task
|
| 39 |
+
|
| 40 |
+
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cbe020f7f236`. 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/traccar__traccar-6064/tests/oracle.patch
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 2 |
+
index b1106021b..ba5653d30 100644
|
| 3 |
+
--- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 4 |
+
+++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java
|
| 5 |
+
@@ -190,7 +190,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 6 |
+
Predicate<String> fmbXXX = (m) -> m != null && m.matches("FM[B-Z]...|MTB100|MSP500");
|
| 7 |
+
Predicate<String> fmb6XX = (m) -> m != null && m.matches("FM.6..");
|
| 8 |
+
Predicate<String> tatXXX = (m) -> m != null && m.matches("T.T...");
|
| 9 |
+
- Predicate<String> ftXXX = (m) -> m != null && m.matches("FT[A-Z]\\d{3}");
|
| 10 |
+
+ Predicate<String> ftXXX = (m) -> m != null && m.matches("(FT[A-Z]|AT[CM])\\d{3}");
|
| 11 |
+
|
| 12 |
+
register(1, any, (p, b) -> p.set(Position.PREFIX_IN + 1, b.readUnsignedByte() > 0));
|
| 13 |
+
register(2, any, (p, b) -> p.set(Position.PREFIX_IN + 2, b.readUnsignedByte() > 0));
|
| 14 |
+
@@ -220,6 +220,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 15 |
+
register(66, any, (p, b) -> p.set(Position.KEY_POWER, b.readUnsignedShort() / 1000.0));
|
| 16 |
+
register(67, any, (p, b) -> p.set(Position.KEY_BATTERY, b.readUnsignedShort() / 1000.0));
|
| 17 |
+
register(68, fmbXXX.or(ftXXX), (p, b) -> p.set("batteryCurrent", b.readUnsignedShort() / 1000.0));
|
| 18 |
+
+ register(70, ftXXX, (p, b) -> p.set(Position.KEY_DEVICE_TEMP, b.readShort() / 10.0));
|
| 19 |
+
register(72, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 1, b.readInt() / 10.0));
|
| 20 |
+
register(73, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 2, b.readInt() / 10.0));
|
| 21 |
+
register(74, fmbXXX, (p, b) -> p.set(Position.PREFIX_TEMP + 3, b.readInt() / 10.0));
|
| 22 |
+
@@ -230,7 +231,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder {
|
| 23 |
+
p.set(Position.KEY_DRIVER_UNIQUE_ID, String.format("%016X", driverUniqueId));
|
| 24 |
+
}
|
| 25 |
+
});
|
| 26 |
+
- register(80, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set("dataMode", b.readUnsignedByte()));
|
| 27 |
+
+ register(80, fmbXXX.and(fmb6XX.negate()).or(ftXXX), (p, b) -> p.set("dataMode", b.readUnsignedByte()));
|
| 28 |
+
register(81, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_OBD_SPEED, b.readUnsignedByte()));
|
| 29 |
+
register(82, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_THROTTLE, b.readUnsignedByte()));
|
| 30 |
+
register(83, fmbXXX.and(fmb6XX.negate()), (p, b) -> p.set(Position.KEY_FUEL_USED, b.readUnsignedInt() / 10.0));
|
| 31 |
+
diff --git a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 32 |
+
index c1b03c99b..c1b30907a 100644
|
| 33 |
+
--- a/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 34 |
+
+++ b/src/test/java/org/traccar/protocol/TeltonikaProtocolDecoderTest.java
|
| 35 |
+
@@ -221,6 +221,16 @@ public class TeltonikaProtocolDecoderTest extends ProtocolTest {
|
| 36 |
+
"00000000000000968e010000019b76daa800000000000000000000000000000000000000001b000b00150500450000716400c80300ed0200ef0000f000012f00017f0333d20833d30a000a0011ffd30012ffe70013002300430fd400440000004600ee00b5000000b6000000ce000001820000000600100000000000c70000000000cd0000000000f100000000032000003249047c00000000000000000100003e0b"),
|
| 37 |
+
position().attribute(Position.KEY_BATTERY_LEVEL, 100));
|
| 38 |
+
|
| 39 |
+
+ decoder.setModelOverride("ATC700");
|
| 40 |
+
+
|
| 41 |
+
+ verifyDecode(decoder, binary(
|
| 42 |
+
+ "00000000000000528e01000001a11df939f8010898823c1ddabd9a00fc00260800000000000b000500150300450000715f00f000064000000500430f9200440000004600f800b503e800b603e8000103200000000000000000010000418f"),
|
| 43 |
+
+ position().attribute(Position.KEY_BATTERY_LEVEL, 95));
|
| 44 |
+
+
|
| 45 |
+
+ verifyDecode(decoder, binary(
|
| 46 |
+
+ "00000000000000528e01000001a11df939f8010898823c1ddabd9a00fc00260800000000000b000500150300450000715f00f000064000000500430f9200440000004600f800b503e800b603e8000103200000000000000000010000418f"),
|
| 47 |
+
+ position().attribute(Position.KEY_DEVICE_TEMP, 24.8));
|
| 48 |
+
+
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
@Test
|