Datasets:
Add 10000 GitHub Trending pr_diff environments (part 105)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/ublue-os__bazzite-6216/tests/test.shAdded+25
- tasks/ublue-os__bazzite-6216/tests/verifier.pyAdded+737
- tasks/ublue-os__bazzite-6229/environment/DockerfileAdded+37
- tasks/ublue-os__bazzite-6229/instruction.mdAdded+32
- tasks/ublue-os__bazzite-6229/solution/patch.diffAdded+176
- tasks/ublue-os__bazzite-6229/solution/solve.shAdded+6
- tasks/ublue-os__bazzite-6229/task.tomlAdded+72
- tasks/ublue-os__bazzite-6229/tests/capture.pyAdded+96
- tasks/ublue-os__bazzite-6229/tests/instruction.mdAdded+32
- tasks/ublue-os__bazzite-6229/tests/oracle.patchAdded+176
- tasks/ublue-os__bazzite-6229/tests/test.shAdded+25
- tasks/ublue-os__bazzite-6229/tests/verifier.pyAdded+737
- tasks/ublue-os__bazzite-6231/environment/DockerfileAdded+37
- tasks/ublue-os__bazzite-6231/instruction.mdAdded+41
- tasks/ublue-os__bazzite-6231/solution/patch.diffAdded+22
- tasks/ublue-os__bazzite-6231/solution/solve.shAdded+6
- tasks/ublue-os__bazzite-6231/task.tomlAdded+68
- tasks/ublue-os__bazzite-6231/tests/capture.pyAdded+96
- tasks/ublue-os__bazzite-6231/tests/instruction.mdAdded+41
- tasks/ublue-os__bazzite-6231/tests/oracle.patchAdded+22
- tasks/ublue-os__bazzite-6231/tests/test.shAdded+25
- tasks/ublue-os__bazzite-6231/tests/verifier.pyAdded+737
- tasks/ublue-os__bazzite-6232/environment/DockerfileAdded+37
- tasks/ublue-os__bazzite-6232/instruction.mdAdded+31
- tasks/ublue-os__bazzite-6232/solution/patch.diffAdded+15
- tasks/ublue-os__bazzite-6232/solution/solve.shAdded+6
- tasks/ublue-os__bazzite-6232/task.tomlAdded+68
- tasks/ublue-os__bazzite-6232/tests/capture.pyAdded+96
- tasks/ublue-os__bazzite-6232/tests/instruction.mdAdded+31
- tasks/ublue-os__bazzite-6232/tests/oracle.patchAdded+15
- tasks/ublue-os__bazzite-6232/tests/test.shAdded+25
- tasks/ublue-os__bazzite-6232/tests/verifier.pyAdded+737
- tasks/ublue-os__bazzite-6234/environment/DockerfileAdded+37
- tasks/ublue-os__bazzite-6234/instruction.mdAdded+20
- tasks/ublue-os__bazzite-6234/solution/patch.diffAdded+189
- tasks/ublue-os__bazzite-6234/solution/solve.shAdded+6
- tasks/ublue-os__bazzite-6234/task.tomlAdded+68
- tasks/ublue-os__bazzite-6234/tests/capture.pyAdded+96
- tasks/ublue-os__bazzite-6234/tests/instruction.mdAdded+20
- tasks/ublue-os__bazzite-6234/tests/oracle.patchAdded+189
- tasks/ublue-os__bazzite-6234/tests/test.shAdded+25
- tasks/ublue-os__bazzite-6234/tests/verifier.pyAdded+737
- tasks/ublue-os__bazzite-6243/environment/DockerfileAdded+37
- tasks/ublue-os__bazzite-6243/instruction.mdAdded+21
- tasks/ublue-os__bazzite-6243/solution/patch.diffAdded+38
- tasks/ublue-os__bazzite-6243/solution/solve.shAdded+6
- tasks/ublue-os__bazzite-6243/task.tomlAdded+68
- tasks/ublue-os__bazzite-6243/tests/capture.pyAdded+96
- tasks/ublue-os__bazzite-6243/tests/instruction.mdAdded+21
- tasks/ublue-os__bazzite-6243/tests/oracle.patchAdded+38
12345678910111213141516171819202122232425#!/bin/bashset -uxo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd /workspacemkdir -p /logs/verifierrm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.jsonCAPTURE_DIR="$(mktemp -d)" || exit 1trap 'rm -rf -- "$CAPTURE_DIR"' EXITif ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7e572db63e000dcd98b0c70f1c5da71f907ff358 > "$CAPTURE_DIR/predicted.patch"; then echo "0.0" > /logs/verifier/reward.txt printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json exit 0firm -f /logs/verifier/predicted.patchcp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch: 'START_VERIFY_OUTPUT'if ! python3 -I "$SCRIPT_DIR/verifier.py" \ "$SCRIPT_DIR/oracle.patch" \ "$CAPTURE_DIR/predicted.patch" \ "$SCRIPT_DIR/instruction.md"; then rm -f /logs/verifier/reward.txt /logs/verifier/reward.json printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.jsonfi: 'END_VERIFY_OUTPUT'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""In-container verifier for pr_diff tasks (6-component reward).
This module is the **standalone verifier** that runs inside the task'sDocker container, NOT a helper used at generation time. Generation emitsits source as ``tests/verifier.py``. Harbor delivers it at verify time,and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
format_valid (0 or 1) — predicted parses as a unified diff (guard) size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) catches "rampage through the codebase" file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — symmetric penalty over-punishes extras) region_overlap ([0, 1]) — predicted hunks overlap oracle hunks (strongest spatial-localization signal) similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only (no free credit for context lines) llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" Anthropic Haiku by default; any OpenAI- compatible server via ``R2E_JUDGE_ENDPOINT``. null when the judge is unavailable (no key or model, network, unreadable reply) → ungraded, no reward file; a reply without a valid score (refusal, content filter, empty, no "score") → a graded 0
Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned fromthe original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-taskpilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).Override per-task via ``task.toml.metadata`` or per-run via env vars``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so theyreach the verifier container).
Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatibleserver (vLLM, Ollama, a gateway) and switches the request to``<endpoint>/chat/completions`` with a bearer token from``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hostedservers ignore it. ``ANTHROPIC_API_KEY`` is only read on the defaultroute and is never sent to a custom endpoint.
Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops acharitable judge from inflating scores on wildly wrong-sized patches).
Outputs (mirrors `_pr_runtime_verifier.py` after #75): /logs/verifier/reward.txt — single float (Harbor reads this); graded runs only /logs/verifier/reward-details.json — full component breakdown + status (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- only, so the breakdown goes to the `reward-details.json` sidecar which Harbor renders under Verifier Logs → Rewards)
Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,``urllib``, ``sys``. The same module is imported by the unit testsunder ``tests/test_pr_diff_verifier.py`` so the in-container behaviorstays in lockstep with what we test."""
from __future__ import annotations
import argparseimport difflibimport jsonimport mathimport osimport reimport sysimport urllib.errorimport urllib.request
# ---------------------------------------------------------------------------# Parsing helpers (shared by multiple components)# ---------------------------------------------------------------------------
_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")_INDEX_RE = re.compile(r"^index ")
def file_paths(diff: str) -> set[str]: """Return the set of ``b/<path>`` paths touched by a unified diff.""" paths: set[str] = set() for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: paths.add(m.group(2)) return paths
def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: """For each touched file, return list of (start_line, end_line) ranges on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). """ out: dict[str, list[tuple[int, int]]] = {} current_file: str | None = None for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: current_file = m.group(2) out.setdefault(current_file, []) continue m = _HUNK_HEADER_RE.match(line) if m and current_file is not None: new_start = int(m.group(3)) new_count = int(m.group(4) or "1") end = new_start + max(new_count - 1, 0) out[current_file].append((new_start, end)) return out
def _normalize_changes_only(diff: str) -> list[str]: """Return the +/- lines (the actual changes) for similarity scoring.
Drops: - ``diff --git`` / ``index abc..def`` metadata - ``@@ ... @@`` hunk markers (volatile line numbers) - context lines (no +/- prefix) — these are unchanged code, scoring them inflates similarity for trivial patches Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity stays in the comparison; normalizes off the tab+timestamp suffix git sometimes appends. """ out: list[str] = [] for line in diff.splitlines(): if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): continue if _HUNK_HEADER_RE.match(line): continue if _FILE_MARKER_RE.match(line): out.append(line.split("\t")[0].strip()) continue # +/- lines (actual changes) if line.startswith("+") or line.startswith("-"): out.append(line) return out
# ---------------------------------------------------------------------------# Reward components# ---------------------------------------------------------------------------
def format_valid(predicted: str) -> float: """1.0 if the predicted text looks like a unified diff; else 0.0.
Requires both a ``diff --git`` header and at least one real +/- line (not the ``---`` / ``+++`` file-marker lines). """ if not predicted.strip(): return 0.0 has_header = False has_change = False for line in predicted.splitlines(): if _DIFF_HEADER_RE.match(line): has_header = True elif (line.startswith("+") or line.startswith("-")) and not line.startswith( ("+++ ", "--- ") ): has_change = True if has_header and has_change: return 1.0 return 0.0
def file_targeting(oracle: str, predicted: str) -> float: """F1 over the changed-file sets.
Why F1 instead of Jaccard: - Missing an oracle file (FN) is a *big* failure. - Touching one unrelated extra file (FP) is a small one. - Jaccard punishes both equally, which over-penalizes the agent for any extra exploration. - F1 weights TP twice, giving partial credit when the agent finds most-but-not-all of the oracle files even with some noise.
Returns 1.0 if both sides touch zero files (degenerate). """ o = file_paths(oracle) p = file_paths(predicted) if not o and not p: return 1.0 tp = len(o & p) fn = len(o - p) fp = len(p - o) if tp == 0: return 0.0 # F1 = 2·TP / (2·TP + FN + FP) return (2 * tp) / (2 * tp + fn + fp)
def _count_loc_changes(diff: str) -> int: """Number of real +/- lines (excluding file-marker lines).""" n = 0 for line in diff.splitlines(): if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): n += 1 return n
def size_sanity(oracle: str, predicted: str) -> float: """Penalize predicted patches that are wildly larger / smaller than the oracle.
Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
This is the "don't rampage through the codebase" guard — a 200-line diff for a 3-line oracle scores ~0.015 here even if every other component looks OK. """ o_loc = _count_loc_changes(oracle) p_loc = _count_loc_changes(predicted) if o_loc == 0 and p_loc == 0: return 1.0 if o_loc == 0 or p_loc == 0: return 0.0 return min(o_loc, p_loc) / max(o_loc, p_loc)
def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: """For each oracle hunk, did the predicted diff edit a line within ``slack_lines`` of that hunk in the same file?
Returns the fraction of oracle hunks that have at least one matching predicted hunk. ``slack_lines`` tolerates slight line-number drift when git diff renders the predicted hunk at a different offset. """ o_ranges = hunk_ranges(oracle) p_ranges = hunk_ranges(predicted) total = sum(len(v) for v in o_ranges.values()) if total == 0: return 1.0 # oracle has no hunks (degenerate) matched = 0 for fname, ranges in o_ranges.items(): p_in_file = p_ranges.get(fname, []) for o_start, o_end in ranges: for p_start, p_end in p_in_file: # Interval overlap with slack — max(starts) <= min(ends) + slack if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: matched += 1 break return matched / total
def similarity(oracle: str, predicted: str) -> float: """SequenceMatcher ratio over +/- lines only.
No free credit for context lines — fixes the v0.8.1 inflation where a one-line fix scored ~0.7 just because the 3 context lines on either side were "matched". """ if not predicted.strip(): return 0.0 o = _normalize_changes_only(oracle) p = _normalize_changes_only(predicted) if not o: return 0.0 # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can # run the verifier past Harbor's timeout. Above this many line pairs, # fall back to difflib's popular-element heuristic, which stays fast. exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
_SIMILARITY_EXACT_PAIRS = 400_000
# A predicted patch over 10x the oracle's changed lines is already a# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a# patch is a graded 0 instead of being scored, so one huge file can't slow# the verifier past its timeout and turn a failing episode into a dropped,# ungraded one. The byte cap stops it from being read at all._MAX_PREDICTED_FACTOR = 10_MAX_PREDICTED_FLOOR_LOC = 1_000_MAX_PREDICTED_BYTES = 16 * 1024 * 1024
def predicted_too_large(oracle: str, predicted: str) -> bool: """Whether the predicted patch is too large to score (a graded 0).""" limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) return _count_loc_changes(predicted) > limit
# ---------------------------------------------------------------------------# LLM-as-judge (Anthropic Messages API, stdlib urllib)# ---------------------------------------------------------------------------
_JUDGE_PROMPT = ( "You are scoring a code-fix patch on whether it logically addresses the " "described issue. Output a single JSON object: " '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' "DO NOT use the oracle to grade. Score on:\n" " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" " - Is the change direction consistent with what the issue describes?\n" " - Is it a real attempt (not boilerplate, not no-op)?\n\n" "Issue:\n{instruction}\n\n" "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" "{oracle}\n\n" "Predicted:\n{predicted}\n\n" "Return ONLY the JSON object.")
_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses._PLACEHOLDER_API_KEY = "EMPTY"
def llm_judge( *, instruction: str, oracle: str, predicted: str, api_key: str, model: str = _DEFAULT_JUDGE_MODEL, timeout: int = 60, endpoint: str | None = None,) -> tuple[float | None, str]: """Return ``(score, status)``.
``score`` is a float in [0, 1] on success, ``None`` on failure. ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. ``output_limit`` means the judge exhausted its configured token budget (ungraded, even if a partial answer contains a score). ``parse`` means the provider's body isn't JSON or has the wrong shape (ungraded); a reply with no usable text (refusal, content filter, empty) or no valid score is ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never increases the other weights.
``endpoint`` — base URL of an OpenAI-compatible server. When set, the request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a bearer token, at temperature 0, and ``model`` must be given explicitly; otherwise it goes to Anthropic's Messages API unchanged. """ if not api_key: return None, "no_api_key" if endpoint and not model: return None, "no_judge_model" if not predicted.strip(): return 0.0, "empty_predicted"
# Truncate hard so we don't blow up the prompt for big diffs prompt = _JUDGE_PROMPT.format( instruction=instruction[:4000], oracle=oracle[:4000], predicted=predicted[:4000], ) payload: dict = { "model": model, "max_tokens": 200, "messages": [{"role": "user", "content": prompt}], } if endpoint: # Small self-hosted models are noisy judges at their default sampling # temperature (same input scoring 0.0 one call and 1.0 the next); pin # them to greedy. The Anthropic route keeps its defaults — the weights # were calibrated against them. payload["temperature"] = 0 url = endpoint.rstrip("/") + "/chat/completions" headers = { "authorization": f"Bearer {api_key}", "content-type": "application/json", } else: url = _ANTHROPIC_MESSAGES_URL headers = { "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): return None, "network"
try: response = json.loads(raw) except json.JSONDecodeError: return None, "parse" # Provider-reported truncation is a grader capacity failure, not evidence # that the submitted patch is wrong. Reasoning models can spend the entire # output budget before producing visible text. Never grade a partial score. if isinstance(response, dict): choices = response.get("choices") if endpoint: if ( isinstance(choices, list) and choices and isinstance(choices[0], dict) and choices[0].get("finish_reason") == "length" ): return None, "output_limit" elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: return None, "output_limit" text = _judge_text(response, openai_compatible=bool(endpoint)) if text is None: return None, "parse"
# Pull the first JSON object out of the model's response m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) if not m: return None, "missing_score" try: obj = json.loads(m.group(0)) score = obj.get("score") except (json.JSONDecodeError, ValueError, TypeError): return None, "missing_score" if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): return None, "invalid_score" return float(score), "ok"
def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
A refusal or a content filter is a well-formed reply with no usable text. The agent's patch is in the prompt, so it can provoke one: that is ``""``, which grades 0, not ``None``, which leaves the run ungraded.
Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and ``content`` empty or holding partial text to discard. OpenAI-compatible: ``message.content`` is null with a ``refusal`` string or ``finish_reason: "content_filter"``. """ if not isinstance(payload, dict): return None if openai_compatible: choices = payload.get("choices") if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): return None message = choices[0].get("message") if not isinstance(message, dict): return None if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": return "" content = message.get("content") if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): # content parts return "".join( part.get("text", "") for part in content if isinstance(part, dict) and isinstance(part.get("text", ""), str) ) return None content = payload.get("content") if not isinstance(content, list): return None if payload.get("stop_reason") == "refusal": return "" return "".join( block["text"] for block in content if isinstance(block, dict) and block.get("type", "text") == "text" and isinstance(block.get("text"), str) )
# ---------------------------------------------------------------------------# Combination# ---------------------------------------------------------------------------
# Judge replies the agent can provoke: its patch text is part of the judge# prompt, so it can steer the answer away from a valid score. These are a# graded 0. An unreadable provider envelope (`parse`), missing configuration,# a disabled judge, transport errors and an exhausted judge output budget leave# the evaluation ungraded. Truncation alone cannot establish an incorrect patch._JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
def evaluation_status(judge_score: float | None, judge_status: str) -> str: """`graded` when the judge scored or the agent can have caused its failure.""" if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: return "graded" return "ungraded"
def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: """Combine declared components, requiring a positively weighted judge.
Without a judge score the result is 0. ``main`` records it as a graded 0 when the agent can have caused the judge failure, and otherwise writes no reward file, so Harbor reports the trial as VERIFIER_FAILED. """ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: return 0.0 if any(w > 0 and components.get(k) is None for k, w in weights.items()): return 0.0 return _weighted_mean(components, weights)
def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] if not available: return 0.0 # Relative weights need not sum to one. Scale first so large finite # overrides cannot overflow the numerator or denominator into NaN. scale = max(w for _, w in available) normalized = [(k, w / scale) for k, w in available] return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
# ---------------------------------------------------------------------------# Entry point (invoked by tests/test.sh inside the container)# ---------------------------------------------------------------------------
# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer# analysis grounded in per-task component data):## - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero# discriminative signal — its 0.05 weight was pure dead weight.# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.# Carrying both at 0.20 double-counts positional accuracy and# additionally penalizes legitimate alternative implementations.# - llm_judge → 0.50: only component capturing semantic correctness# independent of textual form; diverges informatively from# similarity on cases like tokenizers (judge=0.72, sim=0.08).# - region_overlap stays 0.20: strongest spatial-localization signal.# - file_targeting → 0.12: leading indicator, less correlated with the# rest than region/similarity are with each other.# - size_sanity → 0.08: useful outlier detector for catastrophic# over/under-generation (prettier=0.01, serde=0.08).## Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00._DEFAULT_WEIGHTS = { "format_valid": 0.00, "size_sanity": 0.08, "file_targeting": 0.12, "region_overlap": 0.20, "similarity": 0.10, "llm_judge": 0.50,}
# Hard cap: when size_sanity < this threshold, clamp final reward to# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating# the score on patches that are wildly the wrong size (catastrophic# over- or under-generation)._CATASTROPHIC_SIZE_THRESHOLD = 0.10_CATASTROPHIC_SIZE_CAP = 0.40
def _read_weights_from_env() -> dict[str, float]: """Override defaults via R2E_W_* env vars (set in container by harbor).""" overrides = { "format_valid": os.environ.get("R2E_W_FORMAT"), "size_sanity": os.environ.get("R2E_W_SIZE"), "file_targeting": os.environ.get("R2E_W_FILE"), "region_overlap": os.environ.get("R2E_W_REGION"), "similarity": os.environ.get("R2E_W_SIM"), "llm_judge": os.environ.get("R2E_W_JUDGE"), } out = dict(_DEFAULT_WEIGHTS) for k, v in overrides.items(): if v is None: continue try: value = float(v) if math.isfinite(value) and value >= 0: out[k] = value except (TypeError, ValueError): continue return out
def _judge_config_from_env() -> tuple[str, str, str | None]: """``(api_key, model, endpoint)`` for the judge, from the verifier env.
With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a self-hosted server won't have Haiku): when unset, ``model`` comes back as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of calling out. Without an endpoint the default Anthropic route is unchanged. """ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None model = os.environ.get("R2E_JUDGE_MODEL", "").strip() if endpoint: api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY return api_key, model, endpoint return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("oracle") parser.add_argument("predicted") parser.add_argument("instruction") parser.add_argument("--out-dir", default="/logs/verifier") args = parser.parse_args(argv) os.makedirs(args.out_dir, exist_ok=True) # This run is the only authority on the reward: an earlier or planted # reward file must not stand if this evaluation ends up ungraded. for name in ("reward.txt", "reward.json"): try: os.unlink(os.path.join(args.out_dir, name)) except FileNotFoundError: pass oracle = _read_or_empty(args.oracle) try: oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES except OSError: oversized = False predicted = "" if oversized else _read_or_empty(args.predicted) if oversized or predicted_too_large(oracle, predicted): breakdown = { "final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": False, "predicted_status": "predicted_too_large", } _write_outputs(args.out_dir, 0.0, breakdown) return 0 instruction = _read_or_empty(args.instruction) api_key, judge_model, judge_endpoint = _judge_config_from_env()
fv = format_valid(predicted) ss = size_sanity(oracle, predicted) ft = file_targeting(oracle, predicted) ro = region_overlap(oracle, predicted) sim = similarity(oracle, predicted) weights = _read_weights_from_env() if weights["llm_judge"] <= 0: judge_score, judge_status = None, "disabled" else: judge_score, judge_status = llm_judge( instruction=instruction, oracle=oracle, predicted=predicted, api_key=api_key, model=judge_model, endpoint=judge_endpoint, )
components: dict[str, float | None] = { "format_valid": fv, "size_sanity": ss, "file_targeting": ft, "region_overlap": ro, "similarity": sim, "llm_judge": judge_score, } final = combine(components, weights) final = max(0.0, min(1.0, final))
# Hard cap on catastrophic size mismatches. Without this, a charitable # judge can inflate the reward on patches that are dramatically the # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge # was lenient at 0.25 despite the patch being a near-no-op vs a # 500-line oracle). The cap kicks in only at the extremes. if ss < _CATASTROPHIC_SIZE_THRESHOLD: final = min(final, _CATASTROPHIC_SIZE_CAP)
status = evaluation_status(judge_score, judge_status) breakdown = { # No reward exists for an ungraded evaluation: null, not a placeholder 0. "final_reward": round(final, 6) if status == "graded" else None, "evaluation_status": status, "eval_trustworthy": judge_score is not None, "diagnostic_similarity": round( _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), 6, ), "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, "weights": {k: round(v, 6) for k, v in weights.items()}, "judge_model": judge_model if judge_status == "ok" else None, "judge_endpoint": judge_endpoint, "judge_status": judge_status, }
_write_outputs(args.out_dir, final, breakdown) return 0
def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: # An ungraded evaluation writes no reward file. Harbor then raises # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout # instead of training on a 0. Harbor's job mean and pass@k still count the # trial as 0, so evaluation stays fail-closed. if breakdown["evaluation_status"] == "graded": with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: f.write(f"{final:.6f}\n") # Harbor's `reward.json` must be a flat map of floats/ints (spec, see # <https://harborframework.com/docs/tasks>); our breakdown carries nested # dicts, judge strings, and status strings, so it goes to the sidecar the # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) # for `_pr_runtime_verifier.py`. with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: json.dump(breakdown, f, indent=2)
# Also print to stdout so harbor's log captures the breakdown print(json.dumps(breakdown, indent=2))
def _read_or_empty(path: str) -> str: try: with open(path, encoding="utf-8") as f: return f.read() except (OSError, UnicodeDecodeError): return ""
if __name__ == "__main__": sys.exit(main())
__all__ = [ "combine", "file_paths", "file_targeting", "format_valid", "hunk_ranges", "llm_judge", "main", "predicted_too_large", "region_overlap", "similarity", "size_sanity",]12345678910111213141516171819202122232425262728293031323334353637# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.# Agent-agnostic: the agent (claude-code / openhands / codex / etc.)# installs itself at run time via its harbor adapter. We only ship# the source repo — the oracle + verifier arrive at verify time via# tests/, never baked into the agent's image.FROM python:3.12-slimARG GITHUB_TOKEN=RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/*RUN git config --global --add safe.directory /workspace \ && git config --global init.defaultBranch main \ && git config --global advice.detachedHead falseRUN if [ -n "$GITHUB_TOKEN" ]; then \ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \ else \ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \ fi \ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.gitWORKDIR /workspaceRUN git fetch --depth 1 origin e1e1f97053a8332cdefae12e5f61d4696b0d940a 2>/dev/null \ || git fetch --unshallow origin 2>/dev/null || trueRUN git reset --hard e1e1f97053a8332cdefae12e5f61d4696b0d940a \ && git clean -fdx -e .venv -e venv -e __pycache__RUN git checkout -q -B base e1e1f97053a8332cdefae12e5f61d4696b0d940a \ && git remote remove origin 2>/dev/null || trueRUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ && git reflog expire --expire=now --all 2>/dev/null || true \ && git gc --prune=now 2>/dev/null || trueRUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ fi1234567891011121314151617181920212223242526272829303132# Issue
**Title:** feat(atlas8): sync with upstream PR
## Description
also remove files that have previously been removed
<!---Thank you for contributing to the Universal Blue project!Here are some tips for you:
## Thank you for contributing to the Universal Blue project!
Please [read the Contributor's Guide](https://universal-blue.org/contributing.html) before submitting a pull request.
In this project we follow [Semantic PRs][1] and [Conventional Commits][2] to describe features and fixes we made. It would be nice if you did too as we use this to generate changelogs with the right sections:
feat(deck): enable this deck specific feature fix(ally): fix screen rotation on the ally feat(gnome): Stuff that is GNOME specific
If you're unsure a generic `feat:` or `fix:` is fine! Did you already use this? Awesome, thanks again! Not sure what this all means? Here are some [more examples][3].
[1]: https://github.com/Ezard/semantic-prs[2]: https://www.conventionalcommits.org/en/v1.0.0/#summary[3]: https://www.conventionalcommits.org/en/v1.0.0/#examples-->
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yamldeleted file mode 100644index d8e776ee..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml+++ /dev/null@@ -1,46 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 2--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8 Extra Buttons"--# Unique identifier of the capability mapping-id: acer_atlas8_hid_type2--# Idle HID Report-# Data: 9a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00-# BUF[1] = 0x02 = M1 Pressed-# BUF[1] = 0x04 = M2 Pressed-# BUF[1] = 0x06 = M1+M2 Pressed--# This implementation is incomplete as the driver seems to currently be incapable-# of sending a button event depending on which bit is inside the selected byte section-# Guide button will also be included here once we have a kernel quirk in place for the button release signal that is missing-mapping:- - name: M1- source_events:- - hidraw:- value_type: uint8- byte_start: 1- min_value: 255- max_value: 255- target_event:- gamepad:- button: RightPaddle1- - name: M2- source_events:- - hidraw:- value_type: uint8- byte_start: 1- min_value: 77- max_value: 77- target_event:- gamepad:- button: LeftPaddle1--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yamldeleted file mode 100644index 289ec9af..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml+++ /dev/null@@ -1,26 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 2--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8 QAM"--# Unique identifier of the capability mapping-id: acer_atlas8_hid_type1--# List of mapped events that are activated by a specific set of activation keys.-mapping:- - name: QAM- source_events:- - hidraw:- value_type: bool- byte_start: 2- target_event:- gamepad:- button: QuickAccess--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yamldeleted file mode 100644index 7007f850..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml+++ /dev/null@@ -1,27 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 1--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8"--# Unique identifier of the capability mapping-id: acer_atlas8--# List of mapped events that are activated by a specific set of activation keys.-mapping:- # This capability map will make Guide and QAM accessible with hold actions- # since the press/tap actions on these buttons do not work currently- - name: Guide (hold)- source_events:- - keyboard: KeyLeftMeta- - keyboard: KeyTab- target_event:- gamepad:- button: Guide--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yamlindex 37541cd9..9a081290 100644--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml+++ b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml@@ -37,9 +37,19 @@ mapping: - hidraw: value_type: bool byte_start: 3+ bit_offset: 4 target_event: gamepad: button: QuickAccess2+ - name: Guide (hold)+ source_events:+ - hidraw:+ value_type: bool+ byte_start: 3+ bit_offset: 1+ target_event:+ gamepad:+ button: Guide # List of events to filter from the source devices filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yamlindex 6083ad26..ec5aea74 100644--- a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml+++ b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml@@ -15,19 +15,14 @@ matches: sys_vendor: Acer source_devices:- - group: gamepad- evdev:- name: " Xbox360 Controller for Windows Keyboard"- vendor_id: "0502"- product_id: "f901"- handler: event*+ # Atlas 8 Gamepad - group: gamepad evdev: name: Generic X-Box pad vendor_id: "0502" product_id: "f901" handler: event*- # Atlas 8 QAM button+ # Atlas 8 Guide and QAM buttons - group: gamepad hidraw: vendor_id: 0x0502@@ -42,8 +37,6 @@ source_devices: interface_num: 1 capability_map_id: acer_atlas8_hid_type2 -capability_map_id: acer_atlas8- # The target input device(s) to emulate by default target_devices: - xbox-elite123456#!/bin/bashset -euxo pipefailcd /workspacegit config --global --add safe.directory /workspacePATCH="$(dirname "$0")/patch.diff"git apply --verbose --reject "$PATCH"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172version = "1.0"
[task]name = "trending/ublue-os__bazzite-6229"description = "feat(atlas8): sync with upstream PR"
[metadata]difficulty = "large"category = "bugfix"keywords = [ "bazzite", "pr_diff",]
[metadata.repo2env]pipeline = "pr_diff"pipeline_version = "0.3.0"repo = "ublue-os/bazzite"ref = "e1e1f97053a8332cdefae12e5f61d4696b0d940a"reference = "https://github.com/ublue-os/bazzite/pull/6229"source_access = "auto"built_at = "2026-11-16T16:09:50.980913+00:00"reward_kinds = [ "diff_similarity",]spec_version = "0.2.0"content_hash = "sha256:eb116ef92e453ba09241213f66a8aed3a0bcf1fdc8001a058adbe9b6aa4c3189"
[metadata.repo2env.pr_diff]pr_merged_at = "2026-11-04T13:19:56Z"diff_format = "unified"context_files = [ "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml", "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml", "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml", "system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml", "system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml",]bootstrap_image = "python:3.12-slim"
[metadata.repo2env.reward_calibration]baseline_reward = 0.0loc_changed = 120difficulty = "large"
[metadata.repo2env.evaluation]schema_version = "1"status = "unverified"stage = "generation"reason_codes = [ "validation_not_run",]detail = "Generated task; validation has not been established."provenance = "unknown"evidence = []
[metadata.repo2env.reproducibility]mode = "inline_dockerfile"image_ref = "python:3.12-slim"image_tag = "python:3.12-slim"image_visibility = "public"pushed_at = "2026-11-16T16:20:03.587263+00:00"pushed_by = "scalingX"inline_recipe_sha256 = "sha256:e1c72bf41c74f9342ae165a509f4de0c95f0f2f3c9693a7cc559c4b7390192fa"inline_recipe_lines = 37inline_recipe_source = "user_dockerfile"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 300.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Standalone PR-diff capture without executing workspace Git configuration.
The emitted task uses a regular clone with a pinned base commit. Only itsobject store is read: refs, index, config, hooks and replacement refs are notused. This is a configuration boundary, not a sandbox for a malicious processthat can modify the verifier, binaries or object store while capture runs."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
def capture(workspace: Path, base_commit: str) -> bytes: """Capture tracked and new files through a fresh private Git index.""" if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): raise ValueError("Expected the task's pinned SHA-1 base commit") objects = workspace.resolve() / ".git" / "objects" if not objects.is_dir(): raise ValueError("The task's cloned Git object store is missing") git = shutil.which("git", path=os.defpath) if git is None: raise FileNotFoundError("System git is unavailable") with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: private = Path(temporary) # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, # system/global includes, user attributes, templates or credential env. env = { "PATH": os.defpath, "HOME": temporary, "XDG_CONFIG_HOME": temporary, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", } subprocess.run( [git, "init", "--quiet", "--template=", str(private / "repository")], env=env, cwd=private, check=True, capture_output=True, timeout=60, ) env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) command = [ git, f"--git-dir={private / 'repository/.git'}", f"--work-tree={workspace.resolve()}", ]
def run(*args: str) -> bytes: return subprocess.run( [*command, *args], env=env, cwd=workspace, check=True, capture_output=True, timeout=60, ).stdout
run("read-tree", f"{base_commit}^{{tree}}") # All filter drivers are undefined in the private configuration. The # workspace's clean filters, fsmonitor and hooks cannot be invoked. run("add", "--all", "--", ".") return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("workspace", type=Path) parser.add_argument("base_commit") args = parser.parse_args(argv) try: patch = capture(args.workspace, args.base_commit) except (OSError, ValueError, subprocess.SubprocessError) as exc: # Do not echo child stderr: it may contain workspace-controlled data. sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") return 1 sys.stdout.buffer.write(patch) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132# Issue
**Title:** feat(atlas8): sync with upstream PR
## Description
also remove files that have previously been removed
<!---Thank you for contributing to the Universal Blue project!Here are some tips for you:
## Thank you for contributing to the Universal Blue project!
Please [read the Contributor's Guide](https://universal-blue.org/contributing.html) before submitting a pull request.
In this project we follow [Semantic PRs][1] and [Conventional Commits][2] to describe features and fixes we made. It would be nice if you did too as we use this to generate changelogs with the right sections:
feat(deck): enable this deck specific feature fix(ally): fix screen rotation on the ally feat(gnome): Stuff that is GNOME specific
If you're unsure a generic `feat:` or `fix:` is fine! Did you already use this? Awesome, thanks again! Not sure what this all means? Here are some [more examples][3].
[1]: https://github.com/Ezard/semantic-prs[2]: https://www.conventionalcommits.org/en/v1.0.0/#summary[3]: https://www.conventionalcommits.org/en/v1.0.0/#examples-->
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yamldeleted file mode 100644index d8e776ee..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_extra.yaml+++ /dev/null@@ -1,46 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 2--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8 Extra Buttons"--# Unique identifier of the capability mapping-id: acer_atlas8_hid_type2--# Idle HID Report-# Data: 9a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00-# BUF[1] = 0x02 = M1 Pressed-# BUF[1] = 0x04 = M2 Pressed-# BUF[1] = 0x06 = M1+M2 Pressed--# This implementation is incomplete as the driver seems to currently be incapable-# of sending a button event depending on which bit is inside the selected byte section-# Guide button will also be included here once we have a kernel quirk in place for the button release signal that is missing-mapping:- - name: M1- source_events:- - hidraw:- value_type: uint8- byte_start: 1- min_value: 255- max_value: 255- target_event:- gamepad:- button: RightPaddle1- - name: M2- source_events:- - hidraw:- value_type: uint8- byte_start: 1- min_value: 77- max_value: 77- target_event:- gamepad:- button: LeftPaddle1--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yamldeleted file mode 100644index 289ec9af..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer-atlas8_hidraw_qam.yaml+++ /dev/null@@ -1,26 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 2--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8 QAM"--# Unique identifier of the capability mapping-id: acer_atlas8_hid_type1--# List of mapped events that are activated by a specific set of activation keys.-mapping:- - name: QAM- source_events:- - hidraw:- value_type: bool- byte_start: 2- target_event:- gamepad:- button: QuickAccess--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yamldeleted file mode 100644index 7007f850..00000000--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8.yaml+++ /dev/null@@ -1,27 +0,0 @@-# yaml-language-server: $schema=https://raw.githubusercontent.com/ShadowBlip/InputPlumber/main/rootfs/usr/share/inputplumber/schema/capability_map_v2.json-# Schema version number-version: 1--# The type of configuration schema-kind: CapabilityMap--# Name for the device event map-name: "Acer Atlas 8"--# Unique identifier of the capability mapping-id: acer_atlas8--# List of mapped events that are activated by a specific set of activation keys.-mapping:- # This capability map will make Guide and QAM accessible with hold actions- # since the press/tap actions on these buttons do not work currently- - name: Guide (hold)- source_events:- - keyboard: KeyLeftMeta- - keyboard: KeyTab- target_event:- gamepad:- button: Guide--# List of events to filter from the source devices-filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yamlindex 37541cd9..9a081290 100644--- a/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml+++ b/system_files/deck/shared/etc/inputplumber/capability_maps.d/acer_atlas8_hid_type1.yaml@@ -37,9 +37,19 @@ mapping: - hidraw: value_type: bool byte_start: 3+ bit_offset: 4 target_event: gamepad: button: QuickAccess2+ - name: Guide (hold)+ source_events:+ - hidraw:+ value_type: bool+ byte_start: 3+ bit_offset: 1+ target_event:+ gamepad:+ button: Guide # List of events to filter from the source devices filtered_events: []diff --git a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yamlindex 6083ad26..ec5aea74 100644--- a/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml+++ b/system_files/deck/shared/etc/inputplumber/devices.d/70-acer_atlas8.yaml@@ -15,19 +15,14 @@ matches: sys_vendor: Acer source_devices:- - group: gamepad- evdev:- name: " Xbox360 Controller for Windows Keyboard"- vendor_id: "0502"- product_id: "f901"- handler: event*+ # Atlas 8 Gamepad - group: gamepad evdev: name: Generic X-Box pad vendor_id: "0502" product_id: "f901" handler: event*- # Atlas 8 QAM button+ # Atlas 8 Guide and QAM buttons - group: gamepad hidraw: vendor_id: 0x0502@@ -42,8 +37,6 @@ source_devices: interface_num: 1 capability_map_id: acer_atlas8_hid_type2 -capability_map_id: acer_atlas8- # The target input device(s) to emulate by default target_devices: - xbox-elite12345678910111213141516171819202122232425#!/bin/bashset -uxo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd /workspacemkdir -p /logs/verifierrm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.jsonCAPTURE_DIR="$(mktemp -d)" || exit 1trap 'rm -rf -- "$CAPTURE_DIR"' EXITif ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e1e1f97053a8332cdefae12e5f61d4696b0d940a > "$CAPTURE_DIR/predicted.patch"; then echo "0.0" > /logs/verifier/reward.txt printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json exit 0firm -f /logs/verifier/predicted.patchcp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch: 'START_VERIFY_OUTPUT'if ! python3 -I "$SCRIPT_DIR/verifier.py" \ "$SCRIPT_DIR/oracle.patch" \ "$CAPTURE_DIR/predicted.patch" \ "$SCRIPT_DIR/instruction.md"; then rm -f /logs/verifier/reward.txt /logs/verifier/reward.json printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.jsonfi: 'END_VERIFY_OUTPUT'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""In-container verifier for pr_diff tasks (6-component reward).
This module is the **standalone verifier** that runs inside the task'sDocker container, NOT a helper used at generation time. Generation emitsits source as ``tests/verifier.py``. Harbor delivers it at verify time,and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
format_valid (0 or 1) — predicted parses as a unified diff (guard) size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) catches "rampage through the codebase" file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — symmetric penalty over-punishes extras) region_overlap ([0, 1]) — predicted hunks overlap oracle hunks (strongest spatial-localization signal) similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only (no free credit for context lines) llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" Anthropic Haiku by default; any OpenAI- compatible server via ``R2E_JUDGE_ENDPOINT``. null when the judge is unavailable (no key or model, network, unreadable reply) → ungraded, no reward file; a reply without a valid score (refusal, content filter, empty, no "score") → a graded 0
Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned fromthe original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-taskpilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).Override per-task via ``task.toml.metadata`` or per-run via env vars``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so theyreach the verifier container).
Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatibleserver (vLLM, Ollama, a gateway) and switches the request to``<endpoint>/chat/completions`` with a bearer token from``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hostedservers ignore it. ``ANTHROPIC_API_KEY`` is only read on the defaultroute and is never sent to a custom endpoint.
Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops acharitable judge from inflating scores on wildly wrong-sized patches).
Outputs (mirrors `_pr_runtime_verifier.py` after #75): /logs/verifier/reward.txt — single float (Harbor reads this); graded runs only /logs/verifier/reward-details.json — full component breakdown + status (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- only, so the breakdown goes to the `reward-details.json` sidecar which Harbor renders under Verifier Logs → Rewards)
Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,``urllib``, ``sys``. The same module is imported by the unit testsunder ``tests/test_pr_diff_verifier.py`` so the in-container behaviorstays in lockstep with what we test."""
from __future__ import annotations
import argparseimport difflibimport jsonimport mathimport osimport reimport sysimport urllib.errorimport urllib.request
# ---------------------------------------------------------------------------# Parsing helpers (shared by multiple components)# ---------------------------------------------------------------------------
_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")_INDEX_RE = re.compile(r"^index ")
def file_paths(diff: str) -> set[str]: """Return the set of ``b/<path>`` paths touched by a unified diff.""" paths: set[str] = set() for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: paths.add(m.group(2)) return paths
def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: """For each touched file, return list of (start_line, end_line) ranges on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). """ out: dict[str, list[tuple[int, int]]] = {} current_file: str | None = None for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: current_file = m.group(2) out.setdefault(current_file, []) continue m = _HUNK_HEADER_RE.match(line) if m and current_file is not None: new_start = int(m.group(3)) new_count = int(m.group(4) or "1") end = new_start + max(new_count - 1, 0) out[current_file].append((new_start, end)) return out
def _normalize_changes_only(diff: str) -> list[str]: """Return the +/- lines (the actual changes) for similarity scoring.
Drops: - ``diff --git`` / ``index abc..def`` metadata - ``@@ ... @@`` hunk markers (volatile line numbers) - context lines (no +/- prefix) — these are unchanged code, scoring them inflates similarity for trivial patches Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity stays in the comparison; normalizes off the tab+timestamp suffix git sometimes appends. """ out: list[str] = [] for line in diff.splitlines(): if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): continue if _HUNK_HEADER_RE.match(line): continue if _FILE_MARKER_RE.match(line): out.append(line.split("\t")[0].strip()) continue # +/- lines (actual changes) if line.startswith("+") or line.startswith("-"): out.append(line) return out
# ---------------------------------------------------------------------------# Reward components# ---------------------------------------------------------------------------
def format_valid(predicted: str) -> float: """1.0 if the predicted text looks like a unified diff; else 0.0.
Requires both a ``diff --git`` header and at least one real +/- line (not the ``---`` / ``+++`` file-marker lines). """ if not predicted.strip(): return 0.0 has_header = False has_change = False for line in predicted.splitlines(): if _DIFF_HEADER_RE.match(line): has_header = True elif (line.startswith("+") or line.startswith("-")) and not line.startswith( ("+++ ", "--- ") ): has_change = True if has_header and has_change: return 1.0 return 0.0
def file_targeting(oracle: str, predicted: str) -> float: """F1 over the changed-file sets.
Why F1 instead of Jaccard: - Missing an oracle file (FN) is a *big* failure. - Touching one unrelated extra file (FP) is a small one. - Jaccard punishes both equally, which over-penalizes the agent for any extra exploration. - F1 weights TP twice, giving partial credit when the agent finds most-but-not-all of the oracle files even with some noise.
Returns 1.0 if both sides touch zero files (degenerate). """ o = file_paths(oracle) p = file_paths(predicted) if not o and not p: return 1.0 tp = len(o & p) fn = len(o - p) fp = len(p - o) if tp == 0: return 0.0 # F1 = 2·TP / (2·TP + FN + FP) return (2 * tp) / (2 * tp + fn + fp)
def _count_loc_changes(diff: str) -> int: """Number of real +/- lines (excluding file-marker lines).""" n = 0 for line in diff.splitlines(): if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): n += 1 return n
def size_sanity(oracle: str, predicted: str) -> float: """Penalize predicted patches that are wildly larger / smaller than the oracle.
Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
This is the "don't rampage through the codebase" guard — a 200-line diff for a 3-line oracle scores ~0.015 here even if every other component looks OK. """ o_loc = _count_loc_changes(oracle) p_loc = _count_loc_changes(predicted) if o_loc == 0 and p_loc == 0: return 1.0 if o_loc == 0 or p_loc == 0: return 0.0 return min(o_loc, p_loc) / max(o_loc, p_loc)
def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: """For each oracle hunk, did the predicted diff edit a line within ``slack_lines`` of that hunk in the same file?
Returns the fraction of oracle hunks that have at least one matching predicted hunk. ``slack_lines`` tolerates slight line-number drift when git diff renders the predicted hunk at a different offset. """ o_ranges = hunk_ranges(oracle) p_ranges = hunk_ranges(predicted) total = sum(len(v) for v in o_ranges.values()) if total == 0: return 1.0 # oracle has no hunks (degenerate) matched = 0 for fname, ranges in o_ranges.items(): p_in_file = p_ranges.get(fname, []) for o_start, o_end in ranges: for p_start, p_end in p_in_file: # Interval overlap with slack — max(starts) <= min(ends) + slack if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: matched += 1 break return matched / total
def similarity(oracle: str, predicted: str) -> float: """SequenceMatcher ratio over +/- lines only.
No free credit for context lines — fixes the v0.8.1 inflation where a one-line fix scored ~0.7 just because the 3 context lines on either side were "matched". """ if not predicted.strip(): return 0.0 o = _normalize_changes_only(oracle) p = _normalize_changes_only(predicted) if not o: return 0.0 # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can # run the verifier past Harbor's timeout. Above this many line pairs, # fall back to difflib's popular-element heuristic, which stays fast. exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
_SIMILARITY_EXACT_PAIRS = 400_000
# A predicted patch over 10x the oracle's changed lines is already a# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a# patch is a graded 0 instead of being scored, so one huge file can't slow# the verifier past its timeout and turn a failing episode into a dropped,# ungraded one. The byte cap stops it from being read at all._MAX_PREDICTED_FACTOR = 10_MAX_PREDICTED_FLOOR_LOC = 1_000_MAX_PREDICTED_BYTES = 16 * 1024 * 1024
def predicted_too_large(oracle: str, predicted: str) -> bool: """Whether the predicted patch is too large to score (a graded 0).""" limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) return _count_loc_changes(predicted) > limit
# ---------------------------------------------------------------------------# LLM-as-judge (Anthropic Messages API, stdlib urllib)# ---------------------------------------------------------------------------
_JUDGE_PROMPT = ( "You are scoring a code-fix patch on whether it logically addresses the " "described issue. Output a single JSON object: " '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' "DO NOT use the oracle to grade. Score on:\n" " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" " - Is the change direction consistent with what the issue describes?\n" " - Is it a real attempt (not boilerplate, not no-op)?\n\n" "Issue:\n{instruction}\n\n" "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" "{oracle}\n\n" "Predicted:\n{predicted}\n\n" "Return ONLY the JSON object.")
_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses._PLACEHOLDER_API_KEY = "EMPTY"
def llm_judge( *, instruction: str, oracle: str, predicted: str, api_key: str, model: str = _DEFAULT_JUDGE_MODEL, timeout: int = 60, endpoint: str | None = None,) -> tuple[float | None, str]: """Return ``(score, status)``.
``score`` is a float in [0, 1] on success, ``None`` on failure. ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. ``output_limit`` means the judge exhausted its configured token budget (ungraded, even if a partial answer contains a score). ``parse`` means the provider's body isn't JSON or has the wrong shape (ungraded); a reply with no usable text (refusal, content filter, empty) or no valid score is ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never increases the other weights.
``endpoint`` — base URL of an OpenAI-compatible server. When set, the request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a bearer token, at temperature 0, and ``model`` must be given explicitly; otherwise it goes to Anthropic's Messages API unchanged. """ if not api_key: return None, "no_api_key" if endpoint and not model: return None, "no_judge_model" if not predicted.strip(): return 0.0, "empty_predicted"
# Truncate hard so we don't blow up the prompt for big diffs prompt = _JUDGE_PROMPT.format( instruction=instruction[:4000], oracle=oracle[:4000], predicted=predicted[:4000], ) payload: dict = { "model": model, "max_tokens": 200, "messages": [{"role": "user", "content": prompt}], } if endpoint: # Small self-hosted models are noisy judges at their default sampling # temperature (same input scoring 0.0 one call and 1.0 the next); pin # them to greedy. The Anthropic route keeps its defaults — the weights # were calibrated against them. payload["temperature"] = 0 url = endpoint.rstrip("/") + "/chat/completions" headers = { "authorization": f"Bearer {api_key}", "content-type": "application/json", } else: url = _ANTHROPIC_MESSAGES_URL headers = { "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): return None, "network"
try: response = json.loads(raw) except json.JSONDecodeError: return None, "parse" # Provider-reported truncation is a grader capacity failure, not evidence # that the submitted patch is wrong. Reasoning models can spend the entire # output budget before producing visible text. Never grade a partial score. if isinstance(response, dict): choices = response.get("choices") if endpoint: if ( isinstance(choices, list) and choices and isinstance(choices[0], dict) and choices[0].get("finish_reason") == "length" ): return None, "output_limit" elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: return None, "output_limit" text = _judge_text(response, openai_compatible=bool(endpoint)) if text is None: return None, "parse"
# Pull the first JSON object out of the model's response m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) if not m: return None, "missing_score" try: obj = json.loads(m.group(0)) score = obj.get("score") except (json.JSONDecodeError, ValueError, TypeError): return None, "missing_score" if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): return None, "invalid_score" return float(score), "ok"
def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
A refusal or a content filter is a well-formed reply with no usable text. The agent's patch is in the prompt, so it can provoke one: that is ``""``, which grades 0, not ``None``, which leaves the run ungraded.
Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and ``content`` empty or holding partial text to discard. OpenAI-compatible: ``message.content`` is null with a ``refusal`` string or ``finish_reason: "content_filter"``. """ if not isinstance(payload, dict): return None if openai_compatible: choices = payload.get("choices") if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): return None message = choices[0].get("message") if not isinstance(message, dict): return None if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": return "" content = message.get("content") if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): # content parts return "".join( part.get("text", "") for part in content if isinstance(part, dict) and isinstance(part.get("text", ""), str) ) return None content = payload.get("content") if not isinstance(content, list): return None if payload.get("stop_reason") == "refusal": return "" return "".join( block["text"] for block in content if isinstance(block, dict) and block.get("type", "text") == "text" and isinstance(block.get("text"), str) )
# ---------------------------------------------------------------------------# Combination# ---------------------------------------------------------------------------
# Judge replies the agent can provoke: its patch text is part of the judge# prompt, so it can steer the answer away from a valid score. These are a# graded 0. An unreadable provider envelope (`parse`), missing configuration,# a disabled judge, transport errors and an exhausted judge output budget leave# the evaluation ungraded. Truncation alone cannot establish an incorrect patch._JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
def evaluation_status(judge_score: float | None, judge_status: str) -> str: """`graded` when the judge scored or the agent can have caused its failure.""" if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: return "graded" return "ungraded"
def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: """Combine declared components, requiring a positively weighted judge.
Without a judge score the result is 0. ``main`` records it as a graded 0 when the agent can have caused the judge failure, and otherwise writes no reward file, so Harbor reports the trial as VERIFIER_FAILED. """ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: return 0.0 if any(w > 0 and components.get(k) is None for k, w in weights.items()): return 0.0 return _weighted_mean(components, weights)
def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] if not available: return 0.0 # Relative weights need not sum to one. Scale first so large finite # overrides cannot overflow the numerator or denominator into NaN. scale = max(w for _, w in available) normalized = [(k, w / scale) for k, w in available] return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
# ---------------------------------------------------------------------------# Entry point (invoked by tests/test.sh inside the container)# ---------------------------------------------------------------------------
# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer# analysis grounded in per-task component data):## - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero# discriminative signal — its 0.05 weight was pure dead weight.# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.# Carrying both at 0.20 double-counts positional accuracy and# additionally penalizes legitimate alternative implementations.# - llm_judge → 0.50: only component capturing semantic correctness# independent of textual form; diverges informatively from# similarity on cases like tokenizers (judge=0.72, sim=0.08).# - region_overlap stays 0.20: strongest spatial-localization signal.# - file_targeting → 0.12: leading indicator, less correlated with the# rest than region/similarity are with each other.# - size_sanity → 0.08: useful outlier detector for catastrophic# over/under-generation (prettier=0.01, serde=0.08).## Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00._DEFAULT_WEIGHTS = { "format_valid": 0.00, "size_sanity": 0.08, "file_targeting": 0.12, "region_overlap": 0.20, "similarity": 0.10, "llm_judge": 0.50,}
# Hard cap: when size_sanity < this threshold, clamp final reward to# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating# the score on patches that are wildly the wrong size (catastrophic# over- or under-generation)._CATASTROPHIC_SIZE_THRESHOLD = 0.10_CATASTROPHIC_SIZE_CAP = 0.40
def _read_weights_from_env() -> dict[str, float]: """Override defaults via R2E_W_* env vars (set in container by harbor).""" overrides = { "format_valid": os.environ.get("R2E_W_FORMAT"), "size_sanity": os.environ.get("R2E_W_SIZE"), "file_targeting": os.environ.get("R2E_W_FILE"), "region_overlap": os.environ.get("R2E_W_REGION"), "similarity": os.environ.get("R2E_W_SIM"), "llm_judge": os.environ.get("R2E_W_JUDGE"), } out = dict(_DEFAULT_WEIGHTS) for k, v in overrides.items(): if v is None: continue try: value = float(v) if math.isfinite(value) and value >= 0: out[k] = value except (TypeError, ValueError): continue return out
def _judge_config_from_env() -> tuple[str, str, str | None]: """``(api_key, model, endpoint)`` for the judge, from the verifier env.
With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a self-hosted server won't have Haiku): when unset, ``model`` comes back as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of calling out. Without an endpoint the default Anthropic route is unchanged. """ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None model = os.environ.get("R2E_JUDGE_MODEL", "").strip() if endpoint: api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY return api_key, model, endpoint return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("oracle") parser.add_argument("predicted") parser.add_argument("instruction") parser.add_argument("--out-dir", default="/logs/verifier") args = parser.parse_args(argv) os.makedirs(args.out_dir, exist_ok=True) # This run is the only authority on the reward: an earlier or planted # reward file must not stand if this evaluation ends up ungraded. for name in ("reward.txt", "reward.json"): try: os.unlink(os.path.join(args.out_dir, name)) except FileNotFoundError: pass oracle = _read_or_empty(args.oracle) try: oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES except OSError: oversized = False predicted = "" if oversized else _read_or_empty(args.predicted) if oversized or predicted_too_large(oracle, predicted): breakdown = { "final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": False, "predicted_status": "predicted_too_large", } _write_outputs(args.out_dir, 0.0, breakdown) return 0 instruction = _read_or_empty(args.instruction) api_key, judge_model, judge_endpoint = _judge_config_from_env()
fv = format_valid(predicted) ss = size_sanity(oracle, predicted) ft = file_targeting(oracle, predicted) ro = region_overlap(oracle, predicted) sim = similarity(oracle, predicted) weights = _read_weights_from_env() if weights["llm_judge"] <= 0: judge_score, judge_status = None, "disabled" else: judge_score, judge_status = llm_judge( instruction=instruction, oracle=oracle, predicted=predicted, api_key=api_key, model=judge_model, endpoint=judge_endpoint, )
components: dict[str, float | None] = { "format_valid": fv, "size_sanity": ss, "file_targeting": ft, "region_overlap": ro, "similarity": sim, "llm_judge": judge_score, } final = combine(components, weights) final = max(0.0, min(1.0, final))
# Hard cap on catastrophic size mismatches. Without this, a charitable # judge can inflate the reward on patches that are dramatically the # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge # was lenient at 0.25 despite the patch being a near-no-op vs a # 500-line oracle). The cap kicks in only at the extremes. if ss < _CATASTROPHIC_SIZE_THRESHOLD: final = min(final, _CATASTROPHIC_SIZE_CAP)
status = evaluation_status(judge_score, judge_status) breakdown = { # No reward exists for an ungraded evaluation: null, not a placeholder 0. "final_reward": round(final, 6) if status == "graded" else None, "evaluation_status": status, "eval_trustworthy": judge_score is not None, "diagnostic_similarity": round( _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), 6, ), "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, "weights": {k: round(v, 6) for k, v in weights.items()}, "judge_model": judge_model if judge_status == "ok" else None, "judge_endpoint": judge_endpoint, "judge_status": judge_status, }
_write_outputs(args.out_dir, final, breakdown) return 0
def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: # An ungraded evaluation writes no reward file. Harbor then raises # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout # instead of training on a 0. Harbor's job mean and pass@k still count the # trial as 0, so evaluation stays fail-closed. if breakdown["evaluation_status"] == "graded": with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: f.write(f"{final:.6f}\n") # Harbor's `reward.json` must be a flat map of floats/ints (spec, see # <https://harborframework.com/docs/tasks>); our breakdown carries nested # dicts, judge strings, and status strings, so it goes to the sidecar the # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) # for `_pr_runtime_verifier.py`. with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: json.dump(breakdown, f, indent=2)
# Also print to stdout so harbor's log captures the breakdown print(json.dumps(breakdown, indent=2))
def _read_or_empty(path: str) -> str: try: with open(path, encoding="utf-8") as f: return f.read() except (OSError, UnicodeDecodeError): return ""
if __name__ == "__main__": sys.exit(main())
__all__ = [ "combine", "file_paths", "file_targeting", "format_valid", "hunk_ranges", "llm_judge", "main", "predicted_too_large", "region_overlap", "similarity", "size_sanity",]12345678910111213141516171819202122232425262728293031323334353637# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.# Agent-agnostic: the agent (claude-code / openhands / codex / etc.)# installs itself at run time via its harbor adapter. We only ship# the source repo — the oracle + verifier arrive at verify time via# tests/, never baked into the agent's image.FROM python:3.12-slimARG GITHUB_TOKEN=RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/*RUN git config --global --add safe.directory /workspace \ && git config --global init.defaultBranch main \ && git config --global advice.detachedHead falseRUN if [ -n "$GITHUB_TOKEN" ]; then \ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \ else \ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \ fi \ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.gitWORKDIR /workspaceRUN git fetch --depth 1 origin e1e1f97053a8332cdefae12e5f61d4696b0d940a 2>/dev/null \ || git fetch --unshallow origin 2>/dev/null || trueRUN git reset --hard e1e1f97053a8332cdefae12e5f61d4696b0d940a \ && git clean -fdx -e .venv -e venv -e __pycache__RUN git checkout -q -B base e1e1f97053a8332cdefae12e5f61d4696b0d940a \ && git remote remove origin 2>/dev/null || trueRUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ && git reflog expire --expire=now --all 2>/dev/null || true \ && git gc --prune=now 2>/dev/null || trueRUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ fi1234567891011121314151617181920212223242526272829303132333435363738394041# Issue
**Title:** chore(deps): update dependency ubuntu to v26
## Description
This PR contains the following updates:
| Package | Type | Update | Change ||---|---|---|---|| [ubuntu](https://redirect.github.com/actions/runner-images) | github-runner | major | `24.04` → `26.04` |
---
### Configuration
📅 **Schedule**: (UTC)
- Branch creation - At any time (no schedule defined)- Automerge - At any time (no schedule defined)
🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
♻ **Rebasing**: Never, or you tick the rebase/retry checkbox.
🔕 **Ignore**: Close this PR and you won't be reminded about this update again.
---
- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
---
This PR has been generated by [Mend Renovate CLI](https://redirect.github.com/renovatebot/renovate).<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMTMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIxMy4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.12345678910111213141516171819202122diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 4ccf421b..133f55cc 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -448,7 +448,7 @@ jobs: kickoff_gamemode_news: name: Build Game Mode Announcements- runs-on: ubuntu-24.04+ runs-on: ubuntu-26.04 needs: [generate_release] if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' steps:@@ -472,7 +472,7 @@ jobs: client-payload: '{"branch": "${{ steps.get-target.outputs.target }}"}' kickoff_bazzite_dx:- runs-on: ubuntu-24.04+ runs-on: ubuntu-26.04 needs: [generate_release] if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) steps:123456#!/bin/bashset -euxo pipefailcd /workspacegit config --global --add safe.directory /workspacePATCH="$(dirname "$0")/patch.diff"git apply --verbose --reject "$PATCH"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768version = "1.0"
[task]name = "trending/ublue-os__bazzite-6231"description = "chore(deps): update dependency ubuntu to v26"
[metadata]difficulty = "easy"category = "bugfix"keywords = [ "bazzite", "pr_diff",]
[metadata.repo2env]pipeline = "pr_diff"pipeline_version = "0.3.0"repo = "ublue-os/bazzite"ref = "e1e1f97053a8332cdefae12e5f61d4696b0d940a"reference = "https://github.com/ublue-os/bazzite/pull/6231"source_access = "auto"built_at = "2026-11-16T16:09:50.976118+00:00"reward_kinds = [ "diff_similarity",]spec_version = "0.2.0"content_hash = "sha256:8735496b520936c010c54c743fefb8c0fe794be8765daaa74fe581933c430a7f"
[metadata.repo2env.pr_diff]pr_merged_at = "2026-11-05T06:26:34Z"diff_format = "unified"context_files = [ ".github/workflows/build.yml",]bootstrap_image = "python:3.12-slim"
[metadata.repo2env.reward_calibration]baseline_reward = 0.0loc_changed = 4difficulty = "trivial"
[metadata.repo2env.evaluation]schema_version = "1"status = "unverified"stage = "generation"reason_codes = [ "validation_not_run",]detail = "Generated task; validation has not been established."provenance = "unknown"evidence = []
[metadata.repo2env.reproducibility]mode = "inline_dockerfile"image_ref = "python:3.12-slim"image_tag = "python:3.12-slim"image_visibility = "public"pushed_at = "2026-11-16T16:20:03.587819+00:00"pushed_by = "scalingX"inline_recipe_sha256 = "sha256:e1c72bf41c74f9342ae165a509f4de0c95f0f2f3c9693a7cc559c4b7390192fa"inline_recipe_lines = 37inline_recipe_source = "user_dockerfile"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 300.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Standalone PR-diff capture without executing workspace Git configuration.
The emitted task uses a regular clone with a pinned base commit. Only itsobject store is read: refs, index, config, hooks and replacement refs are notused. This is a configuration boundary, not a sandbox for a malicious processthat can modify the verifier, binaries or object store while capture runs."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
def capture(workspace: Path, base_commit: str) -> bytes: """Capture tracked and new files through a fresh private Git index.""" if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): raise ValueError("Expected the task's pinned SHA-1 base commit") objects = workspace.resolve() / ".git" / "objects" if not objects.is_dir(): raise ValueError("The task's cloned Git object store is missing") git = shutil.which("git", path=os.defpath) if git is None: raise FileNotFoundError("System git is unavailable") with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: private = Path(temporary) # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, # system/global includes, user attributes, templates or credential env. env = { "PATH": os.defpath, "HOME": temporary, "XDG_CONFIG_HOME": temporary, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", } subprocess.run( [git, "init", "--quiet", "--template=", str(private / "repository")], env=env, cwd=private, check=True, capture_output=True, timeout=60, ) env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) command = [ git, f"--git-dir={private / 'repository/.git'}", f"--work-tree={workspace.resolve()}", ]
def run(*args: str) -> bytes: return subprocess.run( [*command, *args], env=env, cwd=workspace, check=True, capture_output=True, timeout=60, ).stdout
run("read-tree", f"{base_commit}^{{tree}}") # All filter drivers are undefined in the private configuration. The # workspace's clean filters, fsmonitor and hooks cannot be invoked. run("add", "--all", "--", ".") return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("workspace", type=Path) parser.add_argument("base_commit") args = parser.parse_args(argv) try: patch = capture(args.workspace, args.base_commit) except (OSError, ValueError, subprocess.SubprocessError) as exc: # Do not echo child stderr: it may contain workspace-controlled data. sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") return 1 sys.stdout.buffer.write(patch) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738394041# Issue
**Title:** chore(deps): update dependency ubuntu to v26
## Description
This PR contains the following updates:
| Package | Type | Update | Change ||---|---|---|---|| [ubuntu](https://redirect.github.com/actions/runner-images) | github-runner | major | `24.04` → `26.04` |
---
### Configuration
📅 **Schedule**: (UTC)
- Branch creation - At any time (no schedule defined)- Automerge - At any time (no schedule defined)
🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
♻ **Rebasing**: Never, or you tick the rebase/retry checkbox.
🔕 **Ignore**: Close this PR and you won't be reminded about this update again.
---
- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
---
This PR has been generated by [Mend Renovate CLI](https://redirect.github.com/renovatebot/renovate).<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMTMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIxMy4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1e1f97053a8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.12345678910111213141516171819202122diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 4ccf421b..133f55cc 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -448,7 +448,7 @@ jobs: kickoff_gamemode_news: name: Build Game Mode Announcements- runs-on: ubuntu-24.04+ runs-on: ubuntu-26.04 needs: [generate_release] if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' steps:@@ -472,7 +472,7 @@ jobs: client-payload: '{"branch": "${{ steps.get-target.outputs.target }}"}' kickoff_bazzite_dx:- runs-on: ubuntu-24.04+ runs-on: ubuntu-26.04 needs: [generate_release] if: github.repository == 'ublue-os/bazzite' && github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) steps:12345678910111213141516171819202122232425#!/bin/bashset -uxo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd /workspacemkdir -p /logs/verifierrm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.jsonCAPTURE_DIR="$(mktemp -d)" || exit 1trap 'rm -rf -- "$CAPTURE_DIR"' EXITif ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e1e1f97053a8332cdefae12e5f61d4696b0d940a > "$CAPTURE_DIR/predicted.patch"; then echo "0.0" > /logs/verifier/reward.txt printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json exit 0firm -f /logs/verifier/predicted.patchcp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch: 'START_VERIFY_OUTPUT'if ! python3 -I "$SCRIPT_DIR/verifier.py" \ "$SCRIPT_DIR/oracle.patch" \ "$CAPTURE_DIR/predicted.patch" \ "$SCRIPT_DIR/instruction.md"; then rm -f /logs/verifier/reward.txt /logs/verifier/reward.json printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.jsonfi: 'END_VERIFY_OUTPUT'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""In-container verifier for pr_diff tasks (6-component reward).
This module is the **standalone verifier** that runs inside the task'sDocker container, NOT a helper used at generation time. Generation emitsits source as ``tests/verifier.py``. Harbor delivers it at verify time,and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
format_valid (0 or 1) — predicted parses as a unified diff (guard) size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) catches "rampage through the codebase" file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — symmetric penalty over-punishes extras) region_overlap ([0, 1]) — predicted hunks overlap oracle hunks (strongest spatial-localization signal) similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only (no free credit for context lines) llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" Anthropic Haiku by default; any OpenAI- compatible server via ``R2E_JUDGE_ENDPOINT``. null when the judge is unavailable (no key or model, network, unreadable reply) → ungraded, no reward file; a reply without a valid score (refusal, content filter, empty, no "score") → a graded 0
Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned fromthe original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-taskpilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).Override per-task via ``task.toml.metadata`` or per-run via env vars``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so theyreach the verifier container).
Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatibleserver (vLLM, Ollama, a gateway) and switches the request to``<endpoint>/chat/completions`` with a bearer token from``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hostedservers ignore it. ``ANTHROPIC_API_KEY`` is only read on the defaultroute and is never sent to a custom endpoint.
Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops acharitable judge from inflating scores on wildly wrong-sized patches).
Outputs (mirrors `_pr_runtime_verifier.py` after #75): /logs/verifier/reward.txt — single float (Harbor reads this); graded runs only /logs/verifier/reward-details.json — full component breakdown + status (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- only, so the breakdown goes to the `reward-details.json` sidecar which Harbor renders under Verifier Logs → Rewards)
Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,``urllib``, ``sys``. The same module is imported by the unit testsunder ``tests/test_pr_diff_verifier.py`` so the in-container behaviorstays in lockstep with what we test."""
from __future__ import annotations
import argparseimport difflibimport jsonimport mathimport osimport reimport sysimport urllib.errorimport urllib.request
# ---------------------------------------------------------------------------# Parsing helpers (shared by multiple components)# ---------------------------------------------------------------------------
_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")_INDEX_RE = re.compile(r"^index ")
def file_paths(diff: str) -> set[str]: """Return the set of ``b/<path>`` paths touched by a unified diff.""" paths: set[str] = set() for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: paths.add(m.group(2)) return paths
def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: """For each touched file, return list of (start_line, end_line) ranges on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). """ out: dict[str, list[tuple[int, int]]] = {} current_file: str | None = None for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: current_file = m.group(2) out.setdefault(current_file, []) continue m = _HUNK_HEADER_RE.match(line) if m and current_file is not None: new_start = int(m.group(3)) new_count = int(m.group(4) or "1") end = new_start + max(new_count - 1, 0) out[current_file].append((new_start, end)) return out
def _normalize_changes_only(diff: str) -> list[str]: """Return the +/- lines (the actual changes) for similarity scoring.
Drops: - ``diff --git`` / ``index abc..def`` metadata - ``@@ ... @@`` hunk markers (volatile line numbers) - context lines (no +/- prefix) — these are unchanged code, scoring them inflates similarity for trivial patches Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity stays in the comparison; normalizes off the tab+timestamp suffix git sometimes appends. """ out: list[str] = [] for line in diff.splitlines(): if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): continue if _HUNK_HEADER_RE.match(line): continue if _FILE_MARKER_RE.match(line): out.append(line.split("\t")[0].strip()) continue # +/- lines (actual changes) if line.startswith("+") or line.startswith("-"): out.append(line) return out
# ---------------------------------------------------------------------------# Reward components# ---------------------------------------------------------------------------
def format_valid(predicted: str) -> float: """1.0 if the predicted text looks like a unified diff; else 0.0.
Requires both a ``diff --git`` header and at least one real +/- line (not the ``---`` / ``+++`` file-marker lines). """ if not predicted.strip(): return 0.0 has_header = False has_change = False for line in predicted.splitlines(): if _DIFF_HEADER_RE.match(line): has_header = True elif (line.startswith("+") or line.startswith("-")) and not line.startswith( ("+++ ", "--- ") ): has_change = True if has_header and has_change: return 1.0 return 0.0
def file_targeting(oracle: str, predicted: str) -> float: """F1 over the changed-file sets.
Why F1 instead of Jaccard: - Missing an oracle file (FN) is a *big* failure. - Touching one unrelated extra file (FP) is a small one. - Jaccard punishes both equally, which over-penalizes the agent for any extra exploration. - F1 weights TP twice, giving partial credit when the agent finds most-but-not-all of the oracle files even with some noise.
Returns 1.0 if both sides touch zero files (degenerate). """ o = file_paths(oracle) p = file_paths(predicted) if not o and not p: return 1.0 tp = len(o & p) fn = len(o - p) fp = len(p - o) if tp == 0: return 0.0 # F1 = 2·TP / (2·TP + FN + FP) return (2 * tp) / (2 * tp + fn + fp)
def _count_loc_changes(diff: str) -> int: """Number of real +/- lines (excluding file-marker lines).""" n = 0 for line in diff.splitlines(): if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): n += 1 return n
def size_sanity(oracle: str, predicted: str) -> float: """Penalize predicted patches that are wildly larger / smaller than the oracle.
Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
This is the "don't rampage through the codebase" guard — a 200-line diff for a 3-line oracle scores ~0.015 here even if every other component looks OK. """ o_loc = _count_loc_changes(oracle) p_loc = _count_loc_changes(predicted) if o_loc == 0 and p_loc == 0: return 1.0 if o_loc == 0 or p_loc == 0: return 0.0 return min(o_loc, p_loc) / max(o_loc, p_loc)
def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: """For each oracle hunk, did the predicted diff edit a line within ``slack_lines`` of that hunk in the same file?
Returns the fraction of oracle hunks that have at least one matching predicted hunk. ``slack_lines`` tolerates slight line-number drift when git diff renders the predicted hunk at a different offset. """ o_ranges = hunk_ranges(oracle) p_ranges = hunk_ranges(predicted) total = sum(len(v) for v in o_ranges.values()) if total == 0: return 1.0 # oracle has no hunks (degenerate) matched = 0 for fname, ranges in o_ranges.items(): p_in_file = p_ranges.get(fname, []) for o_start, o_end in ranges: for p_start, p_end in p_in_file: # Interval overlap with slack — max(starts) <= min(ends) + slack if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: matched += 1 break return matched / total
def similarity(oracle: str, predicted: str) -> float: """SequenceMatcher ratio over +/- lines only.
No free credit for context lines — fixes the v0.8.1 inflation where a one-line fix scored ~0.7 just because the 3 context lines on either side were "matched". """ if not predicted.strip(): return 0.0 o = _normalize_changes_only(oracle) p = _normalize_changes_only(predicted) if not o: return 0.0 # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can # run the verifier past Harbor's timeout. Above this many line pairs, # fall back to difflib's popular-element heuristic, which stays fast. exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
_SIMILARITY_EXACT_PAIRS = 400_000
# A predicted patch over 10x the oracle's changed lines is already a# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a# patch is a graded 0 instead of being scored, so one huge file can't slow# the verifier past its timeout and turn a failing episode into a dropped,# ungraded one. The byte cap stops it from being read at all._MAX_PREDICTED_FACTOR = 10_MAX_PREDICTED_FLOOR_LOC = 1_000_MAX_PREDICTED_BYTES = 16 * 1024 * 1024
def predicted_too_large(oracle: str, predicted: str) -> bool: """Whether the predicted patch is too large to score (a graded 0).""" limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) return _count_loc_changes(predicted) > limit
# ---------------------------------------------------------------------------# LLM-as-judge (Anthropic Messages API, stdlib urllib)# ---------------------------------------------------------------------------
_JUDGE_PROMPT = ( "You are scoring a code-fix patch on whether it logically addresses the " "described issue. Output a single JSON object: " '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' "DO NOT use the oracle to grade. Score on:\n" " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" " - Is the change direction consistent with what the issue describes?\n" " - Is it a real attempt (not boilerplate, not no-op)?\n\n" "Issue:\n{instruction}\n\n" "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" "{oracle}\n\n" "Predicted:\n{predicted}\n\n" "Return ONLY the JSON object.")
_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses._PLACEHOLDER_API_KEY = "EMPTY"
def llm_judge( *, instruction: str, oracle: str, predicted: str, api_key: str, model: str = _DEFAULT_JUDGE_MODEL, timeout: int = 60, endpoint: str | None = None,) -> tuple[float | None, str]: """Return ``(score, status)``.
``score`` is a float in [0, 1] on success, ``None`` on failure. ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. ``output_limit`` means the judge exhausted its configured token budget (ungraded, even if a partial answer contains a score). ``parse`` means the provider's body isn't JSON or has the wrong shape (ungraded); a reply with no usable text (refusal, content filter, empty) or no valid score is ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never increases the other weights.
``endpoint`` — base URL of an OpenAI-compatible server. When set, the request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a bearer token, at temperature 0, and ``model`` must be given explicitly; otherwise it goes to Anthropic's Messages API unchanged. """ if not api_key: return None, "no_api_key" if endpoint and not model: return None, "no_judge_model" if not predicted.strip(): return 0.0, "empty_predicted"
# Truncate hard so we don't blow up the prompt for big diffs prompt = _JUDGE_PROMPT.format( instruction=instruction[:4000], oracle=oracle[:4000], predicted=predicted[:4000], ) payload: dict = { "model": model, "max_tokens": 200, "messages": [{"role": "user", "content": prompt}], } if endpoint: # Small self-hosted models are noisy judges at their default sampling # temperature (same input scoring 0.0 one call and 1.0 the next); pin # them to greedy. The Anthropic route keeps its defaults — the weights # were calibrated against them. payload["temperature"] = 0 url = endpoint.rstrip("/") + "/chat/completions" headers = { "authorization": f"Bearer {api_key}", "content-type": "application/json", } else: url = _ANTHROPIC_MESSAGES_URL headers = { "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): return None, "network"
try: response = json.loads(raw) except json.JSONDecodeError: return None, "parse" # Provider-reported truncation is a grader capacity failure, not evidence # that the submitted patch is wrong. Reasoning models can spend the entire # output budget before producing visible text. Never grade a partial score. if isinstance(response, dict): choices = response.get("choices") if endpoint: if ( isinstance(choices, list) and choices and isinstance(choices[0], dict) and choices[0].get("finish_reason") == "length" ): return None, "output_limit" elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: return None, "output_limit" text = _judge_text(response, openai_compatible=bool(endpoint)) if text is None: return None, "parse"
# Pull the first JSON object out of the model's response m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) if not m: return None, "missing_score" try: obj = json.loads(m.group(0)) score = obj.get("score") except (json.JSONDecodeError, ValueError, TypeError): return None, "missing_score" if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): return None, "invalid_score" return float(score), "ok"
def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
A refusal or a content filter is a well-formed reply with no usable text. The agent's patch is in the prompt, so it can provoke one: that is ``""``, which grades 0, not ``None``, which leaves the run ungraded.
Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and ``content`` empty or holding partial text to discard. OpenAI-compatible: ``message.content`` is null with a ``refusal`` string or ``finish_reason: "content_filter"``. """ if not isinstance(payload, dict): return None if openai_compatible: choices = payload.get("choices") if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): return None message = choices[0].get("message") if not isinstance(message, dict): return None if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": return "" content = message.get("content") if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): # content parts return "".join( part.get("text", "") for part in content if isinstance(part, dict) and isinstance(part.get("text", ""), str) ) return None content = payload.get("content") if not isinstance(content, list): return None if payload.get("stop_reason") == "refusal": return "" return "".join( block["text"] for block in content if isinstance(block, dict) and block.get("type", "text") == "text" and isinstance(block.get("text"), str) )
# ---------------------------------------------------------------------------# Combination# ---------------------------------------------------------------------------
# Judge replies the agent can provoke: its patch text is part of the judge# prompt, so it can steer the answer away from a valid score. These are a# graded 0. An unreadable provider envelope (`parse`), missing configuration,# a disabled judge, transport errors and an exhausted judge output budget leave# the evaluation ungraded. Truncation alone cannot establish an incorrect patch._JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
def evaluation_status(judge_score: float | None, judge_status: str) -> str: """`graded` when the judge scored or the agent can have caused its failure.""" if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: return "graded" return "ungraded"
def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: """Combine declared components, requiring a positively weighted judge.
Without a judge score the result is 0. ``main`` records it as a graded 0 when the agent can have caused the judge failure, and otherwise writes no reward file, so Harbor reports the trial as VERIFIER_FAILED. """ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: return 0.0 if any(w > 0 and components.get(k) is None for k, w in weights.items()): return 0.0 return _weighted_mean(components, weights)
def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] if not available: return 0.0 # Relative weights need not sum to one. Scale first so large finite # overrides cannot overflow the numerator or denominator into NaN. scale = max(w for _, w in available) normalized = [(k, w / scale) for k, w in available] return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
# ---------------------------------------------------------------------------# Entry point (invoked by tests/test.sh inside the container)# ---------------------------------------------------------------------------
# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer# analysis grounded in per-task component data):## - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero# discriminative signal — its 0.05 weight was pure dead weight.# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.# Carrying both at 0.20 double-counts positional accuracy and# additionally penalizes legitimate alternative implementations.# - llm_judge → 0.50: only component capturing semantic correctness# independent of textual form; diverges informatively from# similarity on cases like tokenizers (judge=0.72, sim=0.08).# - region_overlap stays 0.20: strongest spatial-localization signal.# - file_targeting → 0.12: leading indicator, less correlated with the# rest than region/similarity are with each other.# - size_sanity → 0.08: useful outlier detector for catastrophic# over/under-generation (prettier=0.01, serde=0.08).## Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00._DEFAULT_WEIGHTS = { "format_valid": 0.00, "size_sanity": 0.08, "file_targeting": 0.12, "region_overlap": 0.20, "similarity": 0.10, "llm_judge": 0.50,}
# Hard cap: when size_sanity < this threshold, clamp final reward to# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating# the score on patches that are wildly the wrong size (catastrophic# over- or under-generation)._CATASTROPHIC_SIZE_THRESHOLD = 0.10_CATASTROPHIC_SIZE_CAP = 0.40
def _read_weights_from_env() -> dict[str, float]: """Override defaults via R2E_W_* env vars (set in container by harbor).""" overrides = { "format_valid": os.environ.get("R2E_W_FORMAT"), "size_sanity": os.environ.get("R2E_W_SIZE"), "file_targeting": os.environ.get("R2E_W_FILE"), "region_overlap": os.environ.get("R2E_W_REGION"), "similarity": os.environ.get("R2E_W_SIM"), "llm_judge": os.environ.get("R2E_W_JUDGE"), } out = dict(_DEFAULT_WEIGHTS) for k, v in overrides.items(): if v is None: continue try: value = float(v) if math.isfinite(value) and value >= 0: out[k] = value except (TypeError, ValueError): continue return out
def _judge_config_from_env() -> tuple[str, str, str | None]: """``(api_key, model, endpoint)`` for the judge, from the verifier env.
With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a self-hosted server won't have Haiku): when unset, ``model`` comes back as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of calling out. Without an endpoint the default Anthropic route is unchanged. """ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None model = os.environ.get("R2E_JUDGE_MODEL", "").strip() if endpoint: api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY return api_key, model, endpoint return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("oracle") parser.add_argument("predicted") parser.add_argument("instruction") parser.add_argument("--out-dir", default="/logs/verifier") args = parser.parse_args(argv) os.makedirs(args.out_dir, exist_ok=True) # This run is the only authority on the reward: an earlier or planted # reward file must not stand if this evaluation ends up ungraded. for name in ("reward.txt", "reward.json"): try: os.unlink(os.path.join(args.out_dir, name)) except FileNotFoundError: pass oracle = _read_or_empty(args.oracle) try: oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES except OSError: oversized = False predicted = "" if oversized else _read_or_empty(args.predicted) if oversized or predicted_too_large(oracle, predicted): breakdown = { "final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": False, "predicted_status": "predicted_too_large", } _write_outputs(args.out_dir, 0.0, breakdown) return 0 instruction = _read_or_empty(args.instruction) api_key, judge_model, judge_endpoint = _judge_config_from_env()
fv = format_valid(predicted) ss = size_sanity(oracle, predicted) ft = file_targeting(oracle, predicted) ro = region_overlap(oracle, predicted) sim = similarity(oracle, predicted) weights = _read_weights_from_env() if weights["llm_judge"] <= 0: judge_score, judge_status = None, "disabled" else: judge_score, judge_status = llm_judge( instruction=instruction, oracle=oracle, predicted=predicted, api_key=api_key, model=judge_model, endpoint=judge_endpoint, )
components: dict[str, float | None] = { "format_valid": fv, "size_sanity": ss, "file_targeting": ft, "region_overlap": ro, "similarity": sim, "llm_judge": judge_score, } final = combine(components, weights) final = max(0.0, min(1.0, final))
# Hard cap on catastrophic size mismatches. Without this, a charitable # judge can inflate the reward on patches that are dramatically the # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge # was lenient at 0.25 despite the patch being a near-no-op vs a # 500-line oracle). The cap kicks in only at the extremes. if ss < _CATASTROPHIC_SIZE_THRESHOLD: final = min(final, _CATASTROPHIC_SIZE_CAP)
status = evaluation_status(judge_score, judge_status) breakdown = { # No reward exists for an ungraded evaluation: null, not a placeholder 0. "final_reward": round(final, 6) if status == "graded" else None, "evaluation_status": status, "eval_trustworthy": judge_score is not None, "diagnostic_similarity": round( _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), 6, ), "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, "weights": {k: round(v, 6) for k, v in weights.items()}, "judge_model": judge_model if judge_status == "ok" else None, "judge_endpoint": judge_endpoint, "judge_status": judge_status, }
_write_outputs(args.out_dir, final, breakdown) return 0
def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: # An ungraded evaluation writes no reward file. Harbor then raises # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout # instead of training on a 0. Harbor's job mean and pass@k still count the # trial as 0, so evaluation stays fail-closed. if breakdown["evaluation_status"] == "graded": with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: f.write(f"{final:.6f}\n") # Harbor's `reward.json` must be a flat map of floats/ints (spec, see # <https://harborframework.com/docs/tasks>); our breakdown carries nested # dicts, judge strings, and status strings, so it goes to the sidecar the # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) # for `_pr_runtime_verifier.py`. with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: json.dump(breakdown, f, indent=2)
# Also print to stdout so harbor's log captures the breakdown print(json.dumps(breakdown, indent=2))
def _read_or_empty(path: str) -> str: try: with open(path, encoding="utf-8") as f: return f.read() except (OSError, UnicodeDecodeError): return ""
if __name__ == "__main__": sys.exit(main())
__all__ = [ "combine", "file_paths", "file_targeting", "format_valid", "hunk_ranges", "llm_judge", "main", "predicted_too_large", "region_overlap", "similarity", "size_sanity",]12345678910111213141516171819202122232425262728293031323334353637# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.# Agent-agnostic: the agent (claude-code / openhands / codex / etc.)# installs itself at run time via its harbor adapter. We only ship# the source repo — the oracle + verifier arrive at verify time via# tests/, never baked into the agent's image.FROM python:3.12-slimARG GITHUB_TOKEN=RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/*RUN git config --global --add safe.directory /workspace \ && git config --global init.defaultBranch main \ && git config --global advice.detachedHead falseRUN if [ -n "$GITHUB_TOKEN" ]; then \ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \ else \ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \ fi \ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.gitWORKDIR /workspaceRUN git fetch --depth 1 origin 64fa640520bcbd038abb2cfdfdf725f87e7a717c 2>/dev/null \ || git fetch --unshallow origin 2>/dev/null || trueRUN git reset --hard 64fa640520bcbd038abb2cfdfdf725f87e7a717c \ && git clean -fdx -e .venv -e venv -e __pycache__RUN git checkout -q -B base 64fa640520bcbd038abb2cfdfdf725f87e7a717c \ && git remote remove origin 2>/dev/null || trueRUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ && git reflog expire --expire=now --all 2>/dev/null || true \ && git gc --prune=now 2>/dev/null || trueRUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ fi12345678910111213141516171819202122232425262728293031# Issue
**Title:** fix(steam-firstrun): show the Portuguese message for pt_BR locales
## Description
`bazzite-steam-firstrun` reduces the locale to its language part:
```bashlang=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)```
For `LANG=pt_BR.UTF-8` this gives `pt`, so the `"pt_BR"` case added in #4750 never matched and Brazilian users got the English message. This PR changes the case to `"pt"`.
Side effect: `pt_PT` users now get this (Brazilian Portuguese) message instead of English. `ntfs-exfat-monitor-script` already uses a single `"pt"` case in the same way.
Tested by running the whole script with different `LANG` values, with `kdialog` and `curl` replaced by stubs that print what would be shown:
| `LANG` | Before | After ||---|---|---|| `pt_BR.UTF-8` | English | Portuguese || `pt_PT.UTF-8` | English | Portuguese || `uk_UA.UTF-8`, `de_DE.UTF-8`, `en_US.UTF-8`, `C.UTF-8` | unchanged | unchanged |
ShellCheck reports the same three pre-existing warnings before and after the change.
Written with AI assistance.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64fa640520bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415diff --git a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrunindex f1c4fb93..bcefb5a8 100755--- a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun+++ b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun@@ -36,8 +36,8 @@ case $lang in "it") info_text=("Steam è in fase di download. Attendere prego. Il download del client Steam potrebbe richiedere alcuni minuti.") ;;-#brazilian portuguese- "pt_BR")+#portuguese (brazilian translation)+ "pt") info_text=("O Steam está sendo executado pela primeira vez. Por favor, aguarde. O download do cliente Steam pode levar alguns minutos.") ;; #ukrainian123456#!/bin/bashset -euxo pipefailcd /workspacegit config --global --add safe.directory /workspacePATCH="$(dirname "$0")/patch.diff"git apply --verbose --reject "$PATCH"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768version = "1.0"
[task]name = "trending/ublue-os__bazzite-6232"description = "fix(steam-firstrun): show the Portuguese message for pt_BR locales"
[metadata]difficulty = "easy"category = "bugfix"keywords = [ "bazzite", "pr_diff",]
[metadata.repo2env]pipeline = "pr_diff"pipeline_version = "0.3.0"repo = "ublue-os/bazzite"ref = "64fa640520bcbd038abb2cfdfdf725f87e7a717c"reference = "https://github.com/ublue-os/bazzite/pull/6232"source_access = "auto"built_at = "2026-11-16T16:09:50.974571+00:00"reward_kinds = [ "diff_similarity",]spec_version = "0.2.0"content_hash = "sha256:1d7d922c5959df60cd9f083bb5a973049f4fe35c7e7b7f2929bd637b36b64f4a"
[metadata.repo2env.pr_diff]pr_merged_at = "2026-11-04T19:49:31Z"diff_format = "unified"context_files = [ "system_files/desktop/shared/usr/bin/bazzite-steam-firstrun",]bootstrap_image = "python:3.12-slim"
[metadata.repo2env.reward_calibration]baseline_reward = 0.0loc_changed = 4difficulty = "trivial"
[metadata.repo2env.evaluation]schema_version = "1"status = "unverified"stage = "generation"reason_codes = [ "validation_not_run",]detail = "Generated task; validation has not been established."provenance = "unknown"evidence = []
[metadata.repo2env.reproducibility]mode = "inline_dockerfile"image_ref = "python:3.12-slim"image_tag = "python:3.12-slim"image_visibility = "public"pushed_at = "2026-11-16T16:20:03.588387+00:00"pushed_by = "scalingX"inline_recipe_sha256 = "sha256:8efe941f13d1b53d0d90fb06826c16145b19741305cd69c07df8ef0b6f35feb8"inline_recipe_lines = 37inline_recipe_source = "user_dockerfile"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 300.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Standalone PR-diff capture without executing workspace Git configuration.
The emitted task uses a regular clone with a pinned base commit. Only itsobject store is read: refs, index, config, hooks and replacement refs are notused. This is a configuration boundary, not a sandbox for a malicious processthat can modify the verifier, binaries or object store while capture runs."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
def capture(workspace: Path, base_commit: str) -> bytes: """Capture tracked and new files through a fresh private Git index.""" if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): raise ValueError("Expected the task's pinned SHA-1 base commit") objects = workspace.resolve() / ".git" / "objects" if not objects.is_dir(): raise ValueError("The task's cloned Git object store is missing") git = shutil.which("git", path=os.defpath) if git is None: raise FileNotFoundError("System git is unavailable") with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: private = Path(temporary) # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, # system/global includes, user attributes, templates or credential env. env = { "PATH": os.defpath, "HOME": temporary, "XDG_CONFIG_HOME": temporary, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", } subprocess.run( [git, "init", "--quiet", "--template=", str(private / "repository")], env=env, cwd=private, check=True, capture_output=True, timeout=60, ) env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) command = [ git, f"--git-dir={private / 'repository/.git'}", f"--work-tree={workspace.resolve()}", ]
def run(*args: str) -> bytes: return subprocess.run( [*command, *args], env=env, cwd=workspace, check=True, capture_output=True, timeout=60, ).stdout
run("read-tree", f"{base_commit}^{{tree}}") # All filter drivers are undefined in the private configuration. The # workspace's clean filters, fsmonitor and hooks cannot be invoked. run("add", "--all", "--", ".") return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("workspace", type=Path) parser.add_argument("base_commit") args = parser.parse_args(argv) try: patch = capture(args.workspace, args.base_commit) except (OSError, ValueError, subprocess.SubprocessError) as exc: # Do not echo child stderr: it may contain workspace-controlled data. sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") return 1 sys.stdout.buffer.write(patch) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031# Issue
**Title:** fix(steam-firstrun): show the Portuguese message for pt_BR locales
## Description
`bazzite-steam-firstrun` reduces the locale to its language part:
```bashlang=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1)```
For `LANG=pt_BR.UTF-8` this gives `pt`, so the `"pt_BR"` case added in #4750 never matched and Brazilian users got the English message. This PR changes the case to `"pt"`.
Side effect: `pt_PT` users now get this (Brazilian Portuguese) message instead of English. `ntfs-exfat-monitor-script` already uses a single `"pt"` case in the same way.
Tested by running the whole script with different `LANG` values, with `kdialog` and `curl` replaced by stubs that print what would be shown:
| `LANG` | Before | After ||---|---|---|| `pt_BR.UTF-8` | English | Portuguese || `pt_PT.UTF-8` | English | Portuguese || `uk_UA.UTF-8`, `de_DE.UTF-8`, `en_US.UTF-8`, `C.UTF-8` | unchanged | unchanged |
ShellCheck reports the same three pre-existing warnings before and after the change.
Written with AI assistance.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64fa640520bc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415diff --git a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrunindex f1c4fb93..bcefb5a8 100755--- a/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun+++ b/system_files/desktop/shared/usr/bin/bazzite-steam-firstrun@@ -36,8 +36,8 @@ case $lang in "it") info_text=("Steam è in fase di download. Attendere prego. Il download del client Steam potrebbe richiedere alcuni minuti.") ;;-#brazilian portuguese- "pt_BR")+#portuguese (brazilian translation)+ "pt") info_text=("O Steam está sendo executado pela primeira vez. Por favor, aguarde. O download do cliente Steam pode levar alguns minutos.") ;; #ukrainian12345678910111213141516171819202122232425#!/bin/bashset -uxo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd /workspacemkdir -p /logs/verifierrm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.jsonCAPTURE_DIR="$(mktemp -d)" || exit 1trap 'rm -rf -- "$CAPTURE_DIR"' EXITif ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 64fa640520bcbd038abb2cfdfdf725f87e7a717c > "$CAPTURE_DIR/predicted.patch"; then echo "0.0" > /logs/verifier/reward.txt printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json exit 0firm -f /logs/verifier/predicted.patchcp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch: 'START_VERIFY_OUTPUT'if ! python3 -I "$SCRIPT_DIR/verifier.py" \ "$SCRIPT_DIR/oracle.patch" \ "$CAPTURE_DIR/predicted.patch" \ "$SCRIPT_DIR/instruction.md"; then rm -f /logs/verifier/reward.txt /logs/verifier/reward.json printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.jsonfi: 'END_VERIFY_OUTPUT'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""In-container verifier for pr_diff tasks (6-component reward).
This module is the **standalone verifier** that runs inside the task'sDocker container, NOT a helper used at generation time. Generation emitsits source as ``tests/verifier.py``. Harbor delivers it at verify time,and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
format_valid (0 or 1) — predicted parses as a unified diff (guard) size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) catches "rampage through the codebase" file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — symmetric penalty over-punishes extras) region_overlap ([0, 1]) — predicted hunks overlap oracle hunks (strongest spatial-localization signal) similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only (no free credit for context lines) llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" Anthropic Haiku by default; any OpenAI- compatible server via ``R2E_JUDGE_ENDPOINT``. null when the judge is unavailable (no key or model, network, unreadable reply) → ungraded, no reward file; a reply without a valid score (refusal, content filter, empty, no "score") → a graded 0
Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned fromthe original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-taskpilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).Override per-task via ``task.toml.metadata`` or per-run via env vars``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so theyreach the verifier container).
Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatibleserver (vLLM, Ollama, a gateway) and switches the request to``<endpoint>/chat/completions`` with a bearer token from``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hostedservers ignore it. ``ANTHROPIC_API_KEY`` is only read on the defaultroute and is never sent to a custom endpoint.
Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops acharitable judge from inflating scores on wildly wrong-sized patches).
Outputs (mirrors `_pr_runtime_verifier.py` after #75): /logs/verifier/reward.txt — single float (Harbor reads this); graded runs only /logs/verifier/reward-details.json — full component breakdown + status (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- only, so the breakdown goes to the `reward-details.json` sidecar which Harbor renders under Verifier Logs → Rewards)
Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,``urllib``, ``sys``. The same module is imported by the unit testsunder ``tests/test_pr_diff_verifier.py`` so the in-container behaviorstays in lockstep with what we test."""
from __future__ import annotations
import argparseimport difflibimport jsonimport mathimport osimport reimport sysimport urllib.errorimport urllib.request
# ---------------------------------------------------------------------------# Parsing helpers (shared by multiple components)# ---------------------------------------------------------------------------
_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")_INDEX_RE = re.compile(r"^index ")
def file_paths(diff: str) -> set[str]: """Return the set of ``b/<path>`` paths touched by a unified diff.""" paths: set[str] = set() for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: paths.add(m.group(2)) return paths
def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: """For each touched file, return list of (start_line, end_line) ranges on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). """ out: dict[str, list[tuple[int, int]]] = {} current_file: str | None = None for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: current_file = m.group(2) out.setdefault(current_file, []) continue m = _HUNK_HEADER_RE.match(line) if m and current_file is not None: new_start = int(m.group(3)) new_count = int(m.group(4) or "1") end = new_start + max(new_count - 1, 0) out[current_file].append((new_start, end)) return out
def _normalize_changes_only(diff: str) -> list[str]: """Return the +/- lines (the actual changes) for similarity scoring.
Drops: - ``diff --git`` / ``index abc..def`` metadata - ``@@ ... @@`` hunk markers (volatile line numbers) - context lines (no +/- prefix) — these are unchanged code, scoring them inflates similarity for trivial patches Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity stays in the comparison; normalizes off the tab+timestamp suffix git sometimes appends. """ out: list[str] = [] for line in diff.splitlines(): if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): continue if _HUNK_HEADER_RE.match(line): continue if _FILE_MARKER_RE.match(line): out.append(line.split("\t")[0].strip()) continue # +/- lines (actual changes) if line.startswith("+") or line.startswith("-"): out.append(line) return out
# ---------------------------------------------------------------------------# Reward components# ---------------------------------------------------------------------------
def format_valid(predicted: str) -> float: """1.0 if the predicted text looks like a unified diff; else 0.0.
Requires both a ``diff --git`` header and at least one real +/- line (not the ``---`` / ``+++`` file-marker lines). """ if not predicted.strip(): return 0.0 has_header = False has_change = False for line in predicted.splitlines(): if _DIFF_HEADER_RE.match(line): has_header = True elif (line.startswith("+") or line.startswith("-")) and not line.startswith( ("+++ ", "--- ") ): has_change = True if has_header and has_change: return 1.0 return 0.0
def file_targeting(oracle: str, predicted: str) -> float: """F1 over the changed-file sets.
Why F1 instead of Jaccard: - Missing an oracle file (FN) is a *big* failure. - Touching one unrelated extra file (FP) is a small one. - Jaccard punishes both equally, which over-penalizes the agent for any extra exploration. - F1 weights TP twice, giving partial credit when the agent finds most-but-not-all of the oracle files even with some noise.
Returns 1.0 if both sides touch zero files (degenerate). """ o = file_paths(oracle) p = file_paths(predicted) if not o and not p: return 1.0 tp = len(o & p) fn = len(o - p) fp = len(p - o) if tp == 0: return 0.0 # F1 = 2·TP / (2·TP + FN + FP) return (2 * tp) / (2 * tp + fn + fp)
def _count_loc_changes(diff: str) -> int: """Number of real +/- lines (excluding file-marker lines).""" n = 0 for line in diff.splitlines(): if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): n += 1 return n
def size_sanity(oracle: str, predicted: str) -> float: """Penalize predicted patches that are wildly larger / smaller than the oracle.
Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
This is the "don't rampage through the codebase" guard — a 200-line diff for a 3-line oracle scores ~0.015 here even if every other component looks OK. """ o_loc = _count_loc_changes(oracle) p_loc = _count_loc_changes(predicted) if o_loc == 0 and p_loc == 0: return 1.0 if o_loc == 0 or p_loc == 0: return 0.0 return min(o_loc, p_loc) / max(o_loc, p_loc)
def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: """For each oracle hunk, did the predicted diff edit a line within ``slack_lines`` of that hunk in the same file?
Returns the fraction of oracle hunks that have at least one matching predicted hunk. ``slack_lines`` tolerates slight line-number drift when git diff renders the predicted hunk at a different offset. """ o_ranges = hunk_ranges(oracle) p_ranges = hunk_ranges(predicted) total = sum(len(v) for v in o_ranges.values()) if total == 0: return 1.0 # oracle has no hunks (degenerate) matched = 0 for fname, ranges in o_ranges.items(): p_in_file = p_ranges.get(fname, []) for o_start, o_end in ranges: for p_start, p_end in p_in_file: # Interval overlap with slack — max(starts) <= min(ends) + slack if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: matched += 1 break return matched / total
def similarity(oracle: str, predicted: str) -> float: """SequenceMatcher ratio over +/- lines only.
No free credit for context lines — fixes the v0.8.1 inflation where a one-line fix scored ~0.7 just because the 3 context lines on either side were "matched". """ if not predicted.strip(): return 0.0 o = _normalize_changes_only(oracle) p = _normalize_changes_only(predicted) if not o: return 0.0 # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can # run the verifier past Harbor's timeout. Above this many line pairs, # fall back to difflib's popular-element heuristic, which stays fast. exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
_SIMILARITY_EXACT_PAIRS = 400_000
# A predicted patch over 10x the oracle's changed lines is already a# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a# patch is a graded 0 instead of being scored, so one huge file can't slow# the verifier past its timeout and turn a failing episode into a dropped,# ungraded one. The byte cap stops it from being read at all._MAX_PREDICTED_FACTOR = 10_MAX_PREDICTED_FLOOR_LOC = 1_000_MAX_PREDICTED_BYTES = 16 * 1024 * 1024
def predicted_too_large(oracle: str, predicted: str) -> bool: """Whether the predicted patch is too large to score (a graded 0).""" limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) return _count_loc_changes(predicted) > limit
# ---------------------------------------------------------------------------# LLM-as-judge (Anthropic Messages API, stdlib urllib)# ---------------------------------------------------------------------------
_JUDGE_PROMPT = ( "You are scoring a code-fix patch on whether it logically addresses the " "described issue. Output a single JSON object: " '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' "DO NOT use the oracle to grade. Score on:\n" " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" " - Is the change direction consistent with what the issue describes?\n" " - Is it a real attempt (not boilerplate, not no-op)?\n\n" "Issue:\n{instruction}\n\n" "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" "{oracle}\n\n" "Predicted:\n{predicted}\n\n" "Return ONLY the JSON object.")
_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses._PLACEHOLDER_API_KEY = "EMPTY"
def llm_judge( *, instruction: str, oracle: str, predicted: str, api_key: str, model: str = _DEFAULT_JUDGE_MODEL, timeout: int = 60, endpoint: str | None = None,) -> tuple[float | None, str]: """Return ``(score, status)``.
``score`` is a float in [0, 1] on success, ``None`` on failure. ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. ``output_limit`` means the judge exhausted its configured token budget (ungraded, even if a partial answer contains a score). ``parse`` means the provider's body isn't JSON or has the wrong shape (ungraded); a reply with no usable text (refusal, content filter, empty) or no valid score is ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never increases the other weights.
``endpoint`` — base URL of an OpenAI-compatible server. When set, the request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a bearer token, at temperature 0, and ``model`` must be given explicitly; otherwise it goes to Anthropic's Messages API unchanged. """ if not api_key: return None, "no_api_key" if endpoint and not model: return None, "no_judge_model" if not predicted.strip(): return 0.0, "empty_predicted"
# Truncate hard so we don't blow up the prompt for big diffs prompt = _JUDGE_PROMPT.format( instruction=instruction[:4000], oracle=oracle[:4000], predicted=predicted[:4000], ) payload: dict = { "model": model, "max_tokens": 200, "messages": [{"role": "user", "content": prompt}], } if endpoint: # Small self-hosted models are noisy judges at their default sampling # temperature (same input scoring 0.0 one call and 1.0 the next); pin # them to greedy. The Anthropic route keeps its defaults — the weights # were calibrated against them. payload["temperature"] = 0 url = endpoint.rstrip("/") + "/chat/completions" headers = { "authorization": f"Bearer {api_key}", "content-type": "application/json", } else: url = _ANTHROPIC_MESSAGES_URL headers = { "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): return None, "network"
try: response = json.loads(raw) except json.JSONDecodeError: return None, "parse" # Provider-reported truncation is a grader capacity failure, not evidence # that the submitted patch is wrong. Reasoning models can spend the entire # output budget before producing visible text. Never grade a partial score. if isinstance(response, dict): choices = response.get("choices") if endpoint: if ( isinstance(choices, list) and choices and isinstance(choices[0], dict) and choices[0].get("finish_reason") == "length" ): return None, "output_limit" elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: return None, "output_limit" text = _judge_text(response, openai_compatible=bool(endpoint)) if text is None: return None, "parse"
# Pull the first JSON object out of the model's response m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) if not m: return None, "missing_score" try: obj = json.loads(m.group(0)) score = obj.get("score") except (json.JSONDecodeError, ValueError, TypeError): return None, "missing_score" if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): return None, "invalid_score" return float(score), "ok"
def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
A refusal or a content filter is a well-formed reply with no usable text. The agent's patch is in the prompt, so it can provoke one: that is ``""``, which grades 0, not ``None``, which leaves the run ungraded.
Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and ``content`` empty or holding partial text to discard. OpenAI-compatible: ``message.content`` is null with a ``refusal`` string or ``finish_reason: "content_filter"``. """ if not isinstance(payload, dict): return None if openai_compatible: choices = payload.get("choices") if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): return None message = choices[0].get("message") if not isinstance(message, dict): return None if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": return "" content = message.get("content") if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): # content parts return "".join( part.get("text", "") for part in content if isinstance(part, dict) and isinstance(part.get("text", ""), str) ) return None content = payload.get("content") if not isinstance(content, list): return None if payload.get("stop_reason") == "refusal": return "" return "".join( block["text"] for block in content if isinstance(block, dict) and block.get("type", "text") == "text" and isinstance(block.get("text"), str) )
# ---------------------------------------------------------------------------# Combination# ---------------------------------------------------------------------------
# Judge replies the agent can provoke: its patch text is part of the judge# prompt, so it can steer the answer away from a valid score. These are a# graded 0. An unreadable provider envelope (`parse`), missing configuration,# a disabled judge, transport errors and an exhausted judge output budget leave# the evaluation ungraded. Truncation alone cannot establish an incorrect patch._JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
def evaluation_status(judge_score: float | None, judge_status: str) -> str: """`graded` when the judge scored or the agent can have caused its failure.""" if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: return "graded" return "ungraded"
def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: """Combine declared components, requiring a positively weighted judge.
Without a judge score the result is 0. ``main`` records it as a graded 0 when the agent can have caused the judge failure, and otherwise writes no reward file, so Harbor reports the trial as VERIFIER_FAILED. """ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: return 0.0 if any(w > 0 and components.get(k) is None for k, w in weights.items()): return 0.0 return _weighted_mean(components, weights)
def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] if not available: return 0.0 # Relative weights need not sum to one. Scale first so large finite # overrides cannot overflow the numerator or denominator into NaN. scale = max(w for _, w in available) normalized = [(k, w / scale) for k, w in available] return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
# ---------------------------------------------------------------------------# Entry point (invoked by tests/test.sh inside the container)# ---------------------------------------------------------------------------
# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer# analysis grounded in per-task component data):## - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero# discriminative signal — its 0.05 weight was pure dead weight.# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.# Carrying both at 0.20 double-counts positional accuracy and# additionally penalizes legitimate alternative implementations.# - llm_judge → 0.50: only component capturing semantic correctness# independent of textual form; diverges informatively from# similarity on cases like tokenizers (judge=0.72, sim=0.08).# - region_overlap stays 0.20: strongest spatial-localization signal.# - file_targeting → 0.12: leading indicator, less correlated with the# rest than region/similarity are with each other.# - size_sanity → 0.08: useful outlier detector for catastrophic# over/under-generation (prettier=0.01, serde=0.08).## Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00._DEFAULT_WEIGHTS = { "format_valid": 0.00, "size_sanity": 0.08, "file_targeting": 0.12, "region_overlap": 0.20, "similarity": 0.10, "llm_judge": 0.50,}
# Hard cap: when size_sanity < this threshold, clamp final reward to# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating# the score on patches that are wildly the wrong size (catastrophic# over- or under-generation)._CATASTROPHIC_SIZE_THRESHOLD = 0.10_CATASTROPHIC_SIZE_CAP = 0.40
def _read_weights_from_env() -> dict[str, float]: """Override defaults via R2E_W_* env vars (set in container by harbor).""" overrides = { "format_valid": os.environ.get("R2E_W_FORMAT"), "size_sanity": os.environ.get("R2E_W_SIZE"), "file_targeting": os.environ.get("R2E_W_FILE"), "region_overlap": os.environ.get("R2E_W_REGION"), "similarity": os.environ.get("R2E_W_SIM"), "llm_judge": os.environ.get("R2E_W_JUDGE"), } out = dict(_DEFAULT_WEIGHTS) for k, v in overrides.items(): if v is None: continue try: value = float(v) if math.isfinite(value) and value >= 0: out[k] = value except (TypeError, ValueError): continue return out
def _judge_config_from_env() -> tuple[str, str, str | None]: """``(api_key, model, endpoint)`` for the judge, from the verifier env.
With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a self-hosted server won't have Haiku): when unset, ``model`` comes back as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of calling out. Without an endpoint the default Anthropic route is unchanged. """ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None model = os.environ.get("R2E_JUDGE_MODEL", "").strip() if endpoint: api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY return api_key, model, endpoint return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("oracle") parser.add_argument("predicted") parser.add_argument("instruction") parser.add_argument("--out-dir", default="/logs/verifier") args = parser.parse_args(argv) os.makedirs(args.out_dir, exist_ok=True) # This run is the only authority on the reward: an earlier or planted # reward file must not stand if this evaluation ends up ungraded. for name in ("reward.txt", "reward.json"): try: os.unlink(os.path.join(args.out_dir, name)) except FileNotFoundError: pass oracle = _read_or_empty(args.oracle) try: oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES except OSError: oversized = False predicted = "" if oversized else _read_or_empty(args.predicted) if oversized or predicted_too_large(oracle, predicted): breakdown = { "final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": False, "predicted_status": "predicted_too_large", } _write_outputs(args.out_dir, 0.0, breakdown) return 0 instruction = _read_or_empty(args.instruction) api_key, judge_model, judge_endpoint = _judge_config_from_env()
fv = format_valid(predicted) ss = size_sanity(oracle, predicted) ft = file_targeting(oracle, predicted) ro = region_overlap(oracle, predicted) sim = similarity(oracle, predicted) weights = _read_weights_from_env() if weights["llm_judge"] <= 0: judge_score, judge_status = None, "disabled" else: judge_score, judge_status = llm_judge( instruction=instruction, oracle=oracle, predicted=predicted, api_key=api_key, model=judge_model, endpoint=judge_endpoint, )
components: dict[str, float | None] = { "format_valid": fv, "size_sanity": ss, "file_targeting": ft, "region_overlap": ro, "similarity": sim, "llm_judge": judge_score, } final = combine(components, weights) final = max(0.0, min(1.0, final))
# Hard cap on catastrophic size mismatches. Without this, a charitable # judge can inflate the reward on patches that are dramatically the # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge # was lenient at 0.25 despite the patch being a near-no-op vs a # 500-line oracle). The cap kicks in only at the extremes. if ss < _CATASTROPHIC_SIZE_THRESHOLD: final = min(final, _CATASTROPHIC_SIZE_CAP)
status = evaluation_status(judge_score, judge_status) breakdown = { # No reward exists for an ungraded evaluation: null, not a placeholder 0. "final_reward": round(final, 6) if status == "graded" else None, "evaluation_status": status, "eval_trustworthy": judge_score is not None, "diagnostic_similarity": round( _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), 6, ), "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, "weights": {k: round(v, 6) for k, v in weights.items()}, "judge_model": judge_model if judge_status == "ok" else None, "judge_endpoint": judge_endpoint, "judge_status": judge_status, }
_write_outputs(args.out_dir, final, breakdown) return 0
def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: # An ungraded evaluation writes no reward file. Harbor then raises # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout # instead of training on a 0. Harbor's job mean and pass@k still count the # trial as 0, so evaluation stays fail-closed. if breakdown["evaluation_status"] == "graded": with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: f.write(f"{final:.6f}\n") # Harbor's `reward.json` must be a flat map of floats/ints (spec, see # <https://harborframework.com/docs/tasks>); our breakdown carries nested # dicts, judge strings, and status strings, so it goes to the sidecar the # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) # for `_pr_runtime_verifier.py`. with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: json.dump(breakdown, f, indent=2)
# Also print to stdout so harbor's log captures the breakdown print(json.dumps(breakdown, indent=2))
def _read_or_empty(path: str) -> str: try: with open(path, encoding="utf-8") as f: return f.read() except (OSError, UnicodeDecodeError): return ""
if __name__ == "__main__": sys.exit(main())
__all__ = [ "combine", "file_paths", "file_targeting", "format_valid", "hunk_ranges", "llm_judge", "main", "predicted_too_large", "region_overlap", "similarity", "size_sanity",]12345678910111213141516171819202122232425262728293031323334353637# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.# Agent-agnostic: the agent (claude-code / openhands / codex / etc.)# installs itself at run time via its harbor adapter. We only ship# the source repo — the oracle + verifier arrive at verify time via# tests/, never baked into the agent's image.FROM python:3.12-slimARG GITHUB_TOKEN=RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/*RUN git config --global --add safe.directory /workspace \ && git config --global init.defaultBranch main \ && git config --global advice.detachedHead falseRUN if [ -n "$GITHUB_TOKEN" ]; then \ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \ else \ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \ fi \ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.gitWORKDIR /workspaceRUN git fetch --depth 1 origin 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 2>/dev/null \ || git fetch --unshallow origin 2>/dev/null || trueRUN git reset --hard 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 \ && git clean -fdx -e .venv -e venv -e __pycache__RUN git checkout -q -B base 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 \ && git remote remove origin 2>/dev/null || trueRUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ && git reflog expire --expire=now --all 2>/dev/null || true \ && git gc --prune=now 2>/dev/null || trueRUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ fi1234567891011121314151617181920# Issue
**Title:** fix: check MOKs aren't in use before suggesting deletion
## Description
I got a `ujust check-anticheat` log from a user with a Ventoy key enrolled. The hint told them to delete every key that isn't well-known without checking what it signs, which could leave a system unbootable.
* Check that MOKs that aren't well-known aren't used by the kernel, the bootloader, another boot entry or a loaded driver before suggesting they be deleted* Show why the TPM boot log couldn't be read* Fix the IOMMU hint for passthrough on by default in the kernel, and the BPF hint when the active LSMs can't be read, which would have dropped SELinux* Tell handheld users to hold off on kernel lockdown for now
I've tested this on my machine, and we should have people give it a whirl on unstable/testing.
This is reaching the level of complexity I like with bash, so I'm exploring a Python rewrite.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1901c6af3ce5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189diff --git a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.justindex f0a48eb3..9d460399 100644--- a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just+++ b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just@@ -53,10 +53,12 @@ check-anticheat: SIGNER_CN=$(sed -n 's|^ *- subject: .*/CN=\([^/]*\).*|\1|p' <<<"$SIGNERS" | head -n1) if ! grep -q 'subject:' <<<"$SIGNERS"; then fail "Signed kernel" "Kernel $(uname -r) is not signed"- elif grep -Eq "$WELL_KNOWN_KEYS" <<<"$SIGNERS"; then- pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}'"+ elif WELL_KNOWN_LINE=$(grep -Em1 "$WELL_KNOWN_KEYS" <<<"$SIGNERS"); then+ # A kernel can have several signatures, so name the well-known one+ SIGNER_CN=$(sed -n 's|.*/CN=\([^/]*\).*|\1|p' <<<"$WELL_KNOWN_LINE")+ pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}'" else- fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}', which is not a well-known key"+ fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}', which is not a well-known key" fi fi @@ -101,14 +103,116 @@ check-anticheat: for der in "$MOK_DIR"/MOK-*.der; do [[ -e $der ]] || continue CERT=$(openssl x509 -inform DER -in "$der" -noout -subject -issuer 2>/dev/null)- if ! grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT"; then- UNKNOWN_MOKS+=("'$(sed -n 's/^subject=.*CN *= *\([^,]*\).*/\1/p' <<<"$CERT")'")- fi+ grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT" || UNKNOWN_MOKS+=("$der") done if (( MOK_STATUS )); then fail "Only well-known Machine Owner Keys" "Couldn't read the enrolled keys (mokutil says: ${MOK_ERR//$'\n'/ })" elif (( ${#UNKNOWN_MOKS[@]} )); then- fail "Only well-known Machine Owner Keys" "Not well-known: ${UNKNOWN_MOKS[*]}. Export them with 'mokutil --export', then remove each with 'sudo mokutil --delete MOK-000N.der'"+ # Never suggest deleting a key that the kernel, an EFI binary or a loaded module depends on+ cert_cn() {+ openssl x509 -inform DER -in "$1" -noout "$2" -nameopt multiline,utf8,-esc_msb 2>/dev/null | sed -n 's/^ *commonName *= *//p' | head -n1+ }+ ESP_DIR=/boot/efi/EFI+ mapfile -t BOOT_FILES < <(find "$ESP_DIR" -type f -iname '*.efi' 2>/dev/null)+ BOOT_READABLE=1+ [[ ${#BOOT_FILES[@]} -gt 0 && -r $KERNEL ]] || BOOT_READABLE=0+ BOOT_FILES+=("$KERNEL")+ declare -A SIGNED_MODULES=()+ while read -r mod _; do+ SIGNER=$(modinfo -F signer "$mod" 2>/dev/null)+ [[ -n $SIGNER ]] && SIGNED_MODULES[$SIGNER]+=" $mod"+ done </proc/modules++ # BOOT and fedora are this system's ESP folders, plus whichever entry the firmware booted, which may chainload them.+ # If that's unknown, treat every folder as ours+ EFI_ENTRIES=$(efibootmgr 2>/dev/null)+ BOOT_CURRENT=$(sed -n 's/^BootCurrent: //p' <<<"$EFI_ENTRIES")+ CURRENT_ENTRY=""+ if [[ -n $BOOT_CURRENT ]]; then+ CURRENT_ENTRY=$(grep -E "^Boot${BOOT_CURRENT}[* ]" <<<"$EFI_ENTRIES" | grep -oiE '\\EFI\\[^\\]+' | head -n1)+ CURRENT_ENTRY=${CURRENT_ENTRY##*\\}+ fi++ KEY_LINES=()+ SAFE_KEYS=""+ SAFE_FILES=()+ OTHER_FILES=()+ for der in "${UNKNOWN_MOKS[@]}"; do+ FILE=${der##*/}+ NAME=$(cert_cn "$der" -subject)+ ISSUER=$(cert_cn "$der" -issuer)+ KEY="'${NAME:-unnamed}' (${FILE})"+ DN=$(openssl x509 -inform DER -in "$der" -noout -subject -nameopt compat 2>/dev/null)+ DN=${DN#subject=}+ if [[ -z $DN ]]; then+ KEY_LINES+=("${KEY}. It couldn't be read, so this system may need it to boot and it cannot be deleted.")+ continue+ fi+ SIGNS_KERNEL=0+ SIGNS_BOOTLOADER=0+ declare -A OTHER_ENTRIES=()+ for file in "${BOOT_FILES[@]}"; do+ # Not sbverify --cert, which accepts any key for binaries that embed a certificate chain, like shim+ sbverify --list "$file" 2>/dev/null | sed -E 's/^ *(- )?((subject|issuer): *)?//' | grep -Fx -- "$DN" >/dev/null || continue+ ENTRY=${file#"$ESP_DIR"/}+ ENTRY=${ENTRY%%/*}+ if [[ $file == "$KERNEL" ]]; then+ SIGNS_KERNEL=1+ elif [[ -z $CURRENT_ENTRY || ${ENTRY,,} == "${CURRENT_ENTRY,,}" || ${ENTRY,,} =~ ^(boot|fedora)$ ]]; then+ SIGNS_BOOTLOADER=1+ else+ OTHER_ENTRIES[$ENTRY]=1+ fi+ done+ # modinfo reports a module's signer by the issuer of its certificate, so check both names+ DRIVERS=""+ [[ -n $NAME ]] && DRIVERS=${SIGNED_MODULES[$NAME]:-}+ [[ -n $ISSUER && $ISSUER != "$NAME" ]] && DRIVERS+=${SIGNED_MODULES[$ISSUER]:-}++ if (( SIGNS_KERNEL || SIGNS_BOOTLOADER )); then+ USES=()+ (( SIGNS_KERNEL )) && USES+=("the running kernel")+ (( SIGNS_BOOTLOADER )) && USES+=("this system's bootloader")+ [[ -n $DRIVERS ]] && USES+=("these drivers:${DRIVERS}")+ SIGNS=${USES[0]}+ (( ${#USES[@]} == 3 )) && SIGNS+=", ${USES[1]}"+ (( ${#USES[@]} > 1 )) && SIGNS+=" and ${USES[-1]}"+ KEY_LINES+=("${KEY}. It signs ${SIGNS}. This system may not boot without it, so it cannot be deleted.")+ elif [[ -n $DRIVERS ]]; then+ KEY_LINES+=("${KEY}. It signs these drivers, which won't load without it, so it cannot be deleted:${DRIVERS}.")+ elif (( ! BOOT_READABLE )); then+ KEY_LINES+=("${KEY}. Couldn't read the kernel and the EFI binaries in /boot/efi, so this system may need it to boot. Check what it signs before deleting it.")+ elif (( ${#OTHER_ENTRIES[@]} )); then+ KEY_LINES+=("${KEY}. It signs the bootloader for another boot entry (${!OTHER_ENTRIES[*]}). This system doesn't need it, but only delete it if you no longer use that entry.")+ OTHER_FILES+=("$FILE")+ else+ SAFE_KEYS+="${SAFE_KEYS:+, }${KEY}"+ SAFE_FILES+=("$FILE")+ fi+ done++ fail "Only well-known Machine Owner Keys"+ for line in "${KEY_LINES[@]}"; do+ printf ' %s\n' "Not well-known: ${line}"+ done+ EXPORT="run 'mokutil --export' in an empty directory"+ if (( ${#SAFE_FILES[@]} )); then+ THESE="These keys are"+ IT=them+ if (( ${#SAFE_FILES[@]} == 1 )); then+ THESE="This key is"+ IT=it+ fi+ printf ' %s\n' "Not well-known: ${SAFE_KEYS}. ${THESE} not used by the running kernel, any boot entry on this drive or any loaded driver, and may be safely deleted."+ printf ' %s\n' "To delete ${IT}, ${EXPORT}, then 'sudo mokutil --delete ${SAFE_FILES[*]}'.${OTHER_FILES[*]:+ Add ${OTHER_FILES[*]} for any boot entry you no longer use.}"+ elif (( ${#OTHER_FILES[@]} == 1 )); then+ printf ' %s\n' "If you no longer use that entry, ${EXPORT}, then 'sudo mokutil --delete ${OTHER_FILES[0]}'."+ elif (( ${#OTHER_FILES[@]} )); then+ printf ' %s\n' "For any of those entries you no longer use, ${EXPORT}, then 'sudo mokutil --delete' with its key: ${OTHER_FILES[*]}."+ fi+ if (( ${#SAFE_FILES[@]} + ${#OTHER_FILES[@]} )); then+ printf ' %s\n' "If asked for a password, use 'universalblue'. At next reboot, select 'Delete MOK' in the mokutil UEFI menu and enter 'universalblue' again."+ fi else pass "Only well-known Machine Owner Keys" fi@@ -120,7 +224,8 @@ check-anticheat: else # GRUB measures into PCRs 8 and 9, systemd-boot and systemd-stub into 11 and 12 if ! PCRS=$(tpm2_eventlog "$EVENT_LOG" 2>/dev/null); then- fail "Measured boot" "Couldn't read the TPM boot log"+ TPM_ERR=$(tpm2_eventlog "$EVENT_LOG" 2>&1 >/dev/null)+ fail "Measured boot" "Couldn't read the TPM boot log (tpm2_eventlog says: ${TPM_ERR//$'\n'/ })" elif grep -Eq '^\s*PCRIndex: (8|9|11|12)$' <<<"$PCRS"; then pass "Measured boot" "The boot manager recorded its measurements" else@@ -135,12 +240,14 @@ check-anticheat: done if [[ -z $PASSTHROUGH ]] && ! has_karg iommu.passthrough=0 && grep -q '^CONFIG_IOMMU_DEFAULT_PASSTHROUGH=y' "/usr/lib/modules/$(uname -r)/config" 2>/dev/null; then- PASSTHROUGH="the kernel's default"+ PASSTHROUGH=default fi if compgen -G '/sys/class/iommu/*' >/dev/null && [[ -z $PASSTHROUGH ]]; then pass "IOMMU enabled, passthrough disabled" elif (( HANDHELD )); then pass "IOMMU enabled, passthrough disabled" "Not required on handheld devices"+ elif [[ $PASSTHROUGH == default ]]; then+ fail "IOMMU enabled, passthrough disabled" "Passthrough is on by default in this kernel. Run 'rpm-ostree kargs --append-if-missing=iommu.passthrough=0'" elif [[ -n $PASSTHROUGH ]]; then fail "IOMMU enabled, passthrough disabled" "Passthrough is on (${PASSTHROUGH}). Remove it with 'rpm-ostree kargs --delete=${PASSTHROUGH}'" elif grep -q GenuineIntel /proc/cpuinfo; then@@ -153,6 +260,9 @@ check-anticheat: LOCKDOWN=$(sed -n 's/.*\[\(.*\)\].*/\1/p' /sys/kernel/security/lockdown 2>/dev/null) if [[ $LOCKDOWN == integrity || $LOCKDOWN == confidentiality ]]; then pass "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN}'"+ elif (( HANDHELD )); then+ fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'."+ printf ' %s\n' "${bold}Note:${normal} Handheld users should hold off on enabling kernel lockdown for now. We're working on a solution." else fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'. Run 'rpm-ostree kargs --append-if-missing=lockdown=integrity'" fi@@ -169,8 +279,10 @@ check-anticheat: LSMS=$(cat /sys/kernel/security/lsm 2>/dev/null) if [[ ,$LSMS, == *,bpf,* ]]; then pass "BPF LSM active"+ elif [[ -z $LSMS ]]; then+ fail "BPF LSM active" "Couldn't read the active LSMs from /sys/kernel/security/lsm" else- fail "BPF LSM active" "Active LSMs: ${LSMS:-unknown}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS:+$LSMS,}bpf'"+ fail "BPF LSM active" "Active LSMs: ${LSMS}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS},bpf'" fi echo123456#!/bin/bashset -euxo pipefailcd /workspacegit config --global --add safe.directory /workspacePATCH="$(dirname "$0")/patch.diff"git apply --verbose --reject "$PATCH"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768version = "1.0"
[task]name = "trending/ublue-os__bazzite-6234"description = "fix: check MOKs aren't in use before suggesting deletion"
[metadata]difficulty = "large"category = "bugfix"keywords = [ "bazzite", "pr_diff",]
[metadata.repo2env]pipeline = "pr_diff"pipeline_version = "0.3.0"repo = "ublue-os/bazzite"ref = "1901c6af3ce5d755baf00e37bcbf1fd313ca9651"reference = "https://github.com/ublue-os/bazzite/pull/6234"source_access = "auto"built_at = "2026-11-16T16:09:50.979136+00:00"reward_kinds = [ "diff_similarity",]spec_version = "0.2.0"content_hash = "sha256:259fac6ae377342851e02822fb244ae7b812ecef38e96e550bbaf073b8af4650"
[metadata.repo2env.pr_diff]pr_merged_at = "2026-11-04T16:36:04Z"diff_format = "unified"context_files = [ "system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just",]bootstrap_image = "python:3.12-slim"
[metadata.repo2env.reward_calibration]baseline_reward = 0.0loc_changed = 132difficulty = "large"
[metadata.repo2env.evaluation]schema_version = "1"status = "unverified"stage = "generation"reason_codes = [ "validation_not_run",]detail = "Generated task; validation has not been established."provenance = "unknown"evidence = []
[metadata.repo2env.reproducibility]mode = "inline_dockerfile"image_ref = "python:3.12-slim"image_tag = "python:3.12-slim"image_visibility = "public"pushed_at = "2026-11-16T16:20:03.588917+00:00"pushed_by = "scalingX"inline_recipe_sha256 = "sha256:74d93ef9d8f18d981ab4f7a0ee26af3c07662dbe889f13667c67bef70bd789cf"inline_recipe_lines = 37inline_recipe_source = "user_dockerfile"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 300.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Standalone PR-diff capture without executing workspace Git configuration.
The emitted task uses a regular clone with a pinned base commit. Only itsobject store is read: refs, index, config, hooks and replacement refs are notused. This is a configuration boundary, not a sandbox for a malicious processthat can modify the verifier, binaries or object store while capture runs."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
def capture(workspace: Path, base_commit: str) -> bytes: """Capture tracked and new files through a fresh private Git index.""" if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): raise ValueError("Expected the task's pinned SHA-1 base commit") objects = workspace.resolve() / ".git" / "objects" if not objects.is_dir(): raise ValueError("The task's cloned Git object store is missing") git = shutil.which("git", path=os.defpath) if git is None: raise FileNotFoundError("System git is unavailable") with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: private = Path(temporary) # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, # system/global includes, user attributes, templates or credential env. env = { "PATH": os.defpath, "HOME": temporary, "XDG_CONFIG_HOME": temporary, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", } subprocess.run( [git, "init", "--quiet", "--template=", str(private / "repository")], env=env, cwd=private, check=True, capture_output=True, timeout=60, ) env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) command = [ git, f"--git-dir={private / 'repository/.git'}", f"--work-tree={workspace.resolve()}", ]
def run(*args: str) -> bytes: return subprocess.run( [*command, *args], env=env, cwd=workspace, check=True, capture_output=True, timeout=60, ).stdout
run("read-tree", f"{base_commit}^{{tree}}") # All filter drivers are undefined in the private configuration. The # workspace's clean filters, fsmonitor and hooks cannot be invoked. run("add", "--all", "--", ".") return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("workspace", type=Path) parser.add_argument("base_commit") args = parser.parse_args(argv) try: patch = capture(args.workspace, args.base_commit) except (OSError, ValueError, subprocess.SubprocessError) as exc: # Do not echo child stderr: it may contain workspace-controlled data. sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") return 1 sys.stdout.buffer.write(patch) return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920# Issue
**Title:** fix: check MOKs aren't in use before suggesting deletion
## Description
I got a `ujust check-anticheat` log from a user with a Ventoy key enrolled. The hint told them to delete every key that isn't well-known without checking what it signs, which could leave a system unbootable.
* Check that MOKs that aren't well-known aren't used by the kernel, the bootloader, another boot entry or a loaded driver before suggesting they be deleted* Show why the TPM boot log couldn't be read* Fix the IOMMU hint for passthrough on by default in the kernel, and the BPF hint when the active LSMs can't be read, which would have dropped SELinux* Tell handheld users to hold off on kernel lockdown for now
I've tested this on my machine, and we should have people give it a whirl on unstable/testing.
This is reaching the level of complexity I like with bash, so I'm exploring a Python rewrite.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1901c6af3ce5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189diff --git a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.justindex f0a48eb3..9d460399 100644--- a/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just+++ b/system_files/desktop/shared/usr/share/ublue-os/just/96-bazzite-anticheat.just@@ -53,10 +53,12 @@ check-anticheat: SIGNER_CN=$(sed -n 's|^ *- subject: .*/CN=\([^/]*\).*|\1|p' <<<"$SIGNERS" | head -n1) if ! grep -q 'subject:' <<<"$SIGNERS"; then fail "Signed kernel" "Kernel $(uname -r) is not signed"- elif grep -Eq "$WELL_KNOWN_KEYS" <<<"$SIGNERS"; then- pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}'"+ elif WELL_KNOWN_LINE=$(grep -Em1 "$WELL_KNOWN_KEYS" <<<"$SIGNERS"); then+ # A kernel can have several signatures, so name the well-known one+ SIGNER_CN=$(sed -n 's|.*/CN=\([^/]*\).*|\1|p' <<<"$WELL_KNOWN_LINE")+ pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}'" else- fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}', which is not a well-known key"+ fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN:-unnamed}', which is not a well-known key" fi fi @@ -101,14 +103,116 @@ check-anticheat: for der in "$MOK_DIR"/MOK-*.der; do [[ -e $der ]] || continue CERT=$(openssl x509 -inform DER -in "$der" -noout -subject -issuer 2>/dev/null)- if ! grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT"; then- UNKNOWN_MOKS+=("'$(sed -n 's/^subject=.*CN *= *\([^,]*\).*/\1/p' <<<"$CERT")'")- fi+ grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT" || UNKNOWN_MOKS+=("$der") done if (( MOK_STATUS )); then fail "Only well-known Machine Owner Keys" "Couldn't read the enrolled keys (mokutil says: ${MOK_ERR//$'\n'/ })" elif (( ${#UNKNOWN_MOKS[@]} )); then- fail "Only well-known Machine Owner Keys" "Not well-known: ${UNKNOWN_MOKS[*]}. Export them with 'mokutil --export', then remove each with 'sudo mokutil --delete MOK-000N.der'"+ # Never suggest deleting a key that the kernel, an EFI binary or a loaded module depends on+ cert_cn() {+ openssl x509 -inform DER -in "$1" -noout "$2" -nameopt multiline,utf8,-esc_msb 2>/dev/null | sed -n 's/^ *commonName *= *//p' | head -n1+ }+ ESP_DIR=/boot/efi/EFI+ mapfile -t BOOT_FILES < <(find "$ESP_DIR" -type f -iname '*.efi' 2>/dev/null)+ BOOT_READABLE=1+ [[ ${#BOOT_FILES[@]} -gt 0 && -r $KERNEL ]] || BOOT_READABLE=0+ BOOT_FILES+=("$KERNEL")+ declare -A SIGNED_MODULES=()+ while read -r mod _; do+ SIGNER=$(modinfo -F signer "$mod" 2>/dev/null)+ [[ -n $SIGNER ]] && SIGNED_MODULES[$SIGNER]+=" $mod"+ done </proc/modules++ # BOOT and fedora are this system's ESP folders, plus whichever entry the firmware booted, which may chainload them.+ # If that's unknown, treat every folder as ours+ EFI_ENTRIES=$(efibootmgr 2>/dev/null)+ BOOT_CURRENT=$(sed -n 's/^BootCurrent: //p' <<<"$EFI_ENTRIES")+ CURRENT_ENTRY=""+ if [[ -n $BOOT_CURRENT ]]; then+ CURRENT_ENTRY=$(grep -E "^Boot${BOOT_CURRENT}[* ]" <<<"$EFI_ENTRIES" | grep -oiE '\\EFI\\[^\\]+' | head -n1)+ CURRENT_ENTRY=${CURRENT_ENTRY##*\\}+ fi++ KEY_LINES=()+ SAFE_KEYS=""+ SAFE_FILES=()+ OTHER_FILES=()+ for der in "${UNKNOWN_MOKS[@]}"; do+ FILE=${der##*/}+ NAME=$(cert_cn "$der" -subject)+ ISSUER=$(cert_cn "$der" -issuer)+ KEY="'${NAME:-unnamed}' (${FILE})"+ DN=$(openssl x509 -inform DER -in "$der" -noout -subject -nameopt compat 2>/dev/null)+ DN=${DN#subject=}+ if [[ -z $DN ]]; then+ KEY_LINES+=("${KEY}. It couldn't be read, so this system may need it to boot and it cannot be deleted.")+ continue+ fi+ SIGNS_KERNEL=0+ SIGNS_BOOTLOADER=0+ declare -A OTHER_ENTRIES=()+ for file in "${BOOT_FILES[@]}"; do+ # Not sbverify --cert, which accepts any key for binaries that embed a certificate chain, like shim+ sbverify --list "$file" 2>/dev/null | sed -E 's/^ *(- )?((subject|issuer): *)?//' | grep -Fx -- "$DN" >/dev/null || continue+ ENTRY=${file#"$ESP_DIR"/}+ ENTRY=${ENTRY%%/*}+ if [[ $file == "$KERNEL" ]]; then+ SIGNS_KERNEL=1+ elif [[ -z $CURRENT_ENTRY || ${ENTRY,,} == "${CURRENT_ENTRY,,}" || ${ENTRY,,} =~ ^(boot|fedora)$ ]]; then+ SIGNS_BOOTLOADER=1+ else+ OTHER_ENTRIES[$ENTRY]=1+ fi+ done+ # modinfo reports a module's signer by the issuer of its certificate, so check both names+ DRIVERS=""+ [[ -n $NAME ]] && DRIVERS=${SIGNED_MODULES[$NAME]:-}+ [[ -n $ISSUER && $ISSUER != "$NAME" ]] && DRIVERS+=${SIGNED_MODULES[$ISSUER]:-}++ if (( SIGNS_KERNEL || SIGNS_BOOTLOADER )); then+ USES=()+ (( SIGNS_KERNEL )) && USES+=("the running kernel")+ (( SIGNS_BOOTLOADER )) && USES+=("this system's bootloader")+ [[ -n $DRIVERS ]] && USES+=("these drivers:${DRIVERS}")+ SIGNS=${USES[0]}+ (( ${#USES[@]} == 3 )) && SIGNS+=", ${USES[1]}"+ (( ${#USES[@]} > 1 )) && SIGNS+=" and ${USES[-1]}"+ KEY_LINES+=("${KEY}. It signs ${SIGNS}. This system may not boot without it, so it cannot be deleted.")+ elif [[ -n $DRIVERS ]]; then+ KEY_LINES+=("${KEY}. It signs these drivers, which won't load without it, so it cannot be deleted:${DRIVERS}.")+ elif (( ! BOOT_READABLE )); then+ KEY_LINES+=("${KEY}. Couldn't read the kernel and the EFI binaries in /boot/efi, so this system may need it to boot. Check what it signs before deleting it.")+ elif (( ${#OTHER_ENTRIES[@]} )); then+ KEY_LINES+=("${KEY}. It signs the bootloader for another boot entry (${!OTHER_ENTRIES[*]}). This system doesn't need it, but only delete it if you no longer use that entry.")+ OTHER_FILES+=("$FILE")+ else+ SAFE_KEYS+="${SAFE_KEYS:+, }${KEY}"+ SAFE_FILES+=("$FILE")+ fi+ done++ fail "Only well-known Machine Owner Keys"+ for line in "${KEY_LINES[@]}"; do+ printf ' %s\n' "Not well-known: ${line}"+ done+ EXPORT="run 'mokutil --export' in an empty directory"+ if (( ${#SAFE_FILES[@]} )); then+ THESE="These keys are"+ IT=them+ if (( ${#SAFE_FILES[@]} == 1 )); then+ THESE="This key is"+ IT=it+ fi+ printf ' %s\n' "Not well-known: ${SAFE_KEYS}. ${THESE} not used by the running kernel, any boot entry on this drive or any loaded driver, and may be safely deleted."+ printf ' %s\n' "To delete ${IT}, ${EXPORT}, then 'sudo mokutil --delete ${SAFE_FILES[*]}'.${OTHER_FILES[*]:+ Add ${OTHER_FILES[*]} for any boot entry you no longer use.}"+ elif (( ${#OTHER_FILES[@]} == 1 )); then+ printf ' %s\n' "If you no longer use that entry, ${EXPORT}, then 'sudo mokutil --delete ${OTHER_FILES[0]}'."+ elif (( ${#OTHER_FILES[@]} )); then+ printf ' %s\n' "For any of those entries you no longer use, ${EXPORT}, then 'sudo mokutil --delete' with its key: ${OTHER_FILES[*]}."+ fi+ if (( ${#SAFE_FILES[@]} + ${#OTHER_FILES[@]} )); then+ printf ' %s\n' "If asked for a password, use 'universalblue'. At next reboot, select 'Delete MOK' in the mokutil UEFI menu and enter 'universalblue' again."+ fi else pass "Only well-known Machine Owner Keys" fi@@ -120,7 +224,8 @@ check-anticheat: else # GRUB measures into PCRs 8 and 9, systemd-boot and systemd-stub into 11 and 12 if ! PCRS=$(tpm2_eventlog "$EVENT_LOG" 2>/dev/null); then- fail "Measured boot" "Couldn't read the TPM boot log"+ TPM_ERR=$(tpm2_eventlog "$EVENT_LOG" 2>&1 >/dev/null)+ fail "Measured boot" "Couldn't read the TPM boot log (tpm2_eventlog says: ${TPM_ERR//$'\n'/ })" elif grep -Eq '^\s*PCRIndex: (8|9|11|12)$' <<<"$PCRS"; then pass "Measured boot" "The boot manager recorded its measurements" else@@ -135,12 +240,14 @@ check-anticheat: done if [[ -z $PASSTHROUGH ]] && ! has_karg iommu.passthrough=0 && grep -q '^CONFIG_IOMMU_DEFAULT_PASSTHROUGH=y' "/usr/lib/modules/$(uname -r)/config" 2>/dev/null; then- PASSTHROUGH="the kernel's default"+ PASSTHROUGH=default fi if compgen -G '/sys/class/iommu/*' >/dev/null && [[ -z $PASSTHROUGH ]]; then pass "IOMMU enabled, passthrough disabled" elif (( HANDHELD )); then pass "IOMMU enabled, passthrough disabled" "Not required on handheld devices"+ elif [[ $PASSTHROUGH == default ]]; then+ fail "IOMMU enabled, passthrough disabled" "Passthrough is on by default in this kernel. Run 'rpm-ostree kargs --append-if-missing=iommu.passthrough=0'" elif [[ -n $PASSTHROUGH ]]; then fail "IOMMU enabled, passthrough disabled" "Passthrough is on (${PASSTHROUGH}). Remove it with 'rpm-ostree kargs --delete=${PASSTHROUGH}'" elif grep -q GenuineIntel /proc/cpuinfo; then@@ -153,6 +260,9 @@ check-anticheat: LOCKDOWN=$(sed -n 's/.*\[\(.*\)\].*/\1/p' /sys/kernel/security/lockdown 2>/dev/null) if [[ $LOCKDOWN == integrity || $LOCKDOWN == confidentiality ]]; then pass "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN}'"+ elif (( HANDHELD )); then+ fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'."+ printf ' %s\n' "${bold}Note:${normal} Handheld users should hold off on enabling kernel lockdown for now. We're working on a solution." else fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'. Run 'rpm-ostree kargs --append-if-missing=lockdown=integrity'" fi@@ -169,8 +279,10 @@ check-anticheat: LSMS=$(cat /sys/kernel/security/lsm 2>/dev/null) if [[ ,$LSMS, == *,bpf,* ]]; then pass "BPF LSM active"+ elif [[ -z $LSMS ]]; then+ fail "BPF LSM active" "Couldn't read the active LSMs from /sys/kernel/security/lsm" else- fail "BPF LSM active" "Active LSMs: ${LSMS:-unknown}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS:+$LSMS,}bpf'"+ fail "BPF LSM active" "Active LSMs: ${LSMS}. Run 'rpm-ostree kargs --append-if-missing=lsm=${LSMS},bpf'" fi echo12345678910111213141516171819202122232425#!/bin/bashset -uxo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"cd /workspacemkdir -p /logs/verifierrm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.jsonCAPTURE_DIR="$(mktemp -d)" || exit 1trap 'rm -rf -- "$CAPTURE_DIR"' EXITif ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1901c6af3ce5d755baf00e37bcbf1fd313ca9651 > "$CAPTURE_DIR/predicted.patch"; then echo "0.0" > /logs/verifier/reward.txt printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json exit 0firm -f /logs/verifier/predicted.patchcp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch: 'START_VERIFY_OUTPUT'if ! python3 -I "$SCRIPT_DIR/verifier.py" \ "$SCRIPT_DIR/oracle.patch" \ "$CAPTURE_DIR/predicted.patch" \ "$SCRIPT_DIR/instruction.md"; then rm -f /logs/verifier/reward.txt /logs/verifier/reward.json printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.jsonfi: 'END_VERIFY_OUTPUT'exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""In-container verifier for pr_diff tasks (6-component reward).
This module is the **standalone verifier** that runs inside the task'sDocker container, NOT a helper used at generation time. Generation emitsits source as ``tests/verifier.py``. Harbor delivers it at verify time,and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
format_valid (0 or 1) — predicted parses as a unified diff (guard) size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) catches "rampage through the codebase" file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — symmetric penalty over-punishes extras) region_overlap ([0, 1]) — predicted hunks overlap oracle hunks (strongest spatial-localization signal) similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only (no free credit for context lines) llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" Anthropic Haiku by default; any OpenAI- compatible server via ``R2E_JUDGE_ENDPOINT``. null when the judge is unavailable (no key or model, network, unreadable reply) → ungraded, no reward file; a reply without a valid score (refusal, content filter, empty, no "score") → a graded 0
Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned fromthe original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-taskpilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).Override per-task via ``task.toml.metadata`` or per-run via env vars``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so theyreach the verifier container).
Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatibleserver (vLLM, Ollama, a gateway) and switches the request to``<endpoint>/chat/completions`` with a bearer token from``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hostedservers ignore it. ``ANTHROPIC_API_KEY`` is only read on the defaultroute and is never sent to a custom endpoint.
Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops acharitable judge from inflating scores on wildly wrong-sized patches).
Outputs (mirrors `_pr_runtime_verifier.py` after #75): /logs/verifier/reward.txt — single float (Harbor reads this); graded runs only /logs/verifier/reward-details.json — full component breakdown + status (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- only, so the breakdown goes to the `reward-details.json` sidecar which Harbor renders under Verifier Logs → Rewards)
Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,``urllib``, ``sys``. The same module is imported by the unit testsunder ``tests/test_pr_diff_verifier.py`` so the in-container behaviorstays in lockstep with what we test."""
from __future__ import annotations
import argparseimport difflibimport jsonimport mathimport osimport reimport sysimport urllib.errorimport urllib.request
# ---------------------------------------------------------------------------# Parsing helpers (shared by multiple components)# ---------------------------------------------------------------------------
_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")_INDEX_RE = re.compile(r"^index ")
def file_paths(diff: str) -> set[str]: """Return the set of ``b/<path>`` paths touched by a unified diff.""" paths: set[str] = set() for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: paths.add(m.group(2)) return paths
def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: """For each touched file, return list of (start_line, end_line) ranges on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). """ out: dict[str, list[tuple[int, int]]] = {} current_file: str | None = None for line in diff.splitlines(): m = _DIFF_HEADER_RE.match(line) if m: current_file = m.group(2) out.setdefault(current_file, []) continue m = _HUNK_HEADER_RE.match(line) if m and current_file is not None: new_start = int(m.group(3)) new_count = int(m.group(4) or "1") end = new_start + max(new_count - 1, 0) out[current_file].append((new_start, end)) return out
def _normalize_changes_only(diff: str) -> list[str]: """Return the +/- lines (the actual changes) for similarity scoring.
Drops: - ``diff --git`` / ``index abc..def`` metadata - ``@@ ... @@`` hunk markers (volatile line numbers) - context lines (no +/- prefix) — these are unchanged code, scoring them inflates similarity for trivial patches Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity stays in the comparison; normalizes off the tab+timestamp suffix git sometimes appends. """ out: list[str] = [] for line in diff.splitlines(): if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): continue if _HUNK_HEADER_RE.match(line): continue if _FILE_MARKER_RE.match(line): out.append(line.split("\t")[0].strip()) continue # +/- lines (actual changes) if line.startswith("+") or line.startswith("-"): out.append(line) return out
# ---------------------------------------------------------------------------# Reward components# ---------------------------------------------------------------------------
def format_valid(predicted: str) -> float: """1.0 if the predicted text looks like a unified diff; else 0.0.
Requires both a ``diff --git`` header and at least one real +/- line (not the ``---`` / ``+++`` file-marker lines). """ if not predicted.strip(): return 0.0 has_header = False has_change = False for line in predicted.splitlines(): if _DIFF_HEADER_RE.match(line): has_header = True elif (line.startswith("+") or line.startswith("-")) and not line.startswith( ("+++ ", "--- ") ): has_change = True if has_header and has_change: return 1.0 return 0.0
def file_targeting(oracle: str, predicted: str) -> float: """F1 over the changed-file sets.
Why F1 instead of Jaccard: - Missing an oracle file (FN) is a *big* failure. - Touching one unrelated extra file (FP) is a small one. - Jaccard punishes both equally, which over-penalizes the agent for any extra exploration. - F1 weights TP twice, giving partial credit when the agent finds most-but-not-all of the oracle files even with some noise.
Returns 1.0 if both sides touch zero files (degenerate). """ o = file_paths(oracle) p = file_paths(predicted) if not o and not p: return 1.0 tp = len(o & p) fn = len(o - p) fp = len(p - o) if tp == 0: return 0.0 # F1 = 2·TP / (2·TP + FN + FP) return (2 * tp) / (2 * tp + fn + fp)
def _count_loc_changes(diff: str) -> int: """Number of real +/- lines (excluding file-marker lines).""" n = 0 for line in diff.splitlines(): if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): n += 1 return n
def size_sanity(oracle: str, predicted: str) -> float: """Penalize predicted patches that are wildly larger / smaller than the oracle.
Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
This is the "don't rampage through the codebase" guard — a 200-line diff for a 3-line oracle scores ~0.015 here even if every other component looks OK. """ o_loc = _count_loc_changes(oracle) p_loc = _count_loc_changes(predicted) if o_loc == 0 and p_loc == 0: return 1.0 if o_loc == 0 or p_loc == 0: return 0.0 return min(o_loc, p_loc) / max(o_loc, p_loc)
def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: """For each oracle hunk, did the predicted diff edit a line within ``slack_lines`` of that hunk in the same file?
Returns the fraction of oracle hunks that have at least one matching predicted hunk. ``slack_lines`` tolerates slight line-number drift when git diff renders the predicted hunk at a different offset. """ o_ranges = hunk_ranges(oracle) p_ranges = hunk_ranges(predicted) total = sum(len(v) for v in o_ranges.values()) if total == 0: return 1.0 # oracle has no hunks (degenerate) matched = 0 for fname, ranges in o_ranges.items(): p_in_file = p_ranges.get(fname, []) for o_start, o_end in ranges: for p_start, p_end in p_in_file: # Interval overlap with slack — max(starts) <= min(ends) + slack if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: matched += 1 break return matched / total
def similarity(oracle: str, predicted: str) -> float: """SequenceMatcher ratio over +/- lines only.
No free credit for context lines — fixes the v0.8.1 inflation where a one-line fix scored ~0.7 just because the 3 context lines on either side were "matched". """ if not predicted.strip(): return 0.0 o = _normalize_changes_only(oracle) p = _normalize_changes_only(predicted) if not o: return 0.0 # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can # run the verifier past Harbor's timeout. Above this many line pairs, # fall back to difflib's popular-element heuristic, which stays fast. exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
_SIMILARITY_EXACT_PAIRS = 400_000
# A predicted patch over 10x the oracle's changed lines is already a# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a# patch is a graded 0 instead of being scored, so one huge file can't slow# the verifier past its timeout and turn a failing episode into a dropped,# ungraded one. The byte cap stops it from being read at all._MAX_PREDICTED_FACTOR = 10_MAX_PREDICTED_FLOOR_LOC = 1_000_MAX_PREDICTED_BYTES = 16 * 1024 * 1024
def predicted_too_large(oracle: str, predicted: str) -> bool: """Whether the predicted patch is too large to score (a graded 0).""" limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) return _count_loc_changes(predicted) > limit
# ---------------------------------------------------------------------------# LLM-as-judge (Anthropic Messages API, stdlib urllib)# ---------------------------------------------------------------------------
_JUDGE_PROMPT = ( "You are scoring a code-fix patch on whether it logically addresses the " "described issue. Output a single JSON object: " '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' "DO NOT use the oracle to grade. Score on:\n" " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" " - Is the change direction consistent with what the issue describes?\n" " - Is it a real attempt (not boilerplate, not no-op)?\n\n" "Issue:\n{instruction}\n\n" "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" "{oracle}\n\n" "Predicted:\n{predicted}\n\n" "Return ONLY the JSON object.")
_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses._PLACEHOLDER_API_KEY = "EMPTY"
def llm_judge( *, instruction: str, oracle: str, predicted: str, api_key: str, model: str = _DEFAULT_JUDGE_MODEL, timeout: int = 60, endpoint: str | None = None,) -> tuple[float | None, str]: """Return ``(score, status)``.
``score`` is a float in [0, 1] on success, ``None`` on failure. ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. ``output_limit`` means the judge exhausted its configured token budget (ungraded, even if a partial answer contains a score). ``parse`` means the provider's body isn't JSON or has the wrong shape (ungraded); a reply with no usable text (refusal, content filter, empty) or no valid score is ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never increases the other weights.
``endpoint`` — base URL of an OpenAI-compatible server. When set, the request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a bearer token, at temperature 0, and ``model`` must be given explicitly; otherwise it goes to Anthropic's Messages API unchanged. """ if not api_key: return None, "no_api_key" if endpoint and not model: return None, "no_judge_model" if not predicted.strip(): return 0.0, "empty_predicted"
# Truncate hard so we don't blow up the prompt for big diffs prompt = _JUDGE_PROMPT.format( instruction=instruction[:4000], oracle=oracle[:4000], predicted=predicted[:4000], ) payload: dict = { "model": model, "max_tokens": 200, "messages": [{"role": "user", "content": prompt}], } if endpoint: # Small self-hosted models are noisy judges at their default sampling # temperature (same input scoring 0.0 one call and 1.0 the next); pin # them to greedy. The Anthropic route keeps its defaults — the weights # were calibrated against them. payload["temperature"] = 0 url = endpoint.rstrip("/") + "/chat/completions" headers = { "authorization": f"Bearer {api_key}", "content-type": "application/json", } else: url = _ANTHROPIC_MESSAGES_URL headers = { "x-api-key": api_key, "anthropic-version": "2023-06-01", "content-type": "application/json", } body = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as resp: raw = resp.read().decode("utf-8") except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): return None, "network"
try: response = json.loads(raw) except json.JSONDecodeError: return None, "parse" # Provider-reported truncation is a grader capacity failure, not evidence # that the submitted patch is wrong. Reasoning models can spend the entire # output budget before producing visible text. Never grade a partial score. if isinstance(response, dict): choices = response.get("choices") if endpoint: if ( isinstance(choices, list) and choices and isinstance(choices[0], dict) and choices[0].get("finish_reason") == "length" ): return None, "output_limit" elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: return None, "output_limit" text = _judge_text(response, openai_compatible=bool(endpoint)) if text is None: return None, "parse"
# Pull the first JSON object out of the model's response m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) if not m: return None, "missing_score" try: obj = json.loads(m.group(0)) score = obj.get("score") except (json.JSONDecodeError, ValueError, TypeError): return None, "missing_score" if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): return None, "invalid_score" return float(score), "ok"
def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
A refusal or a content filter is a well-formed reply with no usable text. The agent's patch is in the prompt, so it can provoke one: that is ``""``, which grades 0, not ``None``, which leaves the run ungraded.
Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and ``content`` empty or holding partial text to discard. OpenAI-compatible: ``message.content`` is null with a ``refusal`` string or ``finish_reason: "content_filter"``. """ if not isinstance(payload, dict): return None if openai_compatible: choices = payload.get("choices") if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): return None message = choices[0].get("message") if not isinstance(message, dict): return None if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": return "" content = message.get("content") if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): # content parts return "".join( part.get("text", "") for part in content if isinstance(part, dict) and isinstance(part.get("text", ""), str) ) return None content = payload.get("content") if not isinstance(content, list): return None if payload.get("stop_reason") == "refusal": return "" return "".join( block["text"] for block in content if isinstance(block, dict) and block.get("type", "text") == "text" and isinstance(block.get("text"), str) )
# ---------------------------------------------------------------------------# Combination# ---------------------------------------------------------------------------
# Judge replies the agent can provoke: its patch text is part of the judge# prompt, so it can steer the answer away from a valid score. These are a# graded 0. An unreadable provider envelope (`parse`), missing configuration,# a disabled judge, transport errors and an exhausted judge output budget leave# the evaluation ungraded. Truncation alone cannot establish an incorrect patch._JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
def evaluation_status(judge_score: float | None, judge_status: str) -> str: """`graded` when the judge scored or the agent can have caused its failure.""" if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: return "graded" return "ungraded"
def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: """Combine declared components, requiring a positively weighted judge.
Without a judge score the result is 0. ``main`` records it as a graded 0 when the agent can have caused the judge failure, and otherwise writes no reward file, so Harbor reports the trial as VERIFIER_FAILED. """ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: return 0.0 if any(w > 0 and components.get(k) is None for k, w in weights.items()): return 0.0 return _weighted_mean(components, weights)
def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] if not available: return 0.0 # Relative weights need not sum to one. Scale first so large finite # overrides cannot overflow the numerator or denominator into NaN. scale = max(w for _, w in available) normalized = [(k, w / scale) for k, w in available] return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
# ---------------------------------------------------------------------------# Entry point (invoked by tests/test.sh inside the container)# ---------------------------------------------------------------------------
# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer# analysis grounded in per-task component data):## - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero# discriminative signal — its 0.05 weight was pure dead weight.# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.# Carrying both at 0.20 double-counts positional accuracy and# additionally penalizes legitimate alternative implementations.# - llm_judge → 0.50: only component capturing semantic correctness# independent of textual form; diverges informatively from# similarity on cases like tokenizers (judge=0.72, sim=0.08).# - region_overlap stays 0.20: strongest spatial-localization signal.# - file_targeting → 0.12: leading indicator, less correlated with the# rest than region/similarity are with each other.# - size_sanity → 0.08: useful outlier detector for catastrophic# over/under-generation (prettier=0.01, serde=0.08).## Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00._DEFAULT_WEIGHTS = { "format_valid": 0.00, "size_sanity": 0.08, "file_targeting": 0.12, "region_overlap": 0.20, "similarity": 0.10, "llm_judge": 0.50,}
# Hard cap: when size_sanity < this threshold, clamp final reward to# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating# the score on patches that are wildly the wrong size (catastrophic# over- or under-generation)._CATASTROPHIC_SIZE_THRESHOLD = 0.10_CATASTROPHIC_SIZE_CAP = 0.40
def _read_weights_from_env() -> dict[str, float]: """Override defaults via R2E_W_* env vars (set in container by harbor).""" overrides = { "format_valid": os.environ.get("R2E_W_FORMAT"), "size_sanity": os.environ.get("R2E_W_SIZE"), "file_targeting": os.environ.get("R2E_W_FILE"), "region_overlap": os.environ.get("R2E_W_REGION"), "similarity": os.environ.get("R2E_W_SIM"), "llm_judge": os.environ.get("R2E_W_JUDGE"), } out = dict(_DEFAULT_WEIGHTS) for k, v in overrides.items(): if v is None: continue try: value = float(v) if math.isfinite(value) and value >= 0: out[k] = value except (TypeError, ValueError): continue return out
def _judge_config_from_env() -> tuple[str, str, str | None]: """``(api_key, model, endpoint)`` for the judge, from the verifier env.
With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a self-hosted server won't have Haiku): when unset, ``model`` comes back as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of calling out. Without an endpoint the default Anthropic route is unchanged. """ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None model = os.environ.get("R2E_JUDGE_MODEL", "").strip() if endpoint: api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY return api_key, model, endpoint return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("oracle") parser.add_argument("predicted") parser.add_argument("instruction") parser.add_argument("--out-dir", default="/logs/verifier") args = parser.parse_args(argv) os.makedirs(args.out_dir, exist_ok=True) # This run is the only authority on the reward: an earlier or planted # reward file must not stand if this evaluation ends up ungraded. for name in ("reward.txt", "reward.json"): try: os.unlink(os.path.join(args.out_dir, name)) except FileNotFoundError: pass oracle = _read_or_empty(args.oracle) try: oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES except OSError: oversized = False predicted = "" if oversized else _read_or_empty(args.predicted) if oversized or predicted_too_large(oracle, predicted): breakdown = { "final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": False, "predicted_status": "predicted_too_large", } _write_outputs(args.out_dir, 0.0, breakdown) return 0 instruction = _read_or_empty(args.instruction) api_key, judge_model, judge_endpoint = _judge_config_from_env()
fv = format_valid(predicted) ss = size_sanity(oracle, predicted) ft = file_targeting(oracle, predicted) ro = region_overlap(oracle, predicted) sim = similarity(oracle, predicted) weights = _read_weights_from_env() if weights["llm_judge"] <= 0: judge_score, judge_status = None, "disabled" else: judge_score, judge_status = llm_judge( instruction=instruction, oracle=oracle, predicted=predicted, api_key=api_key, model=judge_model, endpoint=judge_endpoint, )
components: dict[str, float | None] = { "format_valid": fv, "size_sanity": ss, "file_targeting": ft, "region_overlap": ro, "similarity": sim, "llm_judge": judge_score, } final = combine(components, weights) final = max(0.0, min(1.0, final))
# Hard cap on catastrophic size mismatches. Without this, a charitable # judge can inflate the reward on patches that are dramatically the # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge # was lenient at 0.25 despite the patch being a near-no-op vs a # 500-line oracle). The cap kicks in only at the extremes. if ss < _CATASTROPHIC_SIZE_THRESHOLD: final = min(final, _CATASTROPHIC_SIZE_CAP)
status = evaluation_status(judge_score, judge_status) breakdown = { # No reward exists for an ungraded evaluation: null, not a placeholder 0. "final_reward": round(final, 6) if status == "graded" else None, "evaluation_status": status, "eval_trustworthy": judge_score is not None, "diagnostic_similarity": round( _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), 6, ), "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, "weights": {k: round(v, 6) for k, v in weights.items()}, "judge_model": judge_model if judge_status == "ok" else None, "judge_endpoint": judge_endpoint, "judge_status": judge_status, }
_write_outputs(args.out_dir, final, breakdown) return 0
def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: # An ungraded evaluation writes no reward file. Harbor then raises # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout # instead of training on a 0. Harbor's job mean and pass@k still count the # trial as 0, so evaluation stays fail-closed. if breakdown["evaluation_status"] == "graded": with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: f.write(f"{final:.6f}\n") # Harbor's `reward.json` must be a flat map of floats/ints (spec, see # <https://harborframework.com/docs/tasks>); our breakdown carries nested # dicts, judge strings, and status strings, so it goes to the sidecar the # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) # for `_pr_runtime_verifier.py`. with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: json.dump(breakdown, f, indent=2)
# Also print to stdout so harbor's log captures the breakdown print(json.dumps(breakdown, indent=2))
def _read_or_empty(path: str) -> str: try: with open(path, encoding="utf-8") as f: return f.read() except (OSError, UnicodeDecodeError): return ""
if __name__ == "__main__": sys.exit(main())
__all__ = [ "combine", "file_paths", "file_targeting", "format_valid", "hunk_ranges", "llm_judge", "main", "predicted_too_large", "region_overlap", "similarity", "size_sanity",]12345678910111213141516171819202122232425262728293031323334353637# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.# Agent-agnostic: the agent (claude-code / openhands / codex / etc.)# installs itself at run time via its harbor adapter. We only ship# the source repo — the oracle + verifier arrive at verify time via# tests/, never baked into the agent's image.FROM python:3.12-slimARG GITHUB_TOKEN=RUN apt-get update \ && apt-get install -y --no-install-recommends git ca-certificates curl \ && rm -rf /var/lib/apt/lists/*RUN git config --global --add safe.directory /workspace \ && git config --global init.defaultBranch main \ && git config --global advice.detachedHead falseRUN if [ -n "$GITHUB_TOKEN" ]; then \ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ublue-os/bazzite.git /workspace; \ else \ git clone --filter=blob:none https://github.com/ublue-os/bazzite.git /workspace; \ fi \ && git -C /workspace remote set-url origin https://github.com/ublue-os/bazzite.gitWORKDIR /workspaceRUN git fetch --depth 1 origin 6ef839120b2a224f8aa718cc1c855be96cea50aa 2>/dev/null \ || git fetch --unshallow origin 2>/dev/null || trueRUN git reset --hard 6ef839120b2a224f8aa718cc1c855be96cea50aa \ && git clean -fdx -e .venv -e venv -e __pycache__RUN git checkout -q -B base 6ef839120b2a224f8aa718cc1c855be96cea50aa \ && git remote remove origin 2>/dev/null || trueRUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ && git reflog expire --expire=now --all 2>/dev/null || true \ && git gc --prune=now 2>/dev/null || trueRUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ fi123456789101112131415161718192021# Issue
**Title:** [FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices.
## Description
After the TSC patch got merged in the OGC kernel (), devices with flawed TSC will not have this clocksource enabled by default. Ideally, Bazzite shouldn't enable ```tsc=directsync``` by default for devices that already support this clocksouce and have 0 issues (And I doubt it would affect those devices too, but I can't test this theory)
So I came up with a script that checks if the CPU has support for TSC but it defaults to HPET/ACPI_PM. If the statement is true, it will run the kargs command to add ```tsc=directsync```. The reasons why this script must exist is to:1. Ease the debugging process for devices with buggy TSC that cause system instabilities (either because they default to HPET or they force TSC one way or another)2. Gives a seamless experience and less friction for affected devices. Basically an out-of-the-box experience (as it should be).
I have tested this script beforehand and it works the way I thought it should. In theory, this can be improved by checking journalctl for tsc errors (or dmesg), but I wanted to keep it simple.
Another idea I had was to have this as an ujust command, but it goes against the philosophy of OOTB experience I was aiming for.
Please let me know if there is room for improvement or if I have to fix anything.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6ef839120b2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.1234567891011121314151617181920212223242526272829303132333435363738diff --git a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setupindex a55f4635..ac844d24 100755--- a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup+++ b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup@@ -255,6 +255,33 @@ if [[ -f "/var/lib/waydroid/lxc/waydroid/config" ]]; then sed -i '/lxc\.apparmor\.profile\s*=\s*unconfined/d' "/var/lib/waydroid/lxc/waydroid/config" fi +#Enable TSC directsync after patch+set -eu+if [ ! -r /proc/cpuinfo ]; then+ echo "Cannot read /proc/cpuinfo; unable to check TSC support." >&2+ exit 1+fi+clocksource_file=/sys/devices/system/clocksource/clocksource0/current_clocksource+if [ -r "$clocksource_file" ]; then+ current_clocksource=$(cat "$clocksource_file")+else+ current_clocksource=unknown+fi+if awk '+ /^flags[[:space:]]*:/ {+ for (i = 2; i <= NF; i++) {+ if ($i == "tsc") found = 1+ }+ }+ END { exit !found }+' /proc/cpuinfo &&+ ! { [ "$current_clocksource" = hpet ] ||+ [ "$current_clocksource" = acpi_pm ]; }; then+ echo "CPU reports TSC support."+else+ sudo rpm-ostree kargs --append-if-missing=tsc=directsync+fi+ # HIBERNATION if /usr/libexec/hwsupport/needs-hibernation; then if [[ ! -f /etc/bazzite/hibernation_enabled ]]; then123456#!/bin/bashset -euxo pipefailcd /workspacegit config --global --add safe.directory /workspacePATCH="$(dirname "$0")/patch.diff"git apply --verbose --reject "$PATCH"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768version = "1.0"
[task]name = "trending/ublue-os__bazzite-6243"description = "[FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices."
[metadata]difficulty = "medium"category = "bugfix"keywords = [ "bazzite", "pr_diff",]
[metadata.repo2env]pipeline = "pr_diff"pipeline_version = "0.3.0"repo = "ublue-os/bazzite"ref = "6ef839120b2a224f8aa718cc1c855be96cea50aa"reference = "https://github.com/ublue-os/bazzite/pull/6243"source_access = "auto"built_at = "2026-11-16T16:09:50.973122+00:00"reward_kinds = [ "diff_similarity",]spec_version = "0.2.0"content_hash = "sha256:a8e6adc9c3eb9c47790594eff92c0a54d264138155c4457e5217ff78507d1d60"
[metadata.repo2env.pr_diff]pr_merged_at = "2026-11-05T17:11:52Z"diff_format = "unified"context_files = [ "system_files/desktop/shared/usr/libexec/bazzite-hardware-setup",]bootstrap_image = "python:3.12-slim"
[metadata.repo2env.reward_calibration]baseline_reward = 0.0loc_changed = 27difficulty = "medium"
[metadata.repo2env.evaluation]schema_version = "1"status = "unverified"stage = "generation"reason_codes = [ "validation_not_run",]detail = "Generated task; validation has not been established."provenance = "unknown"evidence = []
[metadata.repo2env.reproducibility]mode = "inline_dockerfile"image_ref = "python:3.12-slim"image_tag = "python:3.12-slim"image_visibility = "public"pushed_at = "2026-11-16T16:20:03.589542+00:00"pushed_by = "scalingX"inline_recipe_sha256 = "sha256:eb02bdf5b9afc8d6ff630ee92be3b4e118a7d702fdb5ee49b13e7c84d4692ad3"inline_recipe_lines = 37inline_recipe_source = "user_dockerfile"
[agent]timeout_sec = 1800.0
[verifier]timeout_sec = 300.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Standalone PR-diff capture without executing workspace Git configuration.
The emitted task uses a regular clone with a pinned base commit. Only itsobject store is read: refs, index, config, hooks and replacement refs are notused. This is a configuration boundary, not a sandbox for a malicious processthat can modify the verifier, binaries or object store while capture runs."""
from __future__ import annotations
import argparseimport jsonimport osimport reimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
def capture(workspace: Path, base_commit: str) -> bytes: """Capture tracked and new files through a fresh private Git index.""" if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): raise ValueError("Expected the task's pinned SHA-1 base commit") objects = workspace.resolve() / ".git" / "objects" if not objects.is_dir(): raise ValueError("The task's cloned Git object store is missing") git = shutil.which("git", path=os.defpath) if git is None: raise FileNotFoundError("System git is unavailable") with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: private = Path(temporary) # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, # system/global includes, user attributes, templates or credential env. env = { "PATH": os.defpath, "HOME": temporary, "XDG_CONFIG_HOME": temporary, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ATTR_NOSYSTEM": "1", "GIT_NO_REPLACE_OBJECTS": "1", "GIT_NO_LAZY_FETCH": "1", "GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C", } subprocess.run( [git, "init", "--quiet", "--template=", str(private / "repository")], env=env, cwd=private, check=True, capture_output=True, timeout=60, ) env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) command = [ git, f"--git-dir={private / 'repository/.git'}", f"--work-tree={workspace.resolve()}", ]
def run(*args: str) -> bytes: return subprocess.run( [*command, *args], env=env, cwd=workspace, check=True, capture_output=True, timeout=60, ).stdout
run("read-tree", f"{base_commit}^{{tree}}") # All filter drivers are undefined in the private configuration. The # workspace's clean filters, fsmonitor and hooks cannot be invoked. run("add", "--all", "--", ".") return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("workspace", type=Path) parser.add_argument("base_commit") args = parser.parse_args(argv) try: patch = capture(args.workspace, args.base_commit) except (OSError, ValueError, subprocess.SubprocessError) as exc: # Do not echo child stderr: it may contain workspace-controlled data. sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") return 1 sys.stdout.buffer.write(patch) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021# Issue
**Title:** [FEATURE] bazzite-hardware-setup -> Include TSC directsync for affected devices.
## Description
After the TSC patch got merged in the OGC kernel (), devices with flawed TSC will not have this clocksource enabled by default. Ideally, Bazzite shouldn't enable ```tsc=directsync``` by default for devices that already support this clocksouce and have 0 issues (And I doubt it would affect those devices too, but I can't test this theory)
So I came up with a script that checks if the CPU has support for TSC but it defaults to HPET/ACPI_PM. If the statement is true, it will run the kargs command to add ```tsc=directsync```. The reasons why this script must exist is to:1. Ease the debugging process for devices with buggy TSC that cause system instabilities (either because they default to HPET or they force TSC one way or another)2. Gives a seamless experience and less friction for affected devices. Basically an out-of-the-box experience (as it should be).
I have tested this script beforehand and it works the way I thought it should. In theory, this can be improved by checking journalctl for tsc errors (or dmesg), but I wanted to keep it simple.
Another idea I had was to have this as an ujust command, but it goes against the philosophy of OOTB experience I was aiming for.
Please let me know if there is room for improvement or if I have to fix anything.
## Task
Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6ef839120b2a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.1234567891011121314151617181920212223242526272829303132333435363738diff --git a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setupindex a55f4635..ac844d24 100755--- a/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup+++ b/system_files/desktop/shared/usr/libexec/bazzite-hardware-setup@@ -255,6 +255,33 @@ if [[ -f "/var/lib/waydroid/lxc/waydroid/config" ]]; then sed -i '/lxc\.apparmor\.profile\s*=\s*unconfined/d' "/var/lib/waydroid/lxc/waydroid/config" fi +#Enable TSC directsync after patch+set -eu+if [ ! -r /proc/cpuinfo ]; then+ echo "Cannot read /proc/cpuinfo; unable to check TSC support." >&2+ exit 1+fi+clocksource_file=/sys/devices/system/clocksource/clocksource0/current_clocksource+if [ -r "$clocksource_file" ]; then+ current_clocksource=$(cat "$clocksource_file")+else+ current_clocksource=unknown+fi+if awk '+ /^flags[[:space:]]*:/ {+ for (i = 2; i <= NF; i++) {+ if ($i == "tsc") found = 1+ }+ }+ END { exit !found }+' /proc/cpuinfo &&+ ! { [ "$current_clocksource" = hpet ] ||+ [ "$current_clocksource" = acpi_pm ]; }; then+ echo "CPU reports TSC support."+else+ sudo rpm-ostree kargs --append-if-missing=tsc=directsync+fi+ # HIBERNATION if /usr/libexec/hwsupport/needs-hibernation; then if [[ ! -f /etc/bazzite/hibernation_enabled ]]; thentasks/ublue-os__bazzite-6216/tests/test.shAdded+25
tasks/ublue-os__bazzite-6216/tests/verifier.pyAdded+737
tasks/ublue-os__bazzite-6229/environment/DockerfileAdded+37
tasks/ublue-os__bazzite-6229/instruction.mdAdded+32
tasks/ublue-os__bazzite-6229/solution/patch.diffAdded+176
tasks/ublue-os__bazzite-6229/solution/solve.shAdded+6
tasks/ublue-os__bazzite-6229/task.tomlAdded+72
tasks/ublue-os__bazzite-6229/tests/capture.pyAdded+96
tasks/ublue-os__bazzite-6229/tests/instruction.mdAdded+32
tasks/ublue-os__bazzite-6229/tests/oracle.patchAdded+176
tasks/ublue-os__bazzite-6229/tests/test.shAdded+25
tasks/ublue-os__bazzite-6229/tests/verifier.pyAdded+737
tasks/ublue-os__bazzite-6231/environment/DockerfileAdded+37
tasks/ublue-os__bazzite-6231/instruction.mdAdded+41
tasks/ublue-os__bazzite-6231/solution/patch.diffAdded+22
tasks/ublue-os__bazzite-6231/solution/solve.shAdded+6
tasks/ublue-os__bazzite-6231/task.tomlAdded+68
tasks/ublue-os__bazzite-6231/tests/capture.pyAdded+96
tasks/ublue-os__bazzite-6231/tests/instruction.mdAdded+41
tasks/ublue-os__bazzite-6231/tests/oracle.patchAdded+22
tasks/ublue-os__bazzite-6231/tests/test.shAdded+25
tasks/ublue-os__bazzite-6231/tests/verifier.pyAdded+737
tasks/ublue-os__bazzite-6232/environment/DockerfileAdded+37
tasks/ublue-os__bazzite-6232/instruction.mdAdded+31
tasks/ublue-os__bazzite-6232/solution/patch.diffAdded+15
tasks/ublue-os__bazzite-6232/solution/solve.shAdded+6
tasks/ublue-os__bazzite-6232/task.tomlAdded+68
tasks/ublue-os__bazzite-6232/tests/capture.pyAdded+96
tasks/ublue-os__bazzite-6232/tests/instruction.mdAdded+31
tasks/ublue-os__bazzite-6232/tests/oracle.patchAdded+15
tasks/ublue-os__bazzite-6232/tests/test.shAdded+25
tasks/ublue-os__bazzite-6232/tests/verifier.pyAdded+737
tasks/ublue-os__bazzite-6234/environment/DockerfileAdded+37
tasks/ublue-os__bazzite-6234/instruction.mdAdded+20
tasks/ublue-os__bazzite-6234/solution/patch.diffAdded+189
tasks/ublue-os__bazzite-6234/solution/solve.shAdded+6
tasks/ublue-os__bazzite-6234/task.tomlAdded+68
tasks/ublue-os__bazzite-6234/tests/capture.pyAdded+96
tasks/ublue-os__bazzite-6234/tests/instruction.mdAdded+20
tasks/ublue-os__bazzite-6234/tests/oracle.patchAdded+189
tasks/ublue-os__bazzite-6234/tests/test.shAdded+25
tasks/ublue-os__bazzite-6234/tests/verifier.pyAdded+737
tasks/ublue-os__bazzite-6243/environment/DockerfileAdded+37
tasks/ublue-os__bazzite-6243/instruction.mdAdded+21
tasks/ublue-os__bazzite-6243/solution/patch.diffAdded+38
tasks/ublue-os__bazzite-6243/solution/solve.shAdded+6
tasks/ublue-os__bazzite-6243/task.tomlAdded+68
tasks/ublue-os__bazzite-6243/tests/capture.pyAdded+96
tasks/ublue-os__bazzite-6243/tests/instruction.mdAdded+21
tasks/ublue-os__bazzite-6243/tests/oracle.patchAdded+38