diff --git a/tasks/ibhagwan__fzf-lua-2520/tests/test.sh b/tasks/ibhagwan__fzf-lua-2520/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4a0801688f55cf0383961836a577abd0c23fc52 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2520/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d9908fd0a5474994f00526ed17f0b77339dc0152 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2520/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2520/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2520/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2523/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2523/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..975617cd7a725fdf4cb825822d1c79f059ac113c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin abe5ecafebb4e24feb162384d5f492431036e791 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard abe5ecafebb4e24feb162384d5f492431036e791 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base abe5ecafebb4e24feb162384d5f492431036e791 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2523/instruction.md b/tasks/ibhagwan__fzf-lua-2523/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42ba93b5c912c330f76e29bfc9355553c2b482a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(#2522): should safely abort confirm() + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abe5ecafebb4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2523/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2523/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4cfb97840e492d58767ba28e2446639128a929ee --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/solution/patch.diff @@ -0,0 +1,99 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 16284119..5b1f57d3 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -931,7 +931,7 @@ M.git_branch_del = function(selected, opts) + utils.warn("Cannot delete active branch '%s'", branch) + return + end +- if vim.fn.confirm("Delete branch " .. branch .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Delete branch " .. branch .. "?", "&Yes\n&No") == 1 then + table.insert(cmd_del_branch, branch) + local output, rc = utils.io_systemlist(cmd_del_branch) + if rc ~= 0 then +@@ -998,7 +998,7 @@ M.git_worktree_del = function(selected, opts) + utils.warn("Cannot delete current worktree '%s'", worktree_path) + return + end +- if vim.fn.confirm("Delete worktree " .. worktree_path .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Delete worktree " .. worktree_path .. "?", "&Yes\n&No") == 1 then + local cmd_del = path.git_cwd({ "git", "worktree", "remove", worktree_path }, opts) ---@type string[] + local output, rc = utils.io_systemlist(cmd_del) + if rc ~= 0 then +@@ -1045,7 +1045,7 @@ M.git_checkout = function(selected, opts) + local commit_hash = match_commit_hash(selected[1], opts) + local current_commit = utils.io_systemlist(cmd_cur_commit)[1] + if commit_hash == current_commit then return end +- if vim.fn.confirm("Checkout commit " .. commit_hash .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Checkout commit " .. commit_hash .. "?", "&Yes\n&No") == 1 then + local cmd_checkout = path.git_cwd({ "git", "checkout" }, opts) + table.insert(cmd_checkout, commit_hash) + local output, rc = utils.io_systemlist(cmd_checkout) +@@ -1103,7 +1103,7 @@ M.git_stage_unstage = function(selected, opts) + end + + M.git_reset = function(selected, opts) +- if vim.fn.confirm("Reset " .. #selected .. " file(s)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Reset " .. #selected .. " file(s)?", "&Yes\n&No") == 1 then + for _, s in ipairs(selected) do + s = utils.strip_ansi_coloring(s) + local is_untracked = s:sub(5, 5) == "?" +@@ -1118,14 +1118,14 @@ M.git_reset = function(selected, opts) + end + + M.git_stash_drop = function(selected, opts) +- if vim.fn.confirm("Drop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Drop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "drop" }, opts) + git_exec(selected, opts, cmd) + end + end + + M.git_stash_pop = function(selected, opts) +- if vim.fn.confirm("Pop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Pop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "pop" }, opts) + git_exec(selected, opts, cmd) + -- trigger autoread or warn the users buffer(s) was changed +@@ -1134,7 +1134,7 @@ M.git_stash_pop = function(selected, opts) + end + + M.git_stash_apply = function(selected, opts) +- if vim.fn.confirm("Apply " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Apply " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "apply" }, opts) + git_exec(selected, opts, cmd) + -- trigger autoread or warn the users buffer(s) was changed +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index fcd25539..9d6039d5 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1055,7 +1055,7 @@ function M.save_dialog(bufnr) + M.warn(string.format("buffer %d has unsaved changes", bufnr)) + return false + end +- local res = vim.fn.confirm(string.format([[Save changes to "%s"?]], info.name), ++ local res = M.confirm(string.format([[Save changes to "%s"?]], info.name), + "&Yes\n&No\n&Cancel") + if res == 0 or res == 3 then + -- user cancelled +@@ -1335,6 +1335,19 @@ function M.input(prompt, default) + return ok and res or nil + end + ++-- wrapper around |confirm()| to allow cancellation with `` ++---@param msg string ++---@param choice? string ++---@param default? integer ++---@param ty? string ++---@return integer ++function M.confirm(msg, choice, default, ty) ++ local ok, res = pcall(vim.fn.confirm, msg, choice, default, ty) ++ if ok and type(res) == "number" then return res end ++ if type(res) == "string" and res:match("Keyboard interrupt") then return 0 end -- ++ error(res) ++end ++ + function M.fzf_bind_to_neovim(key) + local conv_map = { + ["alt"] = "A", diff --git a/tasks/ibhagwan__fzf-lua-2523/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2523/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2523/task.toml b/tasks/ibhagwan__fzf-lua-2523/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..74177071adf2ee1f2b9d07a875b24b095a4f961c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2523" +description = "fix(#2522): should safely abort confirm()" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "abe5ecafebb4e24feb162384d5f492431036e791" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2523" +source_access = "auto" +built_at = "2026-11-16T16:09:56.080171+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a71723a985d85b1ea40793f925008eda3906178207de81df86b14f2ee951ba14" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-19T10:18:51Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +difficulty = "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:01.016342+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f6124650ea22be02accfcc03a379e88887fa028d17d9e25d74a19f90ee3a48ad" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2523/tests/capture.py b/tasks/ibhagwan__fzf-lua-2523/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2523/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2523/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42ba93b5c912c330f76e29bfc9355553c2b482a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(#2522): should safely abort confirm() + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abe5ecafebb4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2523/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2523/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4cfb97840e492d58767ba28e2446639128a929ee --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/tests/oracle.patch @@ -0,0 +1,99 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 16284119..5b1f57d3 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -931,7 +931,7 @@ M.git_branch_del = function(selected, opts) + utils.warn("Cannot delete active branch '%s'", branch) + return + end +- if vim.fn.confirm("Delete branch " .. branch .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Delete branch " .. branch .. "?", "&Yes\n&No") == 1 then + table.insert(cmd_del_branch, branch) + local output, rc = utils.io_systemlist(cmd_del_branch) + if rc ~= 0 then +@@ -998,7 +998,7 @@ M.git_worktree_del = function(selected, opts) + utils.warn("Cannot delete current worktree '%s'", worktree_path) + return + end +- if vim.fn.confirm("Delete worktree " .. worktree_path .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Delete worktree " .. worktree_path .. "?", "&Yes\n&No") == 1 then + local cmd_del = path.git_cwd({ "git", "worktree", "remove", worktree_path }, opts) ---@type string[] + local output, rc = utils.io_systemlist(cmd_del) + if rc ~= 0 then +@@ -1045,7 +1045,7 @@ M.git_checkout = function(selected, opts) + local commit_hash = match_commit_hash(selected[1], opts) + local current_commit = utils.io_systemlist(cmd_cur_commit)[1] + if commit_hash == current_commit then return end +- if vim.fn.confirm("Checkout commit " .. commit_hash .. "?", "&Yes\n&No") == 1 then ++ if utils.confirm("Checkout commit " .. commit_hash .. "?", "&Yes\n&No") == 1 then + local cmd_checkout = path.git_cwd({ "git", "checkout" }, opts) + table.insert(cmd_checkout, commit_hash) + local output, rc = utils.io_systemlist(cmd_checkout) +@@ -1103,7 +1103,7 @@ M.git_stage_unstage = function(selected, opts) + end + + M.git_reset = function(selected, opts) +- if vim.fn.confirm("Reset " .. #selected .. " file(s)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Reset " .. #selected .. " file(s)?", "&Yes\n&No") == 1 then + for _, s in ipairs(selected) do + s = utils.strip_ansi_coloring(s) + local is_untracked = s:sub(5, 5) == "?" +@@ -1118,14 +1118,14 @@ M.git_reset = function(selected, opts) + end + + M.git_stash_drop = function(selected, opts) +- if vim.fn.confirm("Drop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Drop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "drop" }, opts) + git_exec(selected, opts, cmd) + end + end + + M.git_stash_pop = function(selected, opts) +- if vim.fn.confirm("Pop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Pop " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "pop" }, opts) + git_exec(selected, opts, cmd) + -- trigger autoread or warn the users buffer(s) was changed +@@ -1134,7 +1134,7 @@ M.git_stash_pop = function(selected, opts) + end + + M.git_stash_apply = function(selected, opts) +- if vim.fn.confirm("Apply " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then ++ if utils.confirm("Apply " .. #selected .. " stash(es)?", "&Yes\n&No") == 1 then + local cmd = path.git_cwd({ "git", "stash", "apply" }, opts) + git_exec(selected, opts, cmd) + -- trigger autoread or warn the users buffer(s) was changed +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index fcd25539..9d6039d5 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1055,7 +1055,7 @@ function M.save_dialog(bufnr) + M.warn(string.format("buffer %d has unsaved changes", bufnr)) + return false + end +- local res = vim.fn.confirm(string.format([[Save changes to "%s"?]], info.name), ++ local res = M.confirm(string.format([[Save changes to "%s"?]], info.name), + "&Yes\n&No\n&Cancel") + if res == 0 or res == 3 then + -- user cancelled +@@ -1335,6 +1335,19 @@ function M.input(prompt, default) + return ok and res or nil + end + ++-- wrapper around |confirm()| to allow cancellation with `` ++---@param msg string ++---@param choice? string ++---@param default? integer ++---@param ty? string ++---@return integer ++function M.confirm(msg, choice, default, ty) ++ local ok, res = pcall(vim.fn.confirm, msg, choice, default, ty) ++ if ok and type(res) == "number" then return res end ++ if type(res) == "string" and res:match("Keyboard interrupt") then return 0 end -- ++ error(res) ++end ++ + function M.fzf_bind_to_neovim(key) + local conv_map = { + ["alt"] = "A", diff --git a/tasks/ibhagwan__fzf-lua-2523/tests/test.sh b/tasks/ibhagwan__fzf-lua-2523/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d0b41e52bf130cfaeedeb3eeeea3d3ed0f593dca --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace abe5ecafebb4e24feb162384d5f492431036e791 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2523/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2523/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2523/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2524/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2524/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..100232379159f393aa59e7d06f66180c317cb642 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c3714dfc25d056fc6afe17d331b3802e3469694c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c3714dfc25d056fc6afe17d331b3802e3469694c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c3714dfc25d056fc6afe17d331b3802e3469694c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2524/instruction.md b/tasks/ibhagwan__fzf-lua-2524/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec75eba58cd0fe90fa8c32ed74bc81eff2ae661 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** ci fixes + +## Description + +- **ci: mini.nvim rename error_expect -> error_with_emphasis** +- **ci: pin luals to 3.16.4** + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c3714dfc25d0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2524/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2524/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44fb660d40140dcf8958492bf35c12a5bff4eade --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/solution/patch.diff @@ -0,0 +1,87 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index b5496d6f..d0909085 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -24,7 +24,7 @@ jobs: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd +- gh release download -R sumneko/lua-language-server -p '*-linux-x64.tar.gz' -D lua-language-server ++ gh release download 3.16.4 -R sumneko/lua-language-server -p '*-linux-x64.tar.gz' -D lua-language-server + tar xzf lua-language-server/* -C lua-language-server + echo "${PWD}/lua-language-server/bin" >> $GITHUB_PATH + export PATH="${PWD}/lua-language-server/bin:${PATH}" +diff --git a/.luarc.jsonc b/.luarc.jsonc +index f7e9e238..93a729cd 100644 +--- a/.luarc.jsonc ++++ b/.luarc.jsonc +@@ -30,8 +30,6 @@ + "unknown-diag-code", + "unknown-cast-variable", + "luadoc-miss-local-name", +- // disable as buggy since 3.17.0 +- "need-check-nil", + ], + "unusedLocalExclude": ["_*"], + }, +diff --git a/lua/fzf-lua/make_entry.lua b/lua/fzf-lua/make_entry.lua +index e3eec526..1cecd15a 100644 +--- a/lua/fzf-lua/make_entry.lua ++++ b/lua/fzf-lua/make_entry.lua +@@ -246,7 +246,9 @@ local glob_filter = function(paths, globs) + -- matchers = vim.tbl_map(vim.F.nil_wrap(vim.glob.to_lpeg), globs) + if #matchers == 0 then return paths end + return vim.tbl_filter(function(p) +- return vim.iter(matchers):all(function(m) return m:match_str(p) end) ++ local stat = vim.uv.fs_stat(p) -- "--iglob" can filter directory correctly ++ return (stat and stat.type == "directory") or ++ vim.iter(matchers):all(function(m) return m:match_str(p) end) + end, paths) + end + +@@ -343,7 +345,7 @@ M.get_grep_cmd = function(opts, search_query, no_esc) + for i, p in ipairs(search_paths) do + search_paths[i] = path.relative_to(path.normalize(p), utils.cwd()) + end +- search_paths = glob_filter(search_paths, globs) ++ search_paths = opts.rg_glob and glob_filter(search_paths, globs) or search_paths + search_path = table.concat(vim.tbl_map(libuv.shellescape, search_paths), " ") + if is_grep then + -- grep requires adding `-r` to command as paths can be either file or directory +diff --git a/lua/fzf-lua/shell.lua b/lua/fzf-lua/shell.lua +index 8179e7ca..5d5817e8 100644 +--- a/lua/fzf-lua/shell.lua ++++ b/lua/fzf-lua/shell.lua +@@ -139,7 +139,9 @@ function M.pipe_wrap_fn(fn, fzf_field_index, debug) + utils.get_info().selected = args[1] and args[1][1] or nil + uv.pipe_connect(pipe, pipe_path, function(err) + if err then +- error(string.format("pipe_connect(%s) failed with error: %s", pipe_path, err)) ++ ---@diagnostic disable-next-line: undefined-field ++ err = uv.translate_sys_error(uv.errno[err]) ++ utils.warn(string.format("pipe_connect(%s) failed with error: %s", pipe_path, err)) + else + vim.schedule(function() + fn(pipe, unpack(args)) +diff --git a/lua/fzf-lua/test/screenshot.lua b/lua/fzf-lua/test/screenshot.lua +index 5d31c847..3e3eedb4 100644 +--- a/lua/fzf-lua/test/screenshot.lua ++++ b/lua/fzf-lua/test/screenshot.lua +@@ -207,7 +207,7 @@ M.reference_screenshot = function(screenshot, path, opts) + local subject = "screenshot equality to reference at " .. vim.inspect(path) + local context = string.format("%s\nReference:\n%s\n\nObserved:\n%s", cause, tostring(reference), + tostring(screenshot)) +- H.error_expect(subject, context) ++ H.error_with_emphasis(subject, context) + end + + -- modified version (no attr, trim trailing whitespace) +@@ -233,7 +233,7 @@ M.compare = function(reference, screenshot, opts) + local context = string.format("%s\nReference:\n%s\n\nObserved:\n%s", cause, + ruler .. tostring(reference), + ruler .. tostring(screenshot)) +- H.error_expect(subject, context) ++ H.error_with_emphasis(subject, context) + end + + return M diff --git a/tasks/ibhagwan__fzf-lua-2524/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2524/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2524/task.toml b/tasks/ibhagwan__fzf-lua-2524/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7311567b1681e0998d98bad6a6cba5df4820c12c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2524" +description = "ci fixes" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "c3714dfc25d056fc6afe17d331b3802e3469694c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2524" +source_access = "auto" +built_at = "2026-11-16T16:09:56.078908+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4fc30bf52a1c6d30b70d14395f21e9c52e7321137ed4751558945b6e8f940843" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-20T03:59:30Z" +diff_format = "unified" +context_files = [ + ".github/workflows/lint.yaml", + ".luarc.jsonc", + "lua/fzf-lua/make_entry.lua", + "lua/fzf-lua/shell.lua", + "lua/fzf-lua/test/screenshot.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[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:01.016917+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2c8d36197c25681a941f81b49c22d335df00eb1d1481302d3d2af4b7da3d66fa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2524/tests/capture.py b/tasks/ibhagwan__fzf-lua-2524/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2524/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2524/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ec75eba58cd0fe90fa8c32ed74bc81eff2ae661 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** ci fixes + +## Description + +- **ci: mini.nvim rename error_expect -> error_with_emphasis** +- **ci: pin luals to 3.16.4** + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c3714dfc25d0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2524/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2524/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44fb660d40140dcf8958492bf35c12a5bff4eade --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/tests/oracle.patch @@ -0,0 +1,87 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index b5496d6f..d0909085 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -24,7 +24,7 @@ jobs: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + cd +- gh release download -R sumneko/lua-language-server -p '*-linux-x64.tar.gz' -D lua-language-server ++ gh release download 3.16.4 -R sumneko/lua-language-server -p '*-linux-x64.tar.gz' -D lua-language-server + tar xzf lua-language-server/* -C lua-language-server + echo "${PWD}/lua-language-server/bin" >> $GITHUB_PATH + export PATH="${PWD}/lua-language-server/bin:${PATH}" +diff --git a/.luarc.jsonc b/.luarc.jsonc +index f7e9e238..93a729cd 100644 +--- a/.luarc.jsonc ++++ b/.luarc.jsonc +@@ -30,8 +30,6 @@ + "unknown-diag-code", + "unknown-cast-variable", + "luadoc-miss-local-name", +- // disable as buggy since 3.17.0 +- "need-check-nil", + ], + "unusedLocalExclude": ["_*"], + }, +diff --git a/lua/fzf-lua/make_entry.lua b/lua/fzf-lua/make_entry.lua +index e3eec526..1cecd15a 100644 +--- a/lua/fzf-lua/make_entry.lua ++++ b/lua/fzf-lua/make_entry.lua +@@ -246,7 +246,9 @@ local glob_filter = function(paths, globs) + -- matchers = vim.tbl_map(vim.F.nil_wrap(vim.glob.to_lpeg), globs) + if #matchers == 0 then return paths end + return vim.tbl_filter(function(p) +- return vim.iter(matchers):all(function(m) return m:match_str(p) end) ++ local stat = vim.uv.fs_stat(p) -- "--iglob" can filter directory correctly ++ return (stat and stat.type == "directory") or ++ vim.iter(matchers):all(function(m) return m:match_str(p) end) + end, paths) + end + +@@ -343,7 +345,7 @@ M.get_grep_cmd = function(opts, search_query, no_esc) + for i, p in ipairs(search_paths) do + search_paths[i] = path.relative_to(path.normalize(p), utils.cwd()) + end +- search_paths = glob_filter(search_paths, globs) ++ search_paths = opts.rg_glob and glob_filter(search_paths, globs) or search_paths + search_path = table.concat(vim.tbl_map(libuv.shellescape, search_paths), " ") + if is_grep then + -- grep requires adding `-r` to command as paths can be either file or directory +diff --git a/lua/fzf-lua/shell.lua b/lua/fzf-lua/shell.lua +index 8179e7ca..5d5817e8 100644 +--- a/lua/fzf-lua/shell.lua ++++ b/lua/fzf-lua/shell.lua +@@ -139,7 +139,9 @@ function M.pipe_wrap_fn(fn, fzf_field_index, debug) + utils.get_info().selected = args[1] and args[1][1] or nil + uv.pipe_connect(pipe, pipe_path, function(err) + if err then +- error(string.format("pipe_connect(%s) failed with error: %s", pipe_path, err)) ++ ---@diagnostic disable-next-line: undefined-field ++ err = uv.translate_sys_error(uv.errno[err]) ++ utils.warn(string.format("pipe_connect(%s) failed with error: %s", pipe_path, err)) + else + vim.schedule(function() + fn(pipe, unpack(args)) +diff --git a/lua/fzf-lua/test/screenshot.lua b/lua/fzf-lua/test/screenshot.lua +index 5d31c847..3e3eedb4 100644 +--- a/lua/fzf-lua/test/screenshot.lua ++++ b/lua/fzf-lua/test/screenshot.lua +@@ -207,7 +207,7 @@ M.reference_screenshot = function(screenshot, path, opts) + local subject = "screenshot equality to reference at " .. vim.inspect(path) + local context = string.format("%s\nReference:\n%s\n\nObserved:\n%s", cause, tostring(reference), + tostring(screenshot)) +- H.error_expect(subject, context) ++ H.error_with_emphasis(subject, context) + end + + -- modified version (no attr, trim trailing whitespace) +@@ -233,7 +233,7 @@ M.compare = function(reference, screenshot, opts) + local context = string.format("%s\nReference:\n%s\n\nObserved:\n%s", cause, + ruler .. tostring(reference), + ruler .. tostring(screenshot)) +- H.error_expect(subject, context) ++ H.error_with_emphasis(subject, context) + end + + return M diff --git a/tasks/ibhagwan__fzf-lua-2524/tests/test.sh b/tasks/ibhagwan__fzf-lua-2524/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a1b908663186035f0b38bffca6667ec517f8e74 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c3714dfc25d056fc6afe17d331b3802e3469694c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2524/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2524/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2524/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2528/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2528/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..594440ecf23de94c19c46ee3e731dfe4a9beead3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 696f8c071723f845b904af2f99a798650210355e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 696f8c071723f845b904af2f99a798650210355e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 696f8c071723f845b904af2f99a798650210355e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2528/instruction.md b/tasks/ibhagwan__fzf-lua-2528/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c7c3432c22592d218fcb5a4ec6e3f6a831105aa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(tsinjector): manually parse in on_win to fix the highlight on nightly + +## Description + +Fix on nightly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `696f8c071723`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2528/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2528/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2115f8b866f7c5bde5d9ea44d9e6bf87f870ca35 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9886bbd1..7565e9cb 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -30,7 +30,7 @@ function TSInjector.setup() + and pcall(api.nvim_set_decoration_provider, TSInjector._ns, { on_range = function() end }) + or TSInjector._has_on_range + +- local function wrap_ts_hl_callback(name) ++ local function wrap_ts_hl_callback(name, cb) + return function(_, win, buf, ...) + -- print(name, buf, win, TSInjector.cache[buf]) + if not TSInjector.cache[buf] then +@@ -40,6 +40,7 @@ function TSInjector.setup() + if hl.enabled then + vim.treesitter.highlighter.active[buf] = hl.highlighter + if vim.treesitter.highlighter[name] then ++ if cb then cb(hl.highlighter, buf, ...) end + vim.treesitter.highlighter[name](_, win, buf, ...) + end + end +@@ -48,13 +49,27 @@ function TSInjector.setup() + end + end + ++ local on_range = wrap_ts_hl_callback("_on_range") ++ local on_line = TSInjector._has_on_range and function(_, win, buf, row) ++ return on_range(_, win, buf, row, 0, row + 1, 0) ++ end or wrap_ts_hl_callback("_on_line") ++ ++ local on_win_pre = utils.__HAS_NVIM_012 and function(h, buf, topline, botline) ++ if h.parsing then return end ++ h.parsing = nil == h.tree:parse({ topline, botline + 1 }, function(_, trees) ++ if trees and h.parsing then ++ h.parsing = false ++ api.nvim__redraw({ buf = buf, valid = false, flush = false }) ++ end ++ end) ++ end or nil ++ + api.nvim_set_decoration_provider(TSInjector._ns, { + -- NOTE: unsure why we need "on_start" + -- causes issue with mixed lang regions (#2526) + -- on_start = wrap_ts_hl_callback("_on_start"), +- on_win = wrap_ts_hl_callback("_on_win"), +- on_line = wrap_ts_hl_callback("_on_line"), +- on_range = TSInjector._has_on_range and wrap_ts_hl_callback("_on_range") or nil, ++ on_win = wrap_ts_hl_callback("_on_win", on_win_pre), ++ on_line = on_line, + }) + + return true diff --git a/tasks/ibhagwan__fzf-lua-2528/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2528/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2528/task.toml b/tasks/ibhagwan__fzf-lua-2528/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..83cdb625243cba56a9cb11b96c2eea0505c99d74 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2528" +description = "fix(tsinjector): manually parse in on_win to fix the highlight on nightly" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "696f8c071723f845b904af2f99a798650210355e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2528" +source_access = "auto" +built_at = "2026-11-16T16:09:56.074538+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bf0f23068d4ffeb2b79c51144f4bb22575554c25565ebe1d58f51f78005849bb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-21T07:29:38Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "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:01.017413+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dfe86c0e538a049f922d218fb90b02f7db36c8eba57d675c0140124feb5ee922" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2528/tests/capture.py b/tasks/ibhagwan__fzf-lua-2528/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2528/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2528/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c7c3432c22592d218fcb5a4ec6e3f6a831105aa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(tsinjector): manually parse in on_win to fix the highlight on nightly + +## Description + +Fix on nightly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `696f8c071723`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2528/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2528/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2115f8b866f7c5bde5d9ea44d9e6bf87f870ca35 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9886bbd1..7565e9cb 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -30,7 +30,7 @@ function TSInjector.setup() + and pcall(api.nvim_set_decoration_provider, TSInjector._ns, { on_range = function() end }) + or TSInjector._has_on_range + +- local function wrap_ts_hl_callback(name) ++ local function wrap_ts_hl_callback(name, cb) + return function(_, win, buf, ...) + -- print(name, buf, win, TSInjector.cache[buf]) + if not TSInjector.cache[buf] then +@@ -40,6 +40,7 @@ function TSInjector.setup() + if hl.enabled then + vim.treesitter.highlighter.active[buf] = hl.highlighter + if vim.treesitter.highlighter[name] then ++ if cb then cb(hl.highlighter, buf, ...) end + vim.treesitter.highlighter[name](_, win, buf, ...) + end + end +@@ -48,13 +49,27 @@ function TSInjector.setup() + end + end + ++ local on_range = wrap_ts_hl_callback("_on_range") ++ local on_line = TSInjector._has_on_range and function(_, win, buf, row) ++ return on_range(_, win, buf, row, 0, row + 1, 0) ++ end or wrap_ts_hl_callback("_on_line") ++ ++ local on_win_pre = utils.__HAS_NVIM_012 and function(h, buf, topline, botline) ++ if h.parsing then return end ++ h.parsing = nil == h.tree:parse({ topline, botline + 1 }, function(_, trees) ++ if trees and h.parsing then ++ h.parsing = false ++ api.nvim__redraw({ buf = buf, valid = false, flush = false }) ++ end ++ end) ++ end or nil ++ + api.nvim_set_decoration_provider(TSInjector._ns, { + -- NOTE: unsure why we need "on_start" + -- causes issue with mixed lang regions (#2526) + -- on_start = wrap_ts_hl_callback("_on_start"), +- on_win = wrap_ts_hl_callback("_on_win"), +- on_line = wrap_ts_hl_callback("_on_line"), +- on_range = TSInjector._has_on_range and wrap_ts_hl_callback("_on_range") or nil, ++ on_win = wrap_ts_hl_callback("_on_win", on_win_pre), ++ on_line = on_line, + }) + + return true diff --git a/tasks/ibhagwan__fzf-lua-2528/tests/test.sh b/tasks/ibhagwan__fzf-lua-2528/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bad5972d12c0a1a2baad4f230a311ff7fb3f211 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 696f8c071723f845b904af2f99a798650210355e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2528/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2528/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2528/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2529/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2529/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..594440ecf23de94c19c46ee3e731dfe4a9beead3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 696f8c071723f845b904af2f99a798650210355e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 696f8c071723f845b904af2f99a798650210355e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 696f8c071723f845b904af2f99a798650210355e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2529/instruction.md b/tasks/ibhagwan__fzf-lua-2529/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f73331e4261cfc633cc9de298e99195909edad3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: don't set cursorline in terminal buffer + +## Description + +I shouldn't ignore previous comment (: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `696f8c071723`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2529/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2529/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5d8822672efa675884ae9a76d7e3a990a6d93d4d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9886bbd1..31861b12 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1179,7 +1179,9 @@ function FzfWin:set_style_minimal(winid, global) + self:set_winopts(winid, { + number = false, + relativenumber = false, +- cursorline = false, ++ -- BUG(upstream): causes issues with winopts.split=enew ++ -- https://github.com/neovim/neovim/issues/37484 ++ -- cursorline = false, + cursorcolumn = false, + spell = false, + list = false, diff --git a/tasks/ibhagwan__fzf-lua-2529/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2529/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2529/task.toml b/tasks/ibhagwan__fzf-lua-2529/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a844769d0d218e708c0805ae6832c986a6d2c39f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2529" +description = "fix: don't set cursorline in terminal buffer" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "696f8c071723f845b904af2f99a798650210355e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2529" +source_access = "auto" +built_at = "2026-11-16T16:09:56.075905+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2767c0b8b920d7bf56a05eae3a9c9d9cd188edee9d06892af1e4b84b970047e1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-21T07:29:02Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.017901+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dfe86c0e538a049f922d218fb90b02f7db36c8eba57d675c0140124feb5ee922" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2529/tests/capture.py b/tasks/ibhagwan__fzf-lua-2529/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2529/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2529/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f73331e4261cfc633cc9de298e99195909edad3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: don't set cursorline in terminal buffer + +## Description + +I shouldn't ignore previous comment (: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `696f8c071723`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2529/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2529/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5d8822672efa675884ae9a76d7e3a990a6d93d4d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9886bbd1..31861b12 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1179,7 +1179,9 @@ function FzfWin:set_style_minimal(winid, global) + self:set_winopts(winid, { + number = false, + relativenumber = false, +- cursorline = false, ++ -- BUG(upstream): causes issues with winopts.split=enew ++ -- https://github.com/neovim/neovim/issues/37484 ++ -- cursorline = false, + cursorcolumn = false, + spell = false, + list = false, diff --git a/tasks/ibhagwan__fzf-lua-2529/tests/test.sh b/tasks/ibhagwan__fzf-lua-2529/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bad5972d12c0a1a2baad4f230a311ff7fb3f211 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 696f8c071723f845b904af2f99a798650210355e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2529/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2529/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2529/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2530/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2530/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..141d898fceea6c9a901bb55fa1ffd58ec13c4853 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3f04831c9f4bc48618c7fa0dd38d87ad4340bd4d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3f04831c9f4bc48618c7fa0dd38d87ad4340bd4d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3f04831c9f4bc48618c7fa0dd38d87ad4340bd4d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2530/instruction.md b/tasks/ibhagwan__fzf-lua-2530/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41b90ec7948cffc2c33707f77a0dc17f0f35d8fa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** feat(cli): fork when not connected to tty + +## Description + +This makes it so ctrl-q works from within zsh ZLE widgets, for example I have this to define my widgets: +```zsh + FzfLua() { ${NVIM:-nvim} -l "$FZF_LUA_CLI" $@ 0 then return end -- parent process, do nothing ++ -- pid == 0, child process, build the shell command ++ -- tiny delay to let parent (fzf-lua) exit ++ -- then exec nvim conneced to /dev/tty ++ local shell_cmd = string.format( ++ "sleep 0.05; %s %s /dev/tty 2>/dev/tty", cmd, ++ table.concat(vim.tbl_map(function(x) return FzfLua.libuv.shellescape(x) end, { ... }), " ") ++ ) ++ os.execute(shell_cmd) ++ os.exit(0) ++end ++ + local function posix_exec(cmd, ...) + local _is_win = fn.has("win32") == 1 or fn.has("win64") == 1 + if type(cmd) ~= "string" or _is_win or not ffi then return end ++ if not isatty(io.stdout) then return fork(cmd, ...) end + local args = { ... } + -- NOTE: must add NULL to mark end of the vararg + table.insert(args, string.byte("\0")) +@@ -142,13 +168,20 @@ return { + entries[1].line and ("+" .. entries[1].line) or nil, + entries[1].col and ("+norm! %s|"):format(entries[1].col) or nil) + elseif ffi and #entries > 1 then +- local file = fn.tempname() +- fn.writefile(vim.tbl_map(function(e) -- Format: {filename}:{lnum}:{col}: {text} ++ local qf_items = {} ++ for _, e in ipairs(entries) do + local text = e.stripped:match(":%d+:%d?%d?%d?%d?:?(.*)$") or "" +- return ("%s:%d:%d: %s"):format(e.path, e.line or 1, e.col or 1, text) +- end, entries), file) +- posix_exec(fn.exepath("nvim"), "--cmd", +- ("set nohidden | cfile %s | set hidden&"):format(file)) ++ table.insert(qf_items, { ++ filename = e.path, ++ lnum = math.max(1, e.line or 1), ++ col = math.max(1, e.col or 1), ++ text = text, ++ }) ++ end ++ local qf_str = vim.inspect(qf_items):gsub("\n%s*", " ") ++ posix_exec(fn.exepath("nvim"), "-c", string.format( ++ "lua vim.o.hidden=false; vim.fn.setqflist(%s); vim.cmd('cfirst | set hidden&')", ++ qf_str)) + end + quit() + end, diff --git a/tasks/ibhagwan__fzf-lua-2530/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2530/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2530/task.toml b/tasks/ibhagwan__fzf-lua-2530/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ac86d4f3c9d274c67bcabfabf1835d6635f8ff7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2530" +description = "feat(cli): fork when not connected to tty" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "3f04831c9f4bc48618c7fa0dd38d87ad4340bd4d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2530" +source_access = "auto" +built_at = "2026-11-16T16:09:56.071788+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e8433b7df2f4a9d1ff00ce92c5cc8f45417a61aa1bd15e80e843dc9e7578b7bd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-23T02:39:33Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/profiles/cli.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 45 +difficulty = "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:01.018402+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9d1633168b02bc4802a7d059a0912f5e25c1912d3f2fc807e35c10ad6755f2d6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2530/tests/capture.py b/tasks/ibhagwan__fzf-lua-2530/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2530/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2530/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41b90ec7948cffc2c33707f77a0dc17f0f35d8fa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/tests/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** feat(cli): fork when not connected to tty + +## Description + +This makes it so ctrl-q works from within zsh ZLE widgets, for example I have this to define my widgets: +```zsh + FzfLua() { ${NVIM:-nvim} -l "$FZF_LUA_CLI" $@ 0 then return end -- parent process, do nothing ++ -- pid == 0, child process, build the shell command ++ -- tiny delay to let parent (fzf-lua) exit ++ -- then exec nvim conneced to /dev/tty ++ local shell_cmd = string.format( ++ "sleep 0.05; %s %s /dev/tty 2>/dev/tty", cmd, ++ table.concat(vim.tbl_map(function(x) return FzfLua.libuv.shellescape(x) end, { ... }), " ") ++ ) ++ os.execute(shell_cmd) ++ os.exit(0) ++end ++ + local function posix_exec(cmd, ...) + local _is_win = fn.has("win32") == 1 or fn.has("win64") == 1 + if type(cmd) ~= "string" or _is_win or not ffi then return end ++ if not isatty(io.stdout) then return fork(cmd, ...) end + local args = { ... } + -- NOTE: must add NULL to mark end of the vararg + table.insert(args, string.byte("\0")) +@@ -142,13 +168,20 @@ return { + entries[1].line and ("+" .. entries[1].line) or nil, + entries[1].col and ("+norm! %s|"):format(entries[1].col) or nil) + elseif ffi and #entries > 1 then +- local file = fn.tempname() +- fn.writefile(vim.tbl_map(function(e) -- Format: {filename}:{lnum}:{col}: {text} ++ local qf_items = {} ++ for _, e in ipairs(entries) do + local text = e.stripped:match(":%d+:%d?%d?%d?%d?:?(.*)$") or "" +- return ("%s:%d:%d: %s"):format(e.path, e.line or 1, e.col or 1, text) +- end, entries), file) +- posix_exec(fn.exepath("nvim"), "--cmd", +- ("set nohidden | cfile %s | set hidden&"):format(file)) ++ table.insert(qf_items, { ++ filename = e.path, ++ lnum = math.max(1, e.line or 1), ++ col = math.max(1, e.col or 1), ++ text = text, ++ }) ++ end ++ local qf_str = vim.inspect(qf_items):gsub("\n%s*", " ") ++ posix_exec(fn.exepath("nvim"), "-c", string.format( ++ "lua vim.o.hidden=false; vim.fn.setqflist(%s); vim.cmd('cfirst | set hidden&')", ++ qf_str)) + end + quit() + end, diff --git a/tasks/ibhagwan__fzf-lua-2530/tests/test.sh b/tasks/ibhagwan__fzf-lua-2530/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a54e4837b764050f1db085f2b515045da1bec7ab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3f04831c9f4bc48618c7fa0dd38d87ad4340bd4d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2530/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2530/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2530/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2531/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2531/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ebab165e8e6967505432600c3febdbe87f9e1bf4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 20e2d3099ba99f37f9a7c7d9ed2a9d83c3b20618 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 20e2d3099ba99f37f9a7c7d9ed2a9d83c3b20618 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 20e2d3099ba99f37f9a7c7d9ed2a9d83c3b20618 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2531/instruction.md b/tasks/ibhagwan__fzf-lua-2531/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e0cd55f099c2645278fb6bedcb50f24c477f237 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** feat(skim): enable hide profile for skim >= v1.5.3 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `20e2d3099ba9`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2531/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2531/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..75a100963a4161643e53c5f6b8a6035f7c4543d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/solution/patch.diff @@ -0,0 +1,71 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index b17c0fdc..ea75a93d 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -745,6 +745,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + local bin, version, changelog = (function() + if opts.__SK_VERSION then + return "sk", opts.__SK_VERSION, { ++ ["1.5.3"] = { fzf_opts = { ["--algo"] = "frizbee" } }, + ["0.15.5"] = { fzf_opts = { ["--tmux"] = true } }, + ["0.53"] = { fzf_opts = { ["--inline-info"] = true } }, + -- All fzf flags not existing in skim +@@ -811,6 +812,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + -- All skim flags not existing in fzf + ["all"] = { + fzf_opts = { ++ ["--algo"] = false, + ["--inline-info"] = false, + } + }, +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 00f84cea..a587efc0 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -1039,7 +1039,7 @@ end + ---@return table + M.convert_exec_silent_actions = function(opts) + -- `execute-silent` actions are bugged with skim (can't use quotes) +- if utils.has(opts, "sk") then ++ if utils.has(opts, "sk") and not utils.has(opts, "sk", { 1, 5, 3 }) then + return opts + end + for k, v in pairs(opts.actions) do +@@ -1151,7 +1151,10 @@ M.fzf_query_placeholder = "" + M.fzf_field_index = function(opts) + -- fzf already adds single quotes around the placeholder when expanding. + -- for skim we surround it with double quotes or single quote searches fail +- return opts and opts.field_index or opts._is_skim and [["{}"]] or "{q}" ++ -- skim >= v1.5.3 already escapes the field index ++ return opts and opts.field_index ++ or utils.has(opts, "sk") and not utils.has(opts, "sk", { 1, 5, 3 }) and [["{}"]] ++ or "{q}" + end + + ---@param cmd string +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d45ceb4c..b24f66ed 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -265,6 +265,8 @@ M.defaults = { + ["--layout"] = "reverse", + ["--border"] = "none", + ["--highlight-line"] = true, ++ -- typo-resistant algo with skim >= v1.5.3 ++ ["--algo"] = "frizbee", + }, + ---Options passed to fzf-tmux wrapper. + fzf_tmux_opts = { ["-p"] = "80%,80%", ["--margin"] = "0,0" }, +diff --git a/lua/fzf-lua/profiles/hide.lua b/lua/fzf-lua/profiles/hide.lua +index ef4a33a9..3b90c13f 100644 +--- a/lua/fzf-lua/profiles/hide.lua ++++ b/lua/fzf-lua/profiles/hide.lua +@@ -25,7 +25,7 @@ return { + opts.actions = opts.actions or {} + assert(opts.keymap) + assert(opts.keymap.builtin) +- if fzf.utils.has(opts, "sk") then ++ if fzf.utils.has(opts, "sk") and not fzf.utils.has(opts, "sk", { 1, 5, 3 }) then + -- `execute-silent` actions are bugged with skim + -- Set esc to hide since we aren't using the custom callback + opts.actions["esc"] = false diff --git a/tasks/ibhagwan__fzf-lua-2531/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2531/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2531/task.toml b/tasks/ibhagwan__fzf-lua-2531/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..069acdd376407dd3a27e04d2e34c0a8d97dd4be8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2531" +description = "feat(skim): enable hide profile for skim >= v1.5.3" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "20e2d3099ba99f37f9a7c7d9ed2a9d83c3b20618" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2531" +source_access = "auto" +built_at = "2026-11-16T16:09:56.073297+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5205e2e752e10d955c6b4cb397c2293c18b5b93d2ebd1366f2841cdac0942f8b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-23T00:56:03Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/config.lua", + "lua/fzf-lua/core.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/profiles/hide.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[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:01.018887+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b08397afe032fba99a3ab56e9ba259243a89d78ce02d206b72399f54b92857d7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2531/tests/capture.py b/tasks/ibhagwan__fzf-lua-2531/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2531/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2531/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e0cd55f099c2645278fb6bedcb50f24c477f237 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** feat(skim): enable hide profile for skim >= v1.5.3 + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `20e2d3099ba9`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2531/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2531/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..75a100963a4161643e53c5f6b8a6035f7c4543d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/tests/oracle.patch @@ -0,0 +1,71 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index b17c0fdc..ea75a93d 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -745,6 +745,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + local bin, version, changelog = (function() + if opts.__SK_VERSION then + return "sk", opts.__SK_VERSION, { ++ ["1.5.3"] = { fzf_opts = { ["--algo"] = "frizbee" } }, + ["0.15.5"] = { fzf_opts = { ["--tmux"] = true } }, + ["0.53"] = { fzf_opts = { ["--inline-info"] = true } }, + -- All fzf flags not existing in skim +@@ -811,6 +812,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + -- All skim flags not existing in fzf + ["all"] = { + fzf_opts = { ++ ["--algo"] = false, + ["--inline-info"] = false, + } + }, +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 00f84cea..a587efc0 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -1039,7 +1039,7 @@ end + ---@return table + M.convert_exec_silent_actions = function(opts) + -- `execute-silent` actions are bugged with skim (can't use quotes) +- if utils.has(opts, "sk") then ++ if utils.has(opts, "sk") and not utils.has(opts, "sk", { 1, 5, 3 }) then + return opts + end + for k, v in pairs(opts.actions) do +@@ -1151,7 +1151,10 @@ M.fzf_query_placeholder = "" + M.fzf_field_index = function(opts) + -- fzf already adds single quotes around the placeholder when expanding. + -- for skim we surround it with double quotes or single quote searches fail +- return opts and opts.field_index or opts._is_skim and [["{}"]] or "{q}" ++ -- skim >= v1.5.3 already escapes the field index ++ return opts and opts.field_index ++ or utils.has(opts, "sk") and not utils.has(opts, "sk", { 1, 5, 3 }) and [["{}"]] ++ or "{q}" + end + + ---@param cmd string +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d45ceb4c..b24f66ed 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -265,6 +265,8 @@ M.defaults = { + ["--layout"] = "reverse", + ["--border"] = "none", + ["--highlight-line"] = true, ++ -- typo-resistant algo with skim >= v1.5.3 ++ ["--algo"] = "frizbee", + }, + ---Options passed to fzf-tmux wrapper. + fzf_tmux_opts = { ["-p"] = "80%,80%", ["--margin"] = "0,0" }, +diff --git a/lua/fzf-lua/profiles/hide.lua b/lua/fzf-lua/profiles/hide.lua +index ef4a33a9..3b90c13f 100644 +--- a/lua/fzf-lua/profiles/hide.lua ++++ b/lua/fzf-lua/profiles/hide.lua +@@ -25,7 +25,7 @@ return { + opts.actions = opts.actions or {} + assert(opts.keymap) + assert(opts.keymap.builtin) +- if fzf.utils.has(opts, "sk") then ++ if fzf.utils.has(opts, "sk") and not fzf.utils.has(opts, "sk", { 1, 5, 3 }) then + -- `execute-silent` actions are bugged with skim + -- Set esc to hide since we aren't using the custom callback + opts.actions["esc"] = false diff --git a/tasks/ibhagwan__fzf-lua-2531/tests/test.sh b/tasks/ibhagwan__fzf-lua-2531/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0e507c823de45ae1ff7720736b9518a8bc8d6e9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 20e2d3099ba99f37f9a7c7d9ed2a9d83c3b20618 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2531/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2531/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2531/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2533/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2533/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..03f0928fa3543e6587b5f842e3536333cb2b4f1a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b4b1f05957a77f7662de834328827890c1a8c02b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b4b1f05957a77f7662de834328827890c1a8c02b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b4b1f05957a77f7662de834328827890c1a8c02b \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2533/instruction.md b/tasks/ibhagwan__fzf-lua-2533/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74eacf993afce36bd92e3e665d5270f52333311d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** preview items + +## Description + +- **feat(previewer): parse_entry can give async preview result** +- **feat(ui_select): opts.preview_items** + +`opts.preview_items`: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b4b1f05957a7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2533/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2533/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f38c5f7dbf26ae8a34d5f1784faa13dc17526d26 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/solution/patch.diff @@ -0,0 +1,294 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 99480760..622c2995 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -466,21 +466,22 @@ function Previewer.base:display_entry(entry_str) + self.preview_bufnr = self:clear_preview_buf(true) + end + ++ ---@async + local populate_preview_buf = function(entry_str_) + if not self.win or not self.win:validate_preview() then return end + + -- specialized previewer populate function + ---@cast self fzf-lua.previewer.BufferOrFile base class def don't make sense here +- self:populate_preview_buf(entry_str_) ++ if self:populate_preview_buf(entry_str_) == false then return end + + -- reset the preview window highlights + self.win:reset_win_highlights(self.win.preview_winid) + end + + -- debounce preview entries +- self:debounce("preview", self.delay, function() ++ self:debounce("preview", self.delay, coroutine.wrap(function() + populate_preview_buf(entry_str) +- end) ++ end)) + end + + function Previewer.base:cmdline(_) +@@ -669,9 +670,11 @@ function Previewer.buffer_or_file:entry_to_file(entry_str) + return path.entry_to_file(entry_str, self.opts) + end + ++---async result can be return by "_cb(res)" + ---@param entry_str string ++---@param _cb? function + ---@return fzf-lua.buffer_or_file.Entry +-function Previewer.buffer_or_file:parse_entry(entry_str) ++function Previewer.buffer_or_file:parse_entry(entry_str, _cb) + ---@type fzf-lua.buffer_or_file.Entry + local entry = self:entry_to_file(entry_str) + local buf = entry.bufnr +@@ -688,9 +691,11 @@ function Previewer.buffer_or_file:parse_entry(entry_str) + end + if entry.path then + if entry.path:find("^fugitive://") and buf and api.nvim_buf_is_valid(buf) then +- entry.do_not_cache = true +- api.nvim_buf_call(buf, +- function() vim.cmd(("do fugitive BufReadCmd %s"):format(entry.path)) end) ++ if fn.exists("#fugitive#BufReadCmd") == 1 then ++ api.nvim_buf_call(buf, function() ++ api.nvim_exec_autocmds("BufReadCmd", { group = "fugitive", pattern = entry.path }) ++ end) ++ end + return entry + end + entry.tick = vim.tbl_get(uv.fs_stat(entry.path) or {}, "mtime", "nsec") +@@ -852,6 +857,7 @@ end + ---@param entry fzf-lua.buffer_or_file.Entry + ---@return string? + function Previewer.buffer_or_file:key_from_entry(entry) ++ if entry.do_not_cache then return nil end + return (entry.bufnr and string.format("bufnr:%d", entry.bufnr) or entry.uri or entry.path) or nil + end + +@@ -859,7 +865,6 @@ end + ---@param entry fzf-lua.buffer_or_file.Entry + ---@return fzf-lua.buffer_or_file.Bcache? + function Previewer.buffer_or_file:check_bcache(entry) +- if entry.do_not_cache then return end + local key = self:key_from_entry(entry) + if not key then return end + local cached = self.cached_buffers[key] +@@ -867,10 +872,6 @@ function Previewer.buffer_or_file:check_bcache(entry) + entry.cached = cached + assert(self.cached_bufnrs[cached.bufnr]) + assert(api.nvim_buf_is_valid(cached.bufnr)) +- if not cached.tick then -- in case cache don't have "tick" +- assert(cached.tick == entry.tick) +- return cached +- end + if entry.tick ~= cached.tick then + cached.invalid = true + cached.tick = entry.tick +@@ -878,12 +879,48 @@ function Previewer.buffer_or_file:check_bcache(entry) + return cached + end + ++---@alias fzf-lua.line (string|[string,string])[] ++---@param content (string|fzf-lua.line)[] ++---@return string[], table ++local parse_rich = function(content) ++ local lines, extmarks = {}, {} ++ for i, line in ipairs(content) do ++ -- If the line is a string, just add it directly. ++ -- Otherwise, it's a table of parts (rich text line) ++ if type(line) == "string" then ++ lines[#lines + 1] = line ++ else ++ local parts = {} ++ local col = 0 ++ for _, part in ipairs(line) do ++ local norm_part = type(part) == "string" and { part } or part ++ local text, hl = norm_part[1] or "", norm_part[2] ++ parts[#parts + 1] = text ++ local end_col = col + #text ++ if hl then ++ extmarks[#extmarks + 1] = { row = i - 1, col = col, end_col = end_col, hl_group = hl } ++ end ++ col = end_col ++ end ++ lines[#lines + 1] = table.concat(parts, "") ++ end ++ end ++ return lines, extmarks ++end ++ ++---@async + ---@param entry_str string ++---@return false? no preview + function Previewer.buffer_or_file:populate_preview_buf(entry_str) + if not self.win or not self.win:validate_preview() then return end + -- stop ueberzug shell job + self:stop_ueberzug() +- local entry = self:parse_entry(entry_str) ++ local co = coroutine.running() ++ -- schedule can avoid "cannot resume running coroutine" ++ local entry = self:parse_entry(entry_str, ++ vim.schedule_wrap(function(res) assert(coroutine.resume(co, res)) end)) ++ entry = entry or coroutine.yield() ++ if not self.win:validate_preview() then return false end + if utils.tbl_isempty(entry) then return end + local cached = self:check_bcache(entry) + if cached and not cached.invalid and not self:should_load_buffer(entry) then +@@ -965,9 +1002,10 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + return + end + do +- local lines = nil ++ ---@type (fzf-lua.line|string)[] ++ local lines + if entry.debug then +- lines = { entry.debug } ++ lines = { { { entry.debug, "Error" } } } + elseif entry.content then + lines = entry.content + else +@@ -986,7 +1024,17 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + end + end + if lines then +- pcall(api.nvim_buf_set_lines, tmpbuf, 0, -1, false, lines) ++ local textlines, extmarks = parse_rich(lines) ++ extmarks = entry.extmarks or extmarks ++ pcall(api.nvim_buf_set_lines, tmpbuf, 0, -1, false, textlines) ++ if extmarks and #extmarks > 0 then ++ local setmark = vim.F.nil_wrap(api.nvim_buf_set_extmark) ++ local ns = api.nvim_create_namespace("fzf-lua.preview.hl") ++ for _, extmark in ipairs(extmarks) do ++ setmark(tmpbuf, ns, extmark.row, extmark.col, ++ { end_col = extmark.end_col, hl_group = extmark.hl_group }) ++ end ++ end + -- swap preview buffer with new one + self:set_preview_buf(tmpbuf) + self:preview_buf_post(entry) +@@ -1221,9 +1269,12 @@ function Previewer.buffer_or_file:do_syntax(entry) + end + + -- filetype detect +- local did_filetype_detect +- local ft = entry.filetype or +- vim.filetype.match({ buf = bufnr, filename = filepath, contents = entry.content }) ++ local did_filetype_detect = entry.filetype and true or false ++ local ft = entry.filetype or vim.filetype.match({ ++ buf = bufnr, ++ filename = filepath, ++ contents = entry.content and parse_rich(entry.content) or nil ++ }) + if not ft then + ft = filetype_detect(bufnr, filepath) + if not ft then return end +@@ -1250,20 +1301,14 @@ function Previewer.buffer_or_file:do_syntax(entry) + end)() + + while true do +- local ts_success = ts_enabled and ts_attach(bufnr, ft) +- if ts_success then +- self:update_render_markdown() +- break +- end +- if did_filetype_detect then +- vim.bo[bufnr].syntax = ft +- break +- end ++ if ts_enabled and ts_attach(bufnr, ft) then return end ++ if did_filetype_detect then break end + -- sometimes vim.filetype.match get a poor filetype (e.g. ft=text) + -- this should be a fallback we should detect it again from ftdetect/modeline + ft = filetype_detect(bufnr, filepath) or ft + did_filetype_detect = true + end ++ vim.bo[bufnr].syntax = ft + end + + function Previewer.base:maybe_set_cursorline(win, pos) +@@ -1402,6 +1447,7 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + local syntax = function() + if self.syntax then + self:do_syntax(entry) ++ self:update_render_markdown() + self:update_ts_context() + self:attach_snacks_image_inline() + end +@@ -1431,12 +1477,10 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + + -- Should we cache the current preview buffer? + -- we cache only named buffers with valid path/uri +- if not entry.do_not_cache and self.preview_bufnr then +- local key = self:key_from_entry(entry) +- if not key then return end +- local cached = self:cache_buffer(self.preview_bufnr, key, min_winopts) +- cached.tick = entry.tick +- end ++ local key = self:key_from_entry(entry) ++ if not key then return end ++ local cached = self:cache_buffer(self.preview_bufnr, key, min_winopts) ++ cached.tick = entry.tick + end + + ---@class fzf-lua.previewer.HelpTags : fzf-lua.previewer.BufferOrFile,{} +@@ -1660,15 +1704,11 @@ function Previewer.highlights:parse_entry(entry_str) + hl = hl_def.link + until not hl + table.insert(lines, [[]]) +- table.insert(lines, [["THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"]]) ++ table.insert(lines, { { [["THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"]], hlgroup } }) + return { + filetype = "lua", + title = hl, + content = lines, +- line = #lines, +- col = 1, +- end_col = 1 + #lines[#lines], +- hlgroup = hlgroup + } + end + +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 2c182b9d..bb627b66 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -174,7 +174,18 @@ M.ui_select = function(items, ui_opts, on_choice) + -- options over `lsp.code_actions` (#999) + opts_merge_strategy = "force" + end +- if _OPTS_ONCE then ++ ++ if ui_opts.preview_item then ++ opts.previewer = { ++ _ctor = function() ++ local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() ++ ---@diagnostic disable-next-line: unused ++ function previewer:parse_entry(entry_str, cb) return ui_opts.preview_item(entry_str, cb) end ++ ++ return previewer ++ end ++ } ++ elseif _OPTS_ONCE then + -- merge and clear the once opts sent from lsp_code_actions. + -- We also override actions to guarantee a single default + -- action, otherwise selected[1] will be empty due to +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 0420ae8e..98cb280c 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -18,6 +18,7 @@ local FzfLua = require("fzf-lua") + ---@field title? string + ---@field hlgroup? any + ---@field debug? string debug information ++---@field extmarks? table + + ---@class fzf-lua.buffer_or_file.Entry : fzf-lua.path.Entry,{} + ---@field do_not_cache? boolean +@@ -26,7 +27,7 @@ local FzfLua = require("fzf-lua") + ---@field no_syntax? boolean + ---@field cached? fzf-lua.buffer_or_file.Bcache + ---@field filetype? string +----@field content? string[] ++---@field content? (string|fzf-lua.line)[] + ---@field end_line? integer 1-based + ---@field end_col? integer 1-based + diff --git a/tasks/ibhagwan__fzf-lua-2533/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2533/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2533/task.toml b/tasks/ibhagwan__fzf-lua-2533/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..56a0d8761e0e46d31c171cb7e2ff4b64a1c845af --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2533" +description = "preview items" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b4b1f05957a77f7662de834328827890c1a8c02b" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2533" +source_access = "auto" +built_at = "2026-11-16T16:09:55.990958+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ad09d8afc337b4c32dfd825151d82077f2a6b7eae75035f44eb0636ab6ce9ae" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-02T13:40:23Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", + "lua/fzf-lua/providers/ui_select.lua", + "lua/fzf-lua/types.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 134 +difficulty = "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:01.019405+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c9c5f6bf0c94b2e2a66b2b30beb2bbafcee686b17c54e3c4899be8d7e53bebcf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2533/tests/capture.py b/tasks/ibhagwan__fzf-lua-2533/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2533/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2533/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74eacf993afce36bd92e3e665d5270f52333311d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** preview items + +## Description + +- **feat(previewer): parse_entry can give async preview result** +- **feat(ui_select): opts.preview_items** + +`opts.preview_items`: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b4b1f05957a7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2533/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2533/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f38c5f7dbf26ae8a34d5f1784faa13dc17526d26 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/tests/oracle.patch @@ -0,0 +1,294 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 99480760..622c2995 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -466,21 +466,22 @@ function Previewer.base:display_entry(entry_str) + self.preview_bufnr = self:clear_preview_buf(true) + end + ++ ---@async + local populate_preview_buf = function(entry_str_) + if not self.win or not self.win:validate_preview() then return end + + -- specialized previewer populate function + ---@cast self fzf-lua.previewer.BufferOrFile base class def don't make sense here +- self:populate_preview_buf(entry_str_) ++ if self:populate_preview_buf(entry_str_) == false then return end + + -- reset the preview window highlights + self.win:reset_win_highlights(self.win.preview_winid) + end + + -- debounce preview entries +- self:debounce("preview", self.delay, function() ++ self:debounce("preview", self.delay, coroutine.wrap(function() + populate_preview_buf(entry_str) +- end) ++ end)) + end + + function Previewer.base:cmdline(_) +@@ -669,9 +670,11 @@ function Previewer.buffer_or_file:entry_to_file(entry_str) + return path.entry_to_file(entry_str, self.opts) + end + ++---async result can be return by "_cb(res)" + ---@param entry_str string ++---@param _cb? function + ---@return fzf-lua.buffer_or_file.Entry +-function Previewer.buffer_or_file:parse_entry(entry_str) ++function Previewer.buffer_or_file:parse_entry(entry_str, _cb) + ---@type fzf-lua.buffer_or_file.Entry + local entry = self:entry_to_file(entry_str) + local buf = entry.bufnr +@@ -688,9 +691,11 @@ function Previewer.buffer_or_file:parse_entry(entry_str) + end + if entry.path then + if entry.path:find("^fugitive://") and buf and api.nvim_buf_is_valid(buf) then +- entry.do_not_cache = true +- api.nvim_buf_call(buf, +- function() vim.cmd(("do fugitive BufReadCmd %s"):format(entry.path)) end) ++ if fn.exists("#fugitive#BufReadCmd") == 1 then ++ api.nvim_buf_call(buf, function() ++ api.nvim_exec_autocmds("BufReadCmd", { group = "fugitive", pattern = entry.path }) ++ end) ++ end + return entry + end + entry.tick = vim.tbl_get(uv.fs_stat(entry.path) or {}, "mtime", "nsec") +@@ -852,6 +857,7 @@ end + ---@param entry fzf-lua.buffer_or_file.Entry + ---@return string? + function Previewer.buffer_or_file:key_from_entry(entry) ++ if entry.do_not_cache then return nil end + return (entry.bufnr and string.format("bufnr:%d", entry.bufnr) or entry.uri or entry.path) or nil + end + +@@ -859,7 +865,6 @@ end + ---@param entry fzf-lua.buffer_or_file.Entry + ---@return fzf-lua.buffer_or_file.Bcache? + function Previewer.buffer_or_file:check_bcache(entry) +- if entry.do_not_cache then return end + local key = self:key_from_entry(entry) + if not key then return end + local cached = self.cached_buffers[key] +@@ -867,10 +872,6 @@ function Previewer.buffer_or_file:check_bcache(entry) + entry.cached = cached + assert(self.cached_bufnrs[cached.bufnr]) + assert(api.nvim_buf_is_valid(cached.bufnr)) +- if not cached.tick then -- in case cache don't have "tick" +- assert(cached.tick == entry.tick) +- return cached +- end + if entry.tick ~= cached.tick then + cached.invalid = true + cached.tick = entry.tick +@@ -878,12 +879,48 @@ function Previewer.buffer_or_file:check_bcache(entry) + return cached + end + ++---@alias fzf-lua.line (string|[string,string])[] ++---@param content (string|fzf-lua.line)[] ++---@return string[], table ++local parse_rich = function(content) ++ local lines, extmarks = {}, {} ++ for i, line in ipairs(content) do ++ -- If the line is a string, just add it directly. ++ -- Otherwise, it's a table of parts (rich text line) ++ if type(line) == "string" then ++ lines[#lines + 1] = line ++ else ++ local parts = {} ++ local col = 0 ++ for _, part in ipairs(line) do ++ local norm_part = type(part) == "string" and { part } or part ++ local text, hl = norm_part[1] or "", norm_part[2] ++ parts[#parts + 1] = text ++ local end_col = col + #text ++ if hl then ++ extmarks[#extmarks + 1] = { row = i - 1, col = col, end_col = end_col, hl_group = hl } ++ end ++ col = end_col ++ end ++ lines[#lines + 1] = table.concat(parts, "") ++ end ++ end ++ return lines, extmarks ++end ++ ++---@async + ---@param entry_str string ++---@return false? no preview + function Previewer.buffer_or_file:populate_preview_buf(entry_str) + if not self.win or not self.win:validate_preview() then return end + -- stop ueberzug shell job + self:stop_ueberzug() +- local entry = self:parse_entry(entry_str) ++ local co = coroutine.running() ++ -- schedule can avoid "cannot resume running coroutine" ++ local entry = self:parse_entry(entry_str, ++ vim.schedule_wrap(function(res) assert(coroutine.resume(co, res)) end)) ++ entry = entry or coroutine.yield() ++ if not self.win:validate_preview() then return false end + if utils.tbl_isempty(entry) then return end + local cached = self:check_bcache(entry) + if cached and not cached.invalid and not self:should_load_buffer(entry) then +@@ -965,9 +1002,10 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + return + end + do +- local lines = nil ++ ---@type (fzf-lua.line|string)[] ++ local lines + if entry.debug then +- lines = { entry.debug } ++ lines = { { { entry.debug, "Error" } } } + elseif entry.content then + lines = entry.content + else +@@ -986,7 +1024,17 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + end + end + if lines then +- pcall(api.nvim_buf_set_lines, tmpbuf, 0, -1, false, lines) ++ local textlines, extmarks = parse_rich(lines) ++ extmarks = entry.extmarks or extmarks ++ pcall(api.nvim_buf_set_lines, tmpbuf, 0, -1, false, textlines) ++ if extmarks and #extmarks > 0 then ++ local setmark = vim.F.nil_wrap(api.nvim_buf_set_extmark) ++ local ns = api.nvim_create_namespace("fzf-lua.preview.hl") ++ for _, extmark in ipairs(extmarks) do ++ setmark(tmpbuf, ns, extmark.row, extmark.col, ++ { end_col = extmark.end_col, hl_group = extmark.hl_group }) ++ end ++ end + -- swap preview buffer with new one + self:set_preview_buf(tmpbuf) + self:preview_buf_post(entry) +@@ -1221,9 +1269,12 @@ function Previewer.buffer_or_file:do_syntax(entry) + end + + -- filetype detect +- local did_filetype_detect +- local ft = entry.filetype or +- vim.filetype.match({ buf = bufnr, filename = filepath, contents = entry.content }) ++ local did_filetype_detect = entry.filetype and true or false ++ local ft = entry.filetype or vim.filetype.match({ ++ buf = bufnr, ++ filename = filepath, ++ contents = entry.content and parse_rich(entry.content) or nil ++ }) + if not ft then + ft = filetype_detect(bufnr, filepath) + if not ft then return end +@@ -1250,20 +1301,14 @@ function Previewer.buffer_or_file:do_syntax(entry) + end)() + + while true do +- local ts_success = ts_enabled and ts_attach(bufnr, ft) +- if ts_success then +- self:update_render_markdown() +- break +- end +- if did_filetype_detect then +- vim.bo[bufnr].syntax = ft +- break +- end ++ if ts_enabled and ts_attach(bufnr, ft) then return end ++ if did_filetype_detect then break end + -- sometimes vim.filetype.match get a poor filetype (e.g. ft=text) + -- this should be a fallback we should detect it again from ftdetect/modeline + ft = filetype_detect(bufnr, filepath) or ft + did_filetype_detect = true + end ++ vim.bo[bufnr].syntax = ft + end + + function Previewer.base:maybe_set_cursorline(win, pos) +@@ -1402,6 +1447,7 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + local syntax = function() + if self.syntax then + self:do_syntax(entry) ++ self:update_render_markdown() + self:update_ts_context() + self:attach_snacks_image_inline() + end +@@ -1431,12 +1477,10 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + + -- Should we cache the current preview buffer? + -- we cache only named buffers with valid path/uri +- if not entry.do_not_cache and self.preview_bufnr then +- local key = self:key_from_entry(entry) +- if not key then return end +- local cached = self:cache_buffer(self.preview_bufnr, key, min_winopts) +- cached.tick = entry.tick +- end ++ local key = self:key_from_entry(entry) ++ if not key then return end ++ local cached = self:cache_buffer(self.preview_bufnr, key, min_winopts) ++ cached.tick = entry.tick + end + + ---@class fzf-lua.previewer.HelpTags : fzf-lua.previewer.BufferOrFile,{} +@@ -1660,15 +1704,11 @@ function Previewer.highlights:parse_entry(entry_str) + hl = hl_def.link + until not hl + table.insert(lines, [[]]) +- table.insert(lines, [["THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"]]) ++ table.insert(lines, { { [["THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"]], hlgroup } }) + return { + filetype = "lua", + title = hl, + content = lines, +- line = #lines, +- col = 1, +- end_col = 1 + #lines[#lines], +- hlgroup = hlgroup + } + end + +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 2c182b9d..bb627b66 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -174,7 +174,18 @@ M.ui_select = function(items, ui_opts, on_choice) + -- options over `lsp.code_actions` (#999) + opts_merge_strategy = "force" + end +- if _OPTS_ONCE then ++ ++ if ui_opts.preview_item then ++ opts.previewer = { ++ _ctor = function() ++ local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() ++ ---@diagnostic disable-next-line: unused ++ function previewer:parse_entry(entry_str, cb) return ui_opts.preview_item(entry_str, cb) end ++ ++ return previewer ++ end ++ } ++ elseif _OPTS_ONCE then + -- merge and clear the once opts sent from lsp_code_actions. + -- We also override actions to guarantee a single default + -- action, otherwise selected[1] will be empty due to +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 0420ae8e..98cb280c 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -18,6 +18,7 @@ local FzfLua = require("fzf-lua") + ---@field title? string + ---@field hlgroup? any + ---@field debug? string debug information ++---@field extmarks? table + + ---@class fzf-lua.buffer_or_file.Entry : fzf-lua.path.Entry,{} + ---@field do_not_cache? boolean +@@ -26,7 +27,7 @@ local FzfLua = require("fzf-lua") + ---@field no_syntax? boolean + ---@field cached? fzf-lua.buffer_or_file.Bcache + ---@field filetype? string +----@field content? string[] ++---@field content? (string|fzf-lua.line)[] + ---@field end_line? integer 1-based + ---@field end_col? integer 1-based + diff --git a/tasks/ibhagwan__fzf-lua-2533/tests/test.sh b/tasks/ibhagwan__fzf-lua-2533/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3cc047ea24b728667ccfea43787cc9854fa01a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b4b1f05957a77f7662de834328827890c1a8c02b > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2533/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2533/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2533/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2537/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2537/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e24124c00c7e65e8df64e12a113de4ac34ec4829 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 94e2ae01cbc76ba4aa61e2c7b38fe7f25159fc29 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 94e2ae01cbc76ba4aa61e2c7b38fe7f25159fc29 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 94e2ae01cbc76ba4aa61e2c7b38fe7f25159fc29 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2537/instruction.md b/tasks/ibhagwan__fzf-lua-2537/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a38642d5119d0a63c3cbe19b150586ff0abc8523 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** refactor(actions): simplify vimcmd_entry + +## Description + +Split out a few function. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `94e2ae01cbc7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2537/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2537/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44b8e8606097823535ea00b6e4e0563bddcf874b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/solution/patch.diff @@ -0,0 +1,202 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 59110f5a..976a39cc 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -150,29 +150,28 @@ M.resume = function(_, _) + require("fzf-lua").resume() + end + +-local edit_entry = function(entry, fullpath, will_replace_curbuf, opts) ++---requested buffer already loaded in the current window (split?) ++---@param buf? integer ++---@param fullpath string ++---@return boolean ++local buf_edited = function(buf, fullpath) + local curbuf = vim.api.nvim_win_get_buf(0) +- local curbname = vim.api.nvim_buf_get_name(curbuf) +- if entry.bufnr == curbuf or path.equals(curbname, fullpath) then +- -- requested buffer already loaded in the current window (split?) +- return true +- end +- local bufnr = entry.bufnr or (function() +- -- Always open files relative to the current win/tab cwd (#1854) +- -- We normalize the path or Windows will fail with directories starting +- -- with special characters, for example "C:\app\(web)" will be translated +- -- by neovim to "c:\app(web)" (#1082) +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) +- local bufnr0 = vim.fn.bufadd(relpath) +- if bufnr0 == 0 and not opts.silent then +- utils.warn("Unable to add buffer %s", relpath) +- return +- end +- vim.bo[bufnr0].buflisted = true +- return bufnr0 +- end)() +- -- abort if we're unable to load the buffer +- if not tonumber(bufnr) then return end ++ return buf == curbuf or path.equals(fullpath, vim.api.nvim_buf_get_name(curbuf)) ++end ++ ++---@param relpath string ++---@return integer? ++local load_buf = function(relpath) ++ local bufnr = vim.fn.bufadd(relpath) ++ if bufnr == 0 then return end ++ vim.bo[bufnr].buflisted = true ++ return bufnr ++end ++ ++---@param bufnr integer ++---@param will_replace_curbuf boolean ++---@return boolean? success ++local set_buf = function(bufnr, will_replace_curbuf) + -- wipe unnamed empty buffers (e.g. "new") on switch + if will_replace_curbuf + and vim.bo.buftype == "" +@@ -223,17 +222,13 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + if not utils.is_term_buffer(0) then + vim.cmd("normal! m`") + end ++ -- Always open files relative to the current win/tab cwd (#1854) ++ -- We normalize the path or Windows will fail with directories starting ++ -- with special characters, for example "C:\app\(web)" will be translated ++ -- by neovim to "c:\app(web)" (#1082) ++ local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + if bufedit then +- local will_replace_curbuf = (function() +- if #vimcmd > 0 then return false end +- local curbuf = vim.api.nvim_win_get_buf(0) +- local curbname = vim.api.nvim_buf_get_name(curbuf) +- if entry.bufnr == curbuf or path.equals(curbname, fullpath) then +- -- requested buffer already loaded in the current window (split?) +- return false +- end +- return true +- end)() ++ local will_replace_curbuf = #vimcmd == 0 and not buf_edited(entry.bufnr, fullpath) + if will_replace_curbuf then + if utils.wo.winfixbuf then + utils.warn("'winfixbuf' is set for current window, will open in a split.") +@@ -242,18 +237,23 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + and not vim.o.confirm + and not vim.o.autowriteall + and utils.buffer_is_dirty(vim.api.nvim_get_current_buf(), true, true) then ++ if not opts.silent then utils.warn("cannot replace modified buffer") end + return + end + end + if #vimcmd > 0 then vim.cmd(vimcmd) end + -- NOTE: URI entries only execute new buffers (new|vnew|tabnew) + -- and later use `utils.jump_to_location` to load the buffer +- if not entry.uri and not edit_entry(entry, fullpath, will_replace_curbuf, opts) then ++ if not entry.uri and not buf_edited(entry.bufnr, fullpath) then + -- error loading buffer or save dialog cancelled +- return ++ local bufnr = entry.bufnr or load_buf(relpath) ++ if not bufnr then ++ if not opts.silent then utils.warn("Unable to add buffer %s", fullpath) end ++ return ++ end ++ if not set_buf(bufnr, will_replace_curbuf) then return end + end + else +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + vim.cmd(("%s %s"):format(vimcmd, relpath)) + end + -- Reload actions from fzf's (buf/arg del, etc) window end here +@@ -1364,7 +1364,10 @@ local parse_entry = function(e) return e and e:match("%((.-)%)") or nil end + M.serverlist_kill = function(sel) + vim.iter(sel):map(parse_entry):each(function(addr) + local ok, err = utils.rpcexec(addr, "nvim_exec2", "qa!", {}) +- assert(ok or tostring(err):match("Invalid channel"), err) ++ assert(ok ++ or tostring(err):match("Invalid channel") ++ or tostring(err):match("ch %d+ was closed by the peer"), ++ err) + end) + end + +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index f16f3868..daaab393 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -786,42 +786,25 @@ M.serverlist = function(opts) + local socket_paths = vim.fs.find(function(name, _) + return name:match("nvim.*") + end, { path = root, type = "socket", limit = math.huge }) +- +- local found = {} ---@type string[] +- for _, socket in ipairs(socket_paths) do +- -- Don't list servers twice +- if not vim.list_contains(listed, socket) then +- local ok, chan = pcall(vim.fn.sockconnect, "pipe", socket, { rpc = true }) +- if ok and chan then ---@cast chan integer +- -- Check that the server is responding +- if vim.fn.rpcrequest(chan, "nvim_get_chan_info", 0).id then +- table.insert(found, socket) +- end +- vim.fn.chanclose(chan) +- end +- end ++ local found = utils.list_to_map(listed or vim.fn.serverlist()) ++ local filter = function(socket) ++ if found[socket] or socket:match("fzf%-lua") then return false end ++ found[socket] = true ++ local ok, info = utils.rpcexec(socket, "nvim_get_chan_info", 0) ++ return ok and info.id + end +- return found ++ return vim.iter(socket_paths):filter(filter) + end + + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") +- local list = vim.fn.serverlist() ++ + local f = function(cb) +- vim +- .iter(serverlist(list)) +- :filter( +- function(p) +- return not p:match("fzf%-lua") and not vim.tbl_contains(list, p) +- end +- ) +- :map(function(p) +- ---@type boolean, string? +- local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) +- if not ok or not cwd then return end +- cwd = FzfLua.path.normalize(cwd) +- return ("%s (%s)"):format(cwd, p) +- end) +- :each(cb) ++ serverlist():each(function(p) ---@type boolean, string? ++ local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) ++ if not ok or not cwd then return end ++ cwd = FzfLua.path.normalize(cwd) ++ cb(("%s (%s)"):format(cwd, p)) ++ end) + cb(nil) + end + core.fzf_exec(function(cb) +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 9d6039d5..8ff9b662 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1025,7 +1025,7 @@ function M.is_term_buffer(bufnr) + return vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].buftype == "terminal" + end + +----@param bufnr integer ++---@param bufnr? integer + ---@param warn? boolean + ---@param only_if_last_buffer? boolean + ---@return boolean +@@ -1508,7 +1508,8 @@ function M.rpcexec(addr, method, ...) + ---@cast chan integer + local ret = { pcall(vim.rpcrequest, chan, method, ...) } + vim.fn.chanclose(chan) +- return unpack(ret) ++ local tonil = function(v) if v == vim.NIL then return nil else return v end end ++ return unpack(vim.tbl_map(tonil, ret)) + end + + --- Checks if treesitter parser for language is installed diff --git a/tasks/ibhagwan__fzf-lua-2537/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2537/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2537/task.toml b/tasks/ibhagwan__fzf-lua-2537/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecf7faea00ffca73b28f7ef878173eead9cd0755 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2537" +description = "refactor(actions): simplify vimcmd_entry" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "94e2ae01cbc76ba4aa61e2c7b38fe7f25159fc29" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2537" +source_access = "auto" +built_at = "2026-11-16T16:09:56.070102+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5fe97f386646c4460e674a4c2c0687fdc212b3a4b508378aedfa6014adfb1fc7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-29T16:08:57Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/providers/nvim.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 125 +difficulty = "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:01.019876+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:99841d49b65f37ce6a3b676b6ac64dcbb81b0f830c3bd475fd68470c3dfef538" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2537/tests/capture.py b/tasks/ibhagwan__fzf-lua-2537/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2537/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2537/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a38642d5119d0a63c3cbe19b150586ff0abc8523 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** refactor(actions): simplify vimcmd_entry + +## Description + +Split out a few function. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `94e2ae01cbc7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2537/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2537/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44b8e8606097823535ea00b6e4e0563bddcf874b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/tests/oracle.patch @@ -0,0 +1,202 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 59110f5a..976a39cc 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -150,29 +150,28 @@ M.resume = function(_, _) + require("fzf-lua").resume() + end + +-local edit_entry = function(entry, fullpath, will_replace_curbuf, opts) ++---requested buffer already loaded in the current window (split?) ++---@param buf? integer ++---@param fullpath string ++---@return boolean ++local buf_edited = function(buf, fullpath) + local curbuf = vim.api.nvim_win_get_buf(0) +- local curbname = vim.api.nvim_buf_get_name(curbuf) +- if entry.bufnr == curbuf or path.equals(curbname, fullpath) then +- -- requested buffer already loaded in the current window (split?) +- return true +- end +- local bufnr = entry.bufnr or (function() +- -- Always open files relative to the current win/tab cwd (#1854) +- -- We normalize the path or Windows will fail with directories starting +- -- with special characters, for example "C:\app\(web)" will be translated +- -- by neovim to "c:\app(web)" (#1082) +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) +- local bufnr0 = vim.fn.bufadd(relpath) +- if bufnr0 == 0 and not opts.silent then +- utils.warn("Unable to add buffer %s", relpath) +- return +- end +- vim.bo[bufnr0].buflisted = true +- return bufnr0 +- end)() +- -- abort if we're unable to load the buffer +- if not tonumber(bufnr) then return end ++ return buf == curbuf or path.equals(fullpath, vim.api.nvim_buf_get_name(curbuf)) ++end ++ ++---@param relpath string ++---@return integer? ++local load_buf = function(relpath) ++ local bufnr = vim.fn.bufadd(relpath) ++ if bufnr == 0 then return end ++ vim.bo[bufnr].buflisted = true ++ return bufnr ++end ++ ++---@param bufnr integer ++---@param will_replace_curbuf boolean ++---@return boolean? success ++local set_buf = function(bufnr, will_replace_curbuf) + -- wipe unnamed empty buffers (e.g. "new") on switch + if will_replace_curbuf + and vim.bo.buftype == "" +@@ -223,17 +222,13 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + if not utils.is_term_buffer(0) then + vim.cmd("normal! m`") + end ++ -- Always open files relative to the current win/tab cwd (#1854) ++ -- We normalize the path or Windows will fail with directories starting ++ -- with special characters, for example "C:\app\(web)" will be translated ++ -- by neovim to "c:\app(web)" (#1082) ++ local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + if bufedit then +- local will_replace_curbuf = (function() +- if #vimcmd > 0 then return false end +- local curbuf = vim.api.nvim_win_get_buf(0) +- local curbname = vim.api.nvim_buf_get_name(curbuf) +- if entry.bufnr == curbuf or path.equals(curbname, fullpath) then +- -- requested buffer already loaded in the current window (split?) +- return false +- end +- return true +- end)() ++ local will_replace_curbuf = #vimcmd == 0 and not buf_edited(entry.bufnr, fullpath) + if will_replace_curbuf then + if utils.wo.winfixbuf then + utils.warn("'winfixbuf' is set for current window, will open in a split.") +@@ -242,18 +237,23 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + and not vim.o.confirm + and not vim.o.autowriteall + and utils.buffer_is_dirty(vim.api.nvim_get_current_buf(), true, true) then ++ if not opts.silent then utils.warn("cannot replace modified buffer") end + return + end + end + if #vimcmd > 0 then vim.cmd(vimcmd) end + -- NOTE: URI entries only execute new buffers (new|vnew|tabnew) + -- and later use `utils.jump_to_location` to load the buffer +- if not entry.uri and not edit_entry(entry, fullpath, will_replace_curbuf, opts) then ++ if not entry.uri and not buf_edited(entry.bufnr, fullpath) then + -- error loading buffer or save dialog cancelled +- return ++ local bufnr = entry.bufnr or load_buf(relpath) ++ if not bufnr then ++ if not opts.silent then utils.warn("Unable to add buffer %s", fullpath) end ++ return ++ end ++ if not set_buf(bufnr, will_replace_curbuf) then return end + end + else +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + vim.cmd(("%s %s"):format(vimcmd, relpath)) + end + -- Reload actions from fzf's (buf/arg del, etc) window end here +@@ -1364,7 +1364,10 @@ local parse_entry = function(e) return e and e:match("%((.-)%)") or nil end + M.serverlist_kill = function(sel) + vim.iter(sel):map(parse_entry):each(function(addr) + local ok, err = utils.rpcexec(addr, "nvim_exec2", "qa!", {}) +- assert(ok or tostring(err):match("Invalid channel"), err) ++ assert(ok ++ or tostring(err):match("Invalid channel") ++ or tostring(err):match("ch %d+ was closed by the peer"), ++ err) + end) + end + +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index f16f3868..daaab393 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -786,42 +786,25 @@ M.serverlist = function(opts) + local socket_paths = vim.fs.find(function(name, _) + return name:match("nvim.*") + end, { path = root, type = "socket", limit = math.huge }) +- +- local found = {} ---@type string[] +- for _, socket in ipairs(socket_paths) do +- -- Don't list servers twice +- if not vim.list_contains(listed, socket) then +- local ok, chan = pcall(vim.fn.sockconnect, "pipe", socket, { rpc = true }) +- if ok and chan then ---@cast chan integer +- -- Check that the server is responding +- if vim.fn.rpcrequest(chan, "nvim_get_chan_info", 0).id then +- table.insert(found, socket) +- end +- vim.fn.chanclose(chan) +- end +- end ++ local found = utils.list_to_map(listed or vim.fn.serverlist()) ++ local filter = function(socket) ++ if found[socket] or socket:match("fzf%-lua") then return false end ++ found[socket] = true ++ local ok, info = utils.rpcexec(socket, "nvim_get_chan_info", 0) ++ return ok and info.id + end +- return found ++ return vim.iter(socket_paths):filter(filter) + end + + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") +- local list = vim.fn.serverlist() ++ + local f = function(cb) +- vim +- .iter(serverlist(list)) +- :filter( +- function(p) +- return not p:match("fzf%-lua") and not vim.tbl_contains(list, p) +- end +- ) +- :map(function(p) +- ---@type boolean, string? +- local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) +- if not ok or not cwd then return end +- cwd = FzfLua.path.normalize(cwd) +- return ("%s (%s)"):format(cwd, p) +- end) +- :each(cb) ++ serverlist():each(function(p) ---@type boolean, string? ++ local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) ++ if not ok or not cwd then return end ++ cwd = FzfLua.path.normalize(cwd) ++ cb(("%s (%s)"):format(cwd, p)) ++ end) + cb(nil) + end + core.fzf_exec(function(cb) +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 9d6039d5..8ff9b662 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1025,7 +1025,7 @@ function M.is_term_buffer(bufnr) + return vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].buftype == "terminal" + end + +----@param bufnr integer ++---@param bufnr? integer + ---@param warn? boolean + ---@param only_if_last_buffer? boolean + ---@return boolean +@@ -1508,7 +1508,8 @@ function M.rpcexec(addr, method, ...) + ---@cast chan integer + local ret = { pcall(vim.rpcrequest, chan, method, ...) } + vim.fn.chanclose(chan) +- return unpack(ret) ++ local tonil = function(v) if v == vim.NIL then return nil else return v end end ++ return unpack(vim.tbl_map(tonil, ret)) + end + + --- Checks if treesitter parser for language is installed diff --git a/tasks/ibhagwan__fzf-lua-2537/tests/test.sh b/tasks/ibhagwan__fzf-lua-2537/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d543004b53a6a11c0d9a5a976ba4ed6cb25008e2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 94e2ae01cbc76ba4aa61e2c7b38fe7f25159fc29 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2537/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2537/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2537/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2543/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2543/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..744d3b53096f43d2184f378ae980d743b039c104 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 134477b441be0be5fff575642d790c28e5d13401 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 134477b441be0be5fff575642d790c28e5d13401 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 134477b441be0be5fff575642d790c28e5d13401 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2543/instruction.md b/tasks/ibhagwan__fzf-lua-2543/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5596dad64163faf3ac64540fba0f36922914f0fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(serverlist): screenshot when tui is connected + +## Description + +chore: error handling for `make_screenshot` + +fix #2542 + +@phanen, any objection to this? + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `134477b441be`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2543/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2543/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..da424984d22382e4c35d97d837725ef56af9541e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/solution/patch.diff @@ -0,0 +1,77 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 976a39cc..bcc250ed 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1373,7 +1373,7 @@ end + + M.serverlist_spawn = function() + libuv.uv_spawn( +- vim.fn.exepath("nvim"), { args = { "--headless" }, env = { NVIM = "" } }) ++ vim.fn.exepath("nvim"), { args = { "--headless" }, env = { NVIM = "" }, detached = true }) + end + + M.serverlist_connect = function(sel) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index dfe0ad53..9c101677 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1939,8 +1939,8 @@ M.defaults.serverlist = { + keymap = { fzf = { resize = "refresh-preview" } }, + actions = { + ["enter"] = actions.serverlist_connect, +- ["ctrl-o"] = { fn = actions.serverlist_spawn, reload = true }, +- ["ctrl-x"] = { fn = actions.serverlist_kill, reload = true }, ++ ["ctrl-o"] = { fn = actions.serverlist_spawn, reload = true, header = "spawn" }, ++ ["ctrl-x"] = { fn = actions.serverlist_kill, reload = true, header = "kill" }, + }, + } + +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index 0d245be5..e12440d2 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -514,7 +514,8 @@ Previewer.nvim_server = Previewer.cmd_async:extend() + ---@param addr string + ---@param lines integer + ---@param columns integer +----@return integer? pid ++---@return boolean|integer? pid ++---@return string|any, ...any error + local function make_screenshot(screenshot, addr, lines, columns) + local closing = false + local ok, uis = utils.rpcexec(addr, "nvim_list_uis") +@@ -527,16 +528,14 @@ local function make_screenshot(screenshot, addr, lines, columns) + local has_tui = vim.iter(uis):find(function(info) return info.stdout_tty end) + if has_tui then + if vim.env.NVIM == addr then -- parent instance +- utils.rpcexec(addr, "nvim__screenshot", screenshot) +- return ++ return utils.rpcexec(addr, "nvim__screenshot", screenshot) + end +- utils.rpcexec(addr, "nvim_exec_lua", [[ ++ return utils.rpcexec(addr, "nvim_exec_lua", [[ + local lines, columns, screenshot = ... + return vim._with({ go = { lines = lines, columns = columns } }, function() +- api.nvim__screenshot(screenshot) ++ vim.api.nvim__screenshot(screenshot) + end) + ]], { lines, columns, screenshot }) +- return + end + local jobstart = _G.fzf_pty_spawn or vim.fn.jobstart + local nvim_bin = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath +@@ -566,8 +565,12 @@ function Previewer.nvim_server:cmdline(_) + local addr = parse_entry(items[1]) + if not addr then return "true" end + local screenshot = assert(self.opts._screenshot) ---@type string +- local pid = make_screenshot(screenshot, addr, lines, columns) +- local wait = pid ++ local pid, err = make_screenshot(screenshot, addr, lines, columns) ++ if err then ++ return "echo " .. FzfLua.libuv.shellescape(string.format( ++ "make_screenshot failed with error: %s", tostring(err))) ++ end ++ local wait = tonumber(pid) + and vim.fn.executable("waitpid") == 1 + and ("waitpid %s;"):format(pid) + or ("sleep %s;"):format(50 / 1000) diff --git a/tasks/ibhagwan__fzf-lua-2543/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2543/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2543/task.toml b/tasks/ibhagwan__fzf-lua-2543/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..65770b717b4191917f10bb21ec46ae4ba56b95d6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2543" +description = "fix(serverlist): screenshot when tui is connected" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "134477b441be0be5fff575642d790c28e5d13401" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2543" +source_access = "auto" +built_at = "2026-11-16T16:09:56.040946+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1754d2c6f256272106d06c8b6507a87c594d04e4222831b08134d49014929f03" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-01-30T02:53:30Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/previewer/fzf.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "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:01.020345+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:18c3567ea07e6a98f524e58703676d9b136375c209d34cebabdf8cae036b81f0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2543/tests/capture.py b/tasks/ibhagwan__fzf-lua-2543/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2543/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2543/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5596dad64163faf3ac64540fba0f36922914f0fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(serverlist): screenshot when tui is connected + +## Description + +chore: error handling for `make_screenshot` + +fix #2542 + +@phanen, any objection to this? + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `134477b441be`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2543/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2543/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..da424984d22382e4c35d97d837725ef56af9541e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/tests/oracle.patch @@ -0,0 +1,77 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 976a39cc..bcc250ed 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1373,7 +1373,7 @@ end + + M.serverlist_spawn = function() + libuv.uv_spawn( +- vim.fn.exepath("nvim"), { args = { "--headless" }, env = { NVIM = "" } }) ++ vim.fn.exepath("nvim"), { args = { "--headless" }, env = { NVIM = "" }, detached = true }) + end + + M.serverlist_connect = function(sel) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index dfe0ad53..9c101677 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1939,8 +1939,8 @@ M.defaults.serverlist = { + keymap = { fzf = { resize = "refresh-preview" } }, + actions = { + ["enter"] = actions.serverlist_connect, +- ["ctrl-o"] = { fn = actions.serverlist_spawn, reload = true }, +- ["ctrl-x"] = { fn = actions.serverlist_kill, reload = true }, ++ ["ctrl-o"] = { fn = actions.serverlist_spawn, reload = true, header = "spawn" }, ++ ["ctrl-x"] = { fn = actions.serverlist_kill, reload = true, header = "kill" }, + }, + } + +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index 0d245be5..e12440d2 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -514,7 +514,8 @@ Previewer.nvim_server = Previewer.cmd_async:extend() + ---@param addr string + ---@param lines integer + ---@param columns integer +----@return integer? pid ++---@return boolean|integer? pid ++---@return string|any, ...any error + local function make_screenshot(screenshot, addr, lines, columns) + local closing = false + local ok, uis = utils.rpcexec(addr, "nvim_list_uis") +@@ -527,16 +528,14 @@ local function make_screenshot(screenshot, addr, lines, columns) + local has_tui = vim.iter(uis):find(function(info) return info.stdout_tty end) + if has_tui then + if vim.env.NVIM == addr then -- parent instance +- utils.rpcexec(addr, "nvim__screenshot", screenshot) +- return ++ return utils.rpcexec(addr, "nvim__screenshot", screenshot) + end +- utils.rpcexec(addr, "nvim_exec_lua", [[ ++ return utils.rpcexec(addr, "nvim_exec_lua", [[ + local lines, columns, screenshot = ... + return vim._with({ go = { lines = lines, columns = columns } }, function() +- api.nvim__screenshot(screenshot) ++ vim.api.nvim__screenshot(screenshot) + end) + ]], { lines, columns, screenshot }) +- return + end + local jobstart = _G.fzf_pty_spawn or vim.fn.jobstart + local nvim_bin = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath +@@ -566,8 +565,12 @@ function Previewer.nvim_server:cmdline(_) + local addr = parse_entry(items[1]) + if not addr then return "true" end + local screenshot = assert(self.opts._screenshot) ---@type string +- local pid = make_screenshot(screenshot, addr, lines, columns) +- local wait = pid ++ local pid, err = make_screenshot(screenshot, addr, lines, columns) ++ if err then ++ return "echo " .. FzfLua.libuv.shellescape(string.format( ++ "make_screenshot failed with error: %s", tostring(err))) ++ end ++ local wait = tonumber(pid) + and vim.fn.executable("waitpid") == 1 + and ("waitpid %s;"):format(pid) + or ("sleep %s;"):format(50 / 1000) diff --git a/tasks/ibhagwan__fzf-lua-2543/tests/test.sh b/tasks/ibhagwan__fzf-lua-2543/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c623d44f8121cde6441525b5bda9f1d880a7bfa0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 134477b441be0be5fff575642d790c28e5d13401 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2543/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2543/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2543/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2550/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2550/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d2fcbe6d63a130d938d527b53eec33cb9cc78eec --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e5804f4924cf74ad03834c25988998a273ae0d7b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e5804f4924cf74ad03834c25988998a273ae0d7b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e5804f4924cf74ad03834c25988998a273ae0d7b \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2550/instruction.md b/tasks/ibhagwan__fzf-lua-2550/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bdb3342f2c65a3902e9f91a7e1e01f4bbe3f053 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(lsp): change error to warn on lsp error message + +## Description + +see + +Builtin lsp warn on hierarchy request: +https://github.com/neovim/neovim/blob/0501c5fd0959895b18d8166c6c034cdf1832edf3/runtime/lua/vim/lsp/buf.lua#L1275 +Also other "content" request don't throw error message. + +So I think we can change error to warn. + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e5804f4924cf`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2550/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2550/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..27d3d2cdb45a2a270fe6bfe1ed1a856e63276881 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index f1a322ff..3c30884b 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -485,7 +485,8 @@ local function gen_lsp_contents(opts) + local context = { client_id = client_id } + lsp_handler.handler(opts, cb, lsp_handler.method, response.result, context, nil) + elseif response.error then +- utils.error("Error executing '%s': %s", lsp_handler.method, response.error.message) ++ local name = assert(vim.lsp.get_client_by_id(client_id)).name ++ utils.warn("%s[%s]: %s", tostring(name), lsp_handler.method, response.error.message) + end + end + if utils.tbl_isempty(results) then diff --git a/tasks/ibhagwan__fzf-lua-2550/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2550/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2550/task.toml b/tasks/ibhagwan__fzf-lua-2550/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..17a02cd65b976b3386bd41b5751b227a93e886da --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2550" +description = "fix(lsp): change error to warn on lsp error message (#2547)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "e5804f4924cf74ad03834c25988998a273ae0d7b" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2550" +source_access = "auto" +built_at = "2026-11-16T16:09:56.068803+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:678271ec7bc8324e934f81b7043edcbf75854de7341378198f049a0fa0e22fa7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-03T10:29:36Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/lsp.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.020844+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9847868eca079ed13ca231a66ba99208ab981e70495e421b5b32403fff47f8f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2550/tests/capture.py b/tasks/ibhagwan__fzf-lua-2550/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2550/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2550/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bdb3342f2c65a3902e9f91a7e1e01f4bbe3f053 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(lsp): change error to warn on lsp error message + +## Description + +see + +Builtin lsp warn on hierarchy request: +https://github.com/neovim/neovim/blob/0501c5fd0959895b18d8166c6c034cdf1832edf3/runtime/lua/vim/lsp/buf.lua#L1275 +Also other "content" request don't throw error message. + +So I think we can change error to warn. + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e5804f4924cf`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2550/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2550/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..27d3d2cdb45a2a270fe6bfe1ed1a856e63276881 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index f1a322ff..3c30884b 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -485,7 +485,8 @@ local function gen_lsp_contents(opts) + local context = { client_id = client_id } + lsp_handler.handler(opts, cb, lsp_handler.method, response.result, context, nil) + elseif response.error then +- utils.error("Error executing '%s': %s", lsp_handler.method, response.error.message) ++ local name = assert(vim.lsp.get_client_by_id(client_id)).name ++ utils.warn("%s[%s]: %s", tostring(name), lsp_handler.method, response.error.message) + end + end + if utils.tbl_isempty(results) then diff --git a/tasks/ibhagwan__fzf-lua-2550/tests/test.sh b/tasks/ibhagwan__fzf-lua-2550/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..526aa6871dcd3499be1f849ea31fdaae171d9657 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e5804f4924cf74ad03834c25988998a273ae0d7b > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2550/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2550/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2550/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2557/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2557/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d37d226d41caca40934273313d3fdfc07011c17 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ec3fe3d9587005a995a00d55ea424bfc924eaf3e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ec3fe3d9587005a995a00d55ea424bfc924eaf3e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ec3fe3d9587005a995a00d55ea424bfc924eaf3e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2557/instruction.md b/tasks/ibhagwan__fzf-lua-2557/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c65464b2ca804c32796953fc7022fe50696aa8e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(cli): don't set lnum/col when it's invalid + +## Description + +this break `:h restore-cursor` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec3fe3d95870`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2557/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2557/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..827214fe8308b5f8fc1f2bac22ee1fbff3dc9d06 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index a4453c2f..bc0d8c03 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -537,25 +537,23 @@ local function make_screenshot(screenshot, addr, lines, columns) + end) + ]], { lines, columns, screenshot }) + end +- local jobstart = _G.fzf_pty_spawn or vim.fn.jobstart + local nvim_bin = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath +- local chan = jobstart({ nvim_bin, "--server", addr, "--remote-ui" }, { ++ local chan = vim.fn.jobstart({ nvim_bin, "--server", addr, "--remote-ui" }, { + pty = true, + height = lines, + width = columns, + env = { + TERM = "xterm-256color", +- VIMRUNTIME = vim.env.VIMRUNTIME, ++ VIMRUNTIME = os.getenv("VIMRUNTIME"), + }, + on_stdout = function(chan0) + if closing then return end + closing = true + vim.defer_fn(function() utils.rpcexec(addr, "nvim__screenshot", screenshot) end, 10) +- if not _G.fzf_pty_spawn then vim.defer_fn(function() vim.fn.jobstop(chan0) end, 20) end ++ vim.defer_fn(function() vim.fn.jobstop(chan0) end, 20) + end, + }) +- if not _G.fzf_pty_spawn then return vim.fn.jobpid(chan) end +- return chan ++ return vim.fn.jobpid(chan) + end + + function Previewer.nvim_server:cmdline(_) +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 818f56b7..405df4df 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -164,9 +164,11 @@ return { + ["ctrl-q"] = function(s, o) + local entries = parse_entries(s, o) + if ffi and #entries == 1 then ++ local lnum = entries[1].line > 0 and entries[1].line or nil ++ local col = entries[1].col > 0 and entries[1].col or nil + posix_exec(fn.exepath("nvim"), entries[1].path, +- entries[1].line and ("+" .. entries[1].line) or nil, +- entries[1].col and ("+norm! %s|"):format(entries[1].col) or nil) ++ lnum and ("+" .. entries[1].line) or nil, ++ col and ("+norm! %s|"):format(col) or nil) + elseif ffi and #entries > 1 then + local qf_items = {} + for _, e in ipairs(entries) do diff --git a/tasks/ibhagwan__fzf-lua-2557/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2557/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2557/task.toml b/tasks/ibhagwan__fzf-lua-2557/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..44924fdb4695722c5e11fcc75f8da2e5d6e4de24 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2557" +description = "fix(cli): don't set lnum/col when it's invalid" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "ec3fe3d9587005a995a00d55ea424bfc924eaf3e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2557" +source_access = "auto" +built_at = "2026-11-16T16:09:56.067552+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:22de1d330628111e6a2a85611e72844ffd72f5b454d9500e11c769f3f2a7d6e1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-08T01:06:05Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/fzf.lua", + "lua/fzf-lua/profiles/cli.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[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:01.021382+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:31fad1fdde991d7dc5a2ebf0d88dd47a509347f2b52081ebdc06a71f03053993" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2557/tests/capture.py b/tasks/ibhagwan__fzf-lua-2557/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2557/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2557/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c65464b2ca804c32796953fc7022fe50696aa8e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(cli): don't set lnum/col when it's invalid + +## Description + +this break `:h restore-cursor` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec3fe3d95870`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2557/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2557/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..827214fe8308b5f8fc1f2bac22ee1fbff3dc9d06 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index a4453c2f..bc0d8c03 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -537,25 +537,23 @@ local function make_screenshot(screenshot, addr, lines, columns) + end) + ]], { lines, columns, screenshot }) + end +- local jobstart = _G.fzf_pty_spawn or vim.fn.jobstart + local nvim_bin = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath +- local chan = jobstart({ nvim_bin, "--server", addr, "--remote-ui" }, { ++ local chan = vim.fn.jobstart({ nvim_bin, "--server", addr, "--remote-ui" }, { + pty = true, + height = lines, + width = columns, + env = { + TERM = "xterm-256color", +- VIMRUNTIME = vim.env.VIMRUNTIME, ++ VIMRUNTIME = os.getenv("VIMRUNTIME"), + }, + on_stdout = function(chan0) + if closing then return end + closing = true + vim.defer_fn(function() utils.rpcexec(addr, "nvim__screenshot", screenshot) end, 10) +- if not _G.fzf_pty_spawn then vim.defer_fn(function() vim.fn.jobstop(chan0) end, 20) end ++ vim.defer_fn(function() vim.fn.jobstop(chan0) end, 20) + end, + }) +- if not _G.fzf_pty_spawn then return vim.fn.jobpid(chan) end +- return chan ++ return vim.fn.jobpid(chan) + end + + function Previewer.nvim_server:cmdline(_) +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 818f56b7..405df4df 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -164,9 +164,11 @@ return { + ["ctrl-q"] = function(s, o) + local entries = parse_entries(s, o) + if ffi and #entries == 1 then ++ local lnum = entries[1].line > 0 and entries[1].line or nil ++ local col = entries[1].col > 0 and entries[1].col or nil + posix_exec(fn.exepath("nvim"), entries[1].path, +- entries[1].line and ("+" .. entries[1].line) or nil, +- entries[1].col and ("+norm! %s|"):format(entries[1].col) or nil) ++ lnum and ("+" .. entries[1].line) or nil, ++ col and ("+norm! %s|"):format(col) or nil) + elseif ffi and #entries > 1 then + local qf_items = {} + for _, e in ipairs(entries) do diff --git a/tasks/ibhagwan__fzf-lua-2557/tests/test.sh b/tasks/ibhagwan__fzf-lua-2557/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e14792c507be85b2e87b1acfb0fb81be9b3858d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ec3fe3d9587005a995a00d55ea424bfc924eaf3e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2557/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2557/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2557/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2561/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2561/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fd0d22ebd4a4433439564d54cf69368102cc29c3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9de53c3fce885512f982420ee6082d75613ee891 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9de53c3fce885512f982420ee6082d75613ee891 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9de53c3fce885512f982420ee6082d75613ee891 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2561/instruction.md b/tasks/ibhagwan__fzf-lua-2561/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa85bd7cd9e68efa34e99d241995c364e1a524e8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** fix(actions): ensure requested buffer is listed + +## Description + +Since #2552, specifically 6971762, it's possible for `entry.bufnr` to be populated by an unlisted buffer,[^1] which would remain unlisted even as it was set as the current buffer, because any non-nil `bufnr` means `load_buf` is skipped (see line 249). + +This PR moves `vim.bo[bufnr].buflisted = true` from `load_buf` to `set_buf`, such that it applies to any buffer that becomes current through this codepath. + +Not sure if/how to write a test for this. Let me know! + +[^1]: For me, this frequently happens because the language client opens almost the entire workspace in unlisted buffers as context for the language server's static analysis. When I subsequently use fzf-lua to open one of these files, my buffer line and buffer navigation keymaps break because they only work on listed buffers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9de53c3fce88`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2561/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2561/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6e4cf527c844fd61d84d62d83ab309bda5822c5a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index bcc250ed..6139f488 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -164,7 +164,6 @@ end + local load_buf = function(relpath) + local bufnr = vim.fn.bufadd(relpath) + if bufnr == 0 then return end +- vim.bo[bufnr].buflisted = true + return bufnr + end + +@@ -191,6 +190,7 @@ local set_buf = function(bufnr, will_replace_curbuf) + -- user cancelles the save dialog pcall will fail with: + -- Vim:E37: No write since last change (add ! to override) + if not ok then return end ++ vim.bo[bufnr].buflisted = true + return true + end + +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index bfe6c8ba..eba2a661 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -155,5 +155,19 @@ T["actions"]["vimcmd"] = new_set({ + end + }) + ++T["actions"]["buflisted #2561"] = function() ++ child.cmd("edit LICENSE") ++ child.bo.buflisted = false ++ child.cmd("enew") ++ helpers.FzfLua.files(child, { ++ __abort_key = "", ++ __expect_lines = false, ++ __after_open = function() ++ if helpers.IS_WIN() then vim.uv.sleep(250) end ++ end, ++ query = "LICENSE$", ++ }) ++ eq(true, child.bo.buflisted) ++end + + return T diff --git a/tasks/ibhagwan__fzf-lua-2561/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2561/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2561/task.toml b/tasks/ibhagwan__fzf-lua-2561/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..91939d6d0b26401cc10425a0d47d72ec47f77c68 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2561" +description = "fix(actions): ensure requested buffer is listed" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "9de53c3fce885512f982420ee6082d75613ee891" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2561" +source_access = "auto" +built_at = "2026-11-16T16:09:56.066055+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:024d98b9a05a90b8e836550f98217a0cdb871c829182240e8f7369afd1fade17" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-09T12:51:34Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "tests/actions_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[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:01.021897+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1b842c5739a48b8a47f732e0cec55414e31ef88cff30977c28a5cf900d73abc7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2561/tests/capture.py b/tasks/ibhagwan__fzf-lua-2561/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2561/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2561/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa85bd7cd9e68efa34e99d241995c364e1a524e8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** fix(actions): ensure requested buffer is listed + +## Description + +Since #2552, specifically 6971762, it's possible for `entry.bufnr` to be populated by an unlisted buffer,[^1] which would remain unlisted even as it was set as the current buffer, because any non-nil `bufnr` means `load_buf` is skipped (see line 249). + +This PR moves `vim.bo[bufnr].buflisted = true` from `load_buf` to `set_buf`, such that it applies to any buffer that becomes current through this codepath. + +Not sure if/how to write a test for this. Let me know! + +[^1]: For me, this frequently happens because the language client opens almost the entire workspace in unlisted buffers as context for the language server's static analysis. When I subsequently use fzf-lua to open one of these files, my buffer line and buffer navigation keymaps break because they only work on listed buffers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9de53c3fce88`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2561/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2561/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6e4cf527c844fd61d84d62d83ab309bda5822c5a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index bcc250ed..6139f488 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -164,7 +164,6 @@ end + local load_buf = function(relpath) + local bufnr = vim.fn.bufadd(relpath) + if bufnr == 0 then return end +- vim.bo[bufnr].buflisted = true + return bufnr + end + +@@ -191,6 +190,7 @@ local set_buf = function(bufnr, will_replace_curbuf) + -- user cancelles the save dialog pcall will fail with: + -- Vim:E37: No write since last change (add ! to override) + if not ok then return end ++ vim.bo[bufnr].buflisted = true + return true + end + +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index bfe6c8ba..eba2a661 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -155,5 +155,19 @@ T["actions"]["vimcmd"] = new_set({ + end + }) + ++T["actions"]["buflisted #2561"] = function() ++ child.cmd("edit LICENSE") ++ child.bo.buflisted = false ++ child.cmd("enew") ++ helpers.FzfLua.files(child, { ++ __abort_key = "", ++ __expect_lines = false, ++ __after_open = function() ++ if helpers.IS_WIN() then vim.uv.sleep(250) end ++ end, ++ query = "LICENSE$", ++ }) ++ eq(true, child.bo.buflisted) ++end + + return T diff --git a/tasks/ibhagwan__fzf-lua-2561/tests/test.sh b/tasks/ibhagwan__fzf-lua-2561/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..51cbaea6368c8a1073e8e06ab60e796c0c4cd5ad --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9de53c3fce885512f982420ee6082d75613ee891 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2561/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2561/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2561/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2568/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2568/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9e1d4085475ceed374481f003985ffad583bd96d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5921997472574fca3880b62949eb8679dc6f5afc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5921997472574fca3880b62949eb8679dc6f5afc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5921997472574fca3880b62949eb8679dc6f5afc \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2568/instruction.md b/tasks/ibhagwan__fzf-lua-2568/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e1c913f45a784fe1c06eb49968008c79973c32a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): convert border-line to border-fused + +## Description + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `592199747257`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2568/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2568/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..af4e49fb4a64611684911d25f81c9c933d8a0fa1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 0096eb0a..00899878 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -569,6 +569,9 @@ function FzfWin:normalize_border(border, metadata) + ["border-horizontal"] = { "─", "─", "─", "", "─", "─", "─", "" }, + ["border-top"] = { "─", "─", "─", "", "", "", "", "" }, + ["border-bottom"] = { "", "", "", "", "─", "─", "─", "" }, ++ ["border-line"] = function() ++ return require("fzf-lua.profiles.border-fused").winopts.preview.border(self, metadata) ++ end, + } + if type(border) == "string" then + if not valid_borders[border] then +@@ -578,6 +581,7 @@ function FzfWin:normalize_border(border, metadata) + border = "rounded" + else + border = valid_borders[border] ++ border = type(border) == "function" and border() or border + end + elseif type(border) ~= "table" then + if not self._o.silent then diff --git a/tasks/ibhagwan__fzf-lua-2568/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2568/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2568/task.toml b/tasks/ibhagwan__fzf-lua-2568/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cb2b88d6029662bc8404c4a9132b5260ba7363af --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2568" +description = "fix(preview): convert border-line to border-fused (#2567)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "5921997472574fca3880b62949eb8679dc6f5afc" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2568" +source_access = "auto" +built_at = "2026-11-16T16:09:56.064754+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d5f0418787e623e394d89f4cb2e2d19a5c6ae129e9328a3ab5ec3ccce82b5e4c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-17T08:03:34Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.022526+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7a996882d85c4acd811fbe396be76971e84091f57c3da374911aa20e1767e916" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2568/tests/capture.py b/tasks/ibhagwan__fzf-lua-2568/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2568/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2568/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e1c913f45a784fe1c06eb49968008c79973c32a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): convert border-line to border-fused + +## Description + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `592199747257`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2568/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2568/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..af4e49fb4a64611684911d25f81c9c933d8a0fa1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 0096eb0a..00899878 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -569,6 +569,9 @@ function FzfWin:normalize_border(border, metadata) + ["border-horizontal"] = { "─", "─", "─", "", "─", "─", "─", "" }, + ["border-top"] = { "─", "─", "─", "", "", "", "", "" }, + ["border-bottom"] = { "", "", "", "", "─", "─", "─", "" }, ++ ["border-line"] = function() ++ return require("fzf-lua.profiles.border-fused").winopts.preview.border(self, metadata) ++ end, + } + if type(border) == "string" then + if not valid_borders[border] then +@@ -578,6 +581,7 @@ function FzfWin:normalize_border(border, metadata) + border = "rounded" + else + border = valid_borders[border] ++ border = type(border) == "function" and border() or border + end + elseif type(border) ~= "table" then + if not self._o.silent then diff --git a/tasks/ibhagwan__fzf-lua-2568/tests/test.sh b/tasks/ibhagwan__fzf-lua-2568/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2b35bba5738765a45d30a437bb6625e0f70d8e8e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5921997472574fca3880b62949eb8679dc6f5afc > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2568/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2568/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2568/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2570/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2570/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4ef44274c5e55145cde87e4a884ecf568f2acea --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0867870a6033d7e9cc40f40aaf57290fba66682d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0867870a6033d7e9cc40f40aaf57290fba66682d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0867870a6033d7e9cc40f40aaf57290fba66682d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2570/instruction.md b/tasks/ibhagwan__fzf-lua-2570/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..838e24452e736e1a05df6149b4e807de832cac60 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(path): resolve symlink when compare bufname + +## Description + +nvim_buf_get_name/bufname return a resolved version + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0867870a6033`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2570/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2570/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..51fb28c481803d2ebe2735920e48fe68facc62b2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 10155238..9c2e359c 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -537,7 +537,7 @@ function M.entry_to_file(entry, opts, force_uri) + end + elseif file and #file > 0 then -- get bufnr from give path + local buf = vim.fn.bufnr(file) +- if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == file then ++ if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == (uv.fs_realpath(file) or file) then + bufnr = buf + bufname = file + end +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index 589271a4..b0f435b3 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -466,19 +466,19 @@ describe("Testing path module", function() + end) + + it("parse loaded path", function() +- helpers.SKIP_IF_MAC() +- if helpers.IS_WIN() then helpers.SKIP_IF_NOT_NIGHTLY() end ++ helpers.SKIP_IF_WIN() + local r = {} + vim.cmd [[bwipe]] +- vim.cmd.edit("/tmp/foo:bar.txt") +- local bufname = "/tmp/foo:bar.txt" +- eq(path.entry_to_file("/tmp/foo:bar.txt", r), { ++ local name = "/tmp/foo:bar.txt" ++ vim.cmd.edit(name) ++ vim.cmd([[sil write]]) ++ eq(path.entry_to_file(name, r), { + col = 0, + line = 0, +- stripped = bufname, +- path = bufname, ++ stripped = name, ++ path = name, + bufnr = vim.fn.bufnr(), +- bufname = helpers.IS_MAC() and vim.fs.joinpath("/private", bufname) or bufname, ++ bufname = name, + }) + end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2570/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2570/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2570/task.toml b/tasks/ibhagwan__fzf-lua-2570/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0fb263fd377b1fa678ccb717f169481bf63e5390 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2570" +description = "fix(path): resolve symlink when compare bufname" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "0867870a6033d7e9cc40f40aaf57290fba66682d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2570" +source_access = "auto" +built_at = "2026-11-16T16:09:56.063470+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c042d69c9cce13e684e2659f975d5f32351d5644333f41a4a0aca9b86c150afe" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-18T11:37:16Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/path.lua", + "tests/path_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[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:01.023090+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:45c0ab552dade398e5431927c7663399c35d3a41f64d52f8ff225f799f5b7343" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2570/tests/capture.py b/tasks/ibhagwan__fzf-lua-2570/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2570/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2570/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..838e24452e736e1a05df6149b4e807de832cac60 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(path): resolve symlink when compare bufname + +## Description + +nvim_buf_get_name/bufname return a resolved version + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0867870a6033`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2570/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2570/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..51fb28c481803d2ebe2735920e48fe68facc62b2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 10155238..9c2e359c 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -537,7 +537,7 @@ function M.entry_to_file(entry, opts, force_uri) + end + elseif file and #file > 0 then -- get bufnr from give path + local buf = vim.fn.bufnr(file) +- if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == file then ++ if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == (uv.fs_realpath(file) or file) then + bufnr = buf + bufname = file + end +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index 589271a4..b0f435b3 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -466,19 +466,19 @@ describe("Testing path module", function() + end) + + it("parse loaded path", function() +- helpers.SKIP_IF_MAC() +- if helpers.IS_WIN() then helpers.SKIP_IF_NOT_NIGHTLY() end ++ helpers.SKIP_IF_WIN() + local r = {} + vim.cmd [[bwipe]] +- vim.cmd.edit("/tmp/foo:bar.txt") +- local bufname = "/tmp/foo:bar.txt" +- eq(path.entry_to_file("/tmp/foo:bar.txt", r), { ++ local name = "/tmp/foo:bar.txt" ++ vim.cmd.edit(name) ++ vim.cmd([[sil write]]) ++ eq(path.entry_to_file(name, r), { + col = 0, + line = 0, +- stripped = bufname, +- path = bufname, ++ stripped = name, ++ path = name, + bufnr = vim.fn.bufnr(), +- bufname = helpers.IS_MAC() and vim.fs.joinpath("/private", bufname) or bufname, ++ bufname = name, + }) + end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2570/tests/test.sh b/tasks/ibhagwan__fzf-lua-2570/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f06ebc9134e8a86a0dbe8f69e42185c3acbed49c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 0867870a6033d7e9cc40f40aaf57290fba66682d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2570/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2570/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2570/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2571/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2571/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..62c6e1dfeaf731bf8401a17a85bf8abf01c3f20a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin db4764d61597dd548ccc31b625d7ccbb68a92925 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard db4764d61597dd548ccc31b625d7ccbb68a92925 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base db4764d61597dd548ccc31b625d7ccbb68a92925 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2571/instruction.md b/tasks/ibhagwan__fzf-lua-2571/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7a25376684e63ac1eb3cd96d7bb132a486f8256 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(skim): skim 0.12+ support reload + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db4764d61597`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2571/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2571/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..144d0fd28218185548bcd67689377059b5efcab7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 900d5659..08375426 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -960,9 +960,8 @@ M.convert_reload_actions = function(reload_cmd, opts) + local fallback ---@type boolean? + -- Does not work with fzf version < 0.36, fzf fails with + -- "error 2: bind action not specified:" (#735) +- -- Not yet supported with skim +- if not utils.has(opts, "fzf", { 0, 36 }) +- or utils.has(opts, "sk") ++ -- skim require 0.12+ https://github.com/skim-rs/skim/pull/604 ++ if (not utils.has(opts, "fzf", { 0, 36 }) and not utils.has(opts, "sk", { 0, 12, 0 })) + or not reload_cmd then + fallback = true + end diff --git a/tasks/ibhagwan__fzf-lua-2571/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2571/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2571/task.toml b/tasks/ibhagwan__fzf-lua-2571/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d01d316a7589a983af2466302fb94317bbe7b0e2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2571" +description = "fix(skim): skim 0.12+ support reload" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "db4764d61597dd548ccc31b625d7ccbb68a92925" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2571" +source_access = "auto" +built_at = "2026-11-16T16:09:56.062040+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d44b0ebb92fc707af2147a5bd0015b3070daa71ab5250659121e8b8e03157779" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-18T12:46:53Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/core.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.023668+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f3115440961220f747e51cf63e818d0765e6c5be7cef2beb7929d7acab7df0a5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2571/tests/capture.py b/tasks/ibhagwan__fzf-lua-2571/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2571/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2571/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7a25376684e63ac1eb3cd96d7bb132a486f8256 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(skim): skim 0.12+ support reload + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db4764d61597`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2571/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2571/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..144d0fd28218185548bcd67689377059b5efcab7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 900d5659..08375426 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -960,9 +960,8 @@ M.convert_reload_actions = function(reload_cmd, opts) + local fallback ---@type boolean? + -- Does not work with fzf version < 0.36, fzf fails with + -- "error 2: bind action not specified:" (#735) +- -- Not yet supported with skim +- if not utils.has(opts, "fzf", { 0, 36 }) +- or utils.has(opts, "sk") ++ -- skim require 0.12+ https://github.com/skim-rs/skim/pull/604 ++ if (not utils.has(opts, "fzf", { 0, 36 }) and not utils.has(opts, "sk", { 0, 12, 0 })) + or not reload_cmd then + fallback = true + end diff --git a/tasks/ibhagwan__fzf-lua-2571/tests/test.sh b/tasks/ibhagwan__fzf-lua-2571/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..42af59823369a60c7a4aff9bb921f9491a5da6fc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace db4764d61597dd548ccc31b625d7ccbb68a92925 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2571/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2571/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2571/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2572/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2572/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0deef080fcbdf462476e2562c69dc7a928b77d66 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b2c0603216adb92c6bba81053bc996d7ae95b77a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b2c0603216adb92c6bba81053bc996d7ae95b77a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b2c0603216adb92c6bba81053bc996d7ae95b77a \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2572/instruction.md b/tasks/ibhagwan__fzf-lua-2572/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8523fe3097d6d4404407bb112519658eaed2f1b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(manpages): warn when man executable or mandb cache is missing + +## Description + +basically i realized that `man -k .` was not working on nixos (the command for `:FzfLua man_pages` and that i was missing mandb. + +So, thought it would be nice to make sure that this doesn't happen to anyone else by warning in the picker :D + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b2c0603216ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2572/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2572/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..40bd18fe985cf96328d5e0290058d6a13b2f8c35 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/providers/manpages.lua b/lua/fzf-lua/providers/manpages.lua +index 92b68e39..34b6b4e3 100644 +--- a/lua/fzf-lua/providers/manpages.lua ++++ b/lua/fzf-lua/providers/manpages.lua +@@ -39,6 +39,17 @@ M.manpages = function(opts) + return + end + ++ if vim.fn.executable("man") ~= 1 then ++ utils.warn("'man' executable not found.") ++ return ++ end ++ ++ local out = vim.fn.system(opts.cmd) ++ if vim.v.shell_error ~= 0 or vim.trim(out) == "" then ++ utils.warn("'man -k' returned no results, try running 'sudo mandb' to populate the cache.") ++ return ++ end ++ + opts.fn_transform = function(x) + -- split by first occurrence of ' - ' (spaced hyphen) + local man, desc = x:match("^(.-) %- (.*)$") diff --git a/tasks/ibhagwan__fzf-lua-2572/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2572/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2572/task.toml b/tasks/ibhagwan__fzf-lua-2572/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e2792d9a046e425f14a871b1aa66b1d1b989821 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2572" +description = "fix(manpages): warn when man executable or mandb cache is missing" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b2c0603216adb92c6bba81053bc996d7ae95b77a" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2572" +source_access = "auto" +built_at = "2026-11-16T16:09:56.060852+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b06f80b1d3582ec2b7f86a13a65b16bcb5d7005810ab43b98d132472e0ec356a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-21T03:41:06Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/manpages.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[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:01.024201+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e63db6b7c3a1336a3c6d6a016c8aefa8fcac8e09930a3326d729615bd67e540e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2572/tests/capture.py b/tasks/ibhagwan__fzf-lua-2572/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2572/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2572/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8523fe3097d6d4404407bb112519658eaed2f1b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(manpages): warn when man executable or mandb cache is missing + +## Description + +basically i realized that `man -k .` was not working on nixos (the command for `:FzfLua man_pages` and that i was missing mandb. + +So, thought it would be nice to make sure that this doesn't happen to anyone else by warning in the picker :D + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b2c0603216ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2572/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2572/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..40bd18fe985cf96328d5e0290058d6a13b2f8c35 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/providers/manpages.lua b/lua/fzf-lua/providers/manpages.lua +index 92b68e39..34b6b4e3 100644 +--- a/lua/fzf-lua/providers/manpages.lua ++++ b/lua/fzf-lua/providers/manpages.lua +@@ -39,6 +39,17 @@ M.manpages = function(opts) + return + end + ++ if vim.fn.executable("man") ~= 1 then ++ utils.warn("'man' executable not found.") ++ return ++ end ++ ++ local out = vim.fn.system(opts.cmd) ++ if vim.v.shell_error ~= 0 or vim.trim(out) == "" then ++ utils.warn("'man -k' returned no results, try running 'sudo mandb' to populate the cache.") ++ return ++ end ++ + opts.fn_transform = function(x) + -- split by first occurrence of ' - ' (spaced hyphen) + local man, desc = x:match("^(.-) %- (.*)$") diff --git a/tasks/ibhagwan__fzf-lua-2572/tests/test.sh b/tasks/ibhagwan__fzf-lua-2572/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a70ff7615dd3b666d0a2786099b747ba1bfc8bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b2c0603216adb92c6bba81053bc996d7ae95b77a > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2572/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2572/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2572/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2576/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2576/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0aaa4e0c73314bafb4cb9c16a67b0d285f622dcd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9004cbb4c065a32b690e909c49903967b45301eb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9004cbb4c065a32b690e909c49903967b45301eb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9004cbb4c065a32b690e909c49903967b45301eb \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2576/instruction.md b/tasks/ibhagwan__fzf-lua-2576/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d9080637b70c64e4dc9ea3da8403ea53c4b3726 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Ability to filter treesitter nodes + +## Description + +It seems like the treesitter function can only be used to fuzzy-search all symbols. Maybe searching only through specific nodes could be useful (for example to find a function and jump to it) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9004cbb4c065`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2576/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2576/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2e26792888534e358ced94c5f0bac501f24cc345 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index c0d495e1..534c7418 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -592,10 +592,10 @@ M.treesitter = function(opts) + for _, definition in ipairs(get(bufnr0)) do + local nodes = get_local_nodes(definition) + for _, node in ipairs(nodes) do +- if node.node then ++ node.kind = node.kind and node.kind:gsub(".*%.", "") ++ if node.node and (not opts.node_filter or opts.node_filter(node, node.kind)) then + vim.schedule(function() + -- Remove node prefix, e.g. `locals.definition.var` +- node.kind = node.kind and node.kind:gsub(".*%.", "") + local lnum, col, _, _ = ts.get_node_range(node.node) + local node_text = ts.get_node_text(node.node, bufnr0) + local node_kind = node.kind and utils.ansi_from_hl(kind2hl(node.kind), node.kind) diff --git a/tasks/ibhagwan__fzf-lua-2576/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2576/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2576/task.toml b/tasks/ibhagwan__fzf-lua-2576/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90cb9201256a42f32afff4fb322957f8bf27b9de --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2576" +description = "Ability to filter treesitter nodes" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "9004cbb4c065a32b690e909c49903967b45301eb" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2576" +source_access = "auto" +built_at = "2026-11-16T16:09:56.055988+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:84e6950753eb1ead8147a81471cc6ccc9decaf602454d738ecc6c7372931e4c7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-01T15:34:30Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/buffers.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.024692+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:923f976d037c54cbd959f84491b23c210945b938597a4abe05df822e7b59cc85" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2576/tests/capture.py b/tasks/ibhagwan__fzf-lua-2576/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2576/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2576/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d9080637b70c64e4dc9ea3da8403ea53c4b3726 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Ability to filter treesitter nodes + +## Description + +It seems like the treesitter function can only be used to fuzzy-search all symbols. Maybe searching only through specific nodes could be useful (for example to find a function and jump to it) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9004cbb4c065`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2576/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2576/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2e26792888534e358ced94c5f0bac501f24cc345 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index c0d495e1..534c7418 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -592,10 +592,10 @@ M.treesitter = function(opts) + for _, definition in ipairs(get(bufnr0)) do + local nodes = get_local_nodes(definition) + for _, node in ipairs(nodes) do +- if node.node then ++ node.kind = node.kind and node.kind:gsub(".*%.", "") ++ if node.node and (not opts.node_filter or opts.node_filter(node, node.kind)) then + vim.schedule(function() + -- Remove node prefix, e.g. `locals.definition.var` +- node.kind = node.kind and node.kind:gsub(".*%.", "") + local lnum, col, _, _ = ts.get_node_range(node.node) + local node_text = ts.get_node_text(node.node, bufnr0) + local node_kind = node.kind and utils.ansi_from_hl(kind2hl(node.kind), node.kind) diff --git a/tasks/ibhagwan__fzf-lua-2576/tests/test.sh b/tasks/ibhagwan__fzf-lua-2576/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b1529a63aef1d4a9283bf45374f194b4c24ba727 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9004cbb4c065a32b690e909c49903967b45301eb > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2576/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2576/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2576/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2579/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2579/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..45b50affce153374bab45e4165341ab49654b70f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 76ddd6b56875bf4f6fd13848728207e738bb75a3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 76ddd6b56875bf4f6fd13848728207e738bb75a3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 76ddd6b56875bf4f6fd13848728207e738bb75a3 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2579/instruction.md b/tasks/ibhagwan__fzf-lua-2579/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..643b0ef1d992999977209a03d8df78a78e843873 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix bug when close_buf called with nil fzf_bufnr + +## Description + +Fixes a regression caused by 18837e2 merged in #2512. When using the `fzf-tmux` profile, fzf runs in a tmux popup not a nvim terminal buffer so passing nil to close_buf will throw. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76ddd6b56875`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2579/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2579/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..63f58a7f81b783db84501f12c9440368a758cf46 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9291536a..aefc9dae 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1000,7 +1000,9 @@ function FzfWin:close(fzf_bufnr, hide) + pcall(api.nvim_win_close, self.fzf_winid, true) + end + end +- if not hide then self:close_buf(self.fzf_bufnr) end ++ if not hide and self.fzf_bufnr then ++ self:close_buf(self.fzf_bufnr) ++ end + for k, _ in pairs(self.on_closes) do + self.on_closes[k](hide) + self.on_closes[k] = nil diff --git a/tasks/ibhagwan__fzf-lua-2579/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2579/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2579/task.toml b/tasks/ibhagwan__fzf-lua-2579/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..917fcefce5b18b8b23534565b8826c89435f161e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2579" +description = "fix bug when close_buf called with nil fzf_bufnr" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "76ddd6b56875bf4f6fd13848728207e738bb75a3" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2579" +source_access = "auto" +built_at = "2026-11-16T16:09:56.059653+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6bad2910aa0029afb53bfe38fbc395711cf6df63392e21f2085b026e2e084be4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-23T21:32:43Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.025166+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7fae8dae00ec7954a280244e65c0f3b7ce549f3ac8ae88118291dd1200709f4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2579/tests/capture.py b/tasks/ibhagwan__fzf-lua-2579/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2579/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2579/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..643b0ef1d992999977209a03d8df78a78e843873 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix bug when close_buf called with nil fzf_bufnr + +## Description + +Fixes a regression caused by 18837e2 merged in #2512. When using the `fzf-tmux` profile, fzf runs in a tmux popup not a nvim terminal buffer so passing nil to close_buf will throw. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `76ddd6b56875`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2579/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2579/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..63f58a7f81b783db84501f12c9440368a758cf46 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 9291536a..aefc9dae 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1000,7 +1000,9 @@ function FzfWin:close(fzf_bufnr, hide) + pcall(api.nvim_win_close, self.fzf_winid, true) + end + end +- if not hide then self:close_buf(self.fzf_bufnr) end ++ if not hide and self.fzf_bufnr then ++ self:close_buf(self.fzf_bufnr) ++ end + for k, _ in pairs(self.on_closes) do + self.on_closes[k](hide) + self.on_closes[k] = nil diff --git a/tasks/ibhagwan__fzf-lua-2579/tests/test.sh b/tasks/ibhagwan__fzf-lua-2579/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8aeb3fd5bb910a58a03018180ed8eeb8555de183 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 76ddd6b56875bf4f6fd13848728207e738bb75a3 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2579/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2579/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2579/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2582/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2582/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a164d95710e4563cfcc1e27e253bb00667bc40a1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 72ec224172eea757eab6b349775ad5bada7521d7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 72ec224172eea757eab6b349775ad5bada7521d7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 72ec224172eea757eab6b349775ad5bada7521d7 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2582/instruction.md b/tasks/ibhagwan__fzf-lua-2582/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4eec5fdb7dc2a664e7625f176e872557badae3a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): backdrop won't close after redraw + +## Description + +fix #2581 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `72ec224172ee`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2582/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2582/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..59cc42cff6b893305d76db23619dbd27b25a1f66 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/win/backdrop.lua b/lua/fzf-lua/win/backdrop.lua +index 6d373cd2..a8f32325 100644 +--- a/lua/fzf-lua/win/backdrop.lua ++++ b/lua/fzf-lua/win/backdrop.lua +@@ -14,7 +14,7 @@ function M.open(backdrop, zindex, hls) + if api.nvim_win_is_valid(M.win) then + api.nvim_win_set_config(M.win, { width = vim.o.columns, height = vim.o.lines }) + end +- return ++ return function() M.close() end + end + + -- Validate backdrop hlgroup and opacity +@@ -53,7 +53,6 @@ function M.open(backdrop, zindex, hls) + end + + function M.close() +- if not M.win or not M.buf then return end + if M.win and api.nvim_win_is_valid(M.win) then api.nvim_win_close(M.win, true) end + if M.buf and api.nvim_buf_is_valid(M.buf) then api.nvim_buf_delete(M.buf, { force = true }) end + M.buf = nil diff --git a/tasks/ibhagwan__fzf-lua-2582/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2582/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2582/task.toml b/tasks/ibhagwan__fzf-lua-2582/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49ab052df1d9ecb636700d3e74328a06a5a1553b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2582" +description = "fix(preview): backdrop won't close after redraw (#2581)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "72ec224172eea757eab6b349775ad5bada7521d7" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2582" +source_access = "auto" +built_at = "2026-11-16T16:09:56.058468+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:176f599ffbb6f25d7e03acc503a015374401fecfce124d1d2477375c44fd4b09" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-25T03:24:05Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win/backdrop.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.025750+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9f7e5d1d2746a004c238c49c37b654cea790dcd8c8607287568e25cde83b1beb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2582/tests/capture.py b/tasks/ibhagwan__fzf-lua-2582/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2582/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2582/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4eec5fdb7dc2a664e7625f176e872557badae3a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): backdrop won't close after redraw + +## Description + +fix #2581 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `72ec224172ee`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2582/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2582/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..59cc42cff6b893305d76db23619dbd27b25a1f66 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/win/backdrop.lua b/lua/fzf-lua/win/backdrop.lua +index 6d373cd2..a8f32325 100644 +--- a/lua/fzf-lua/win/backdrop.lua ++++ b/lua/fzf-lua/win/backdrop.lua +@@ -14,7 +14,7 @@ function M.open(backdrop, zindex, hls) + if api.nvim_win_is_valid(M.win) then + api.nvim_win_set_config(M.win, { width = vim.o.columns, height = vim.o.lines }) + end +- return ++ return function() M.close() end + end + + -- Validate backdrop hlgroup and opacity +@@ -53,7 +53,6 @@ function M.open(backdrop, zindex, hls) + end + + function M.close() +- if not M.win or not M.buf then return end + if M.win and api.nvim_win_is_valid(M.win) then api.nvim_win_close(M.win, true) end + if M.buf and api.nvim_buf_is_valid(M.buf) then api.nvim_buf_delete(M.buf, { force = true }) end + M.buf = nil diff --git a/tasks/ibhagwan__fzf-lua-2582/tests/test.sh b/tasks/ibhagwan__fzf-lua-2582/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cfeed34936760c4fa07332daa76fb53a3ea109cd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 72ec224172eea757eab6b349775ad5bada7521d7 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2582/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2582/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2582/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2584/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2584/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..11b2af313237355ce96976804c5374dd93aaf907 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cc81c66dba2153f08c382565466e18d6ea5a6c50 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cc81c66dba2153f08c382565466e18d6ea5a6c50 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cc81c66dba2153f08c382565466e18d6ea5a6c50 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2584/instruction.md b/tasks/ibhagwan__fzf-lua-2584/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94b2a34db716481e6bfd3e3bd7174e66594c405b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): copy buffer option to correctly position indent-blankline extmark + +## Description + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cc81c66dba21`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2584/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2584/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..31125bb9f43eec6099179fdad52a10761542ba6e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 8982399e..c2f38ba4 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1018,6 +1018,9 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + entry.filetype = vim.bo[entry.bufnr].filetype + local lines = api.nvim_buf_get_lines(entry.bufnr, 0, -1, false) + local tmpbuf = reuse_buf or self:get_tmp_buffer() ++ vim.bo[tmpbuf].expandtab = vim.bo[entry.bufnr].expandtab ++ vim.bo[tmpbuf].shiftwidth = vim.bo[entry.bufnr].shiftwidth ++ vim.bo[tmpbuf].tabstop = vim.bo[entry.bufnr].tabstop + api.nvim_buf_set_lines(tmpbuf, 0, -1, false, lines) + -- terminal buffers use minimal window style (2nd arg) + self:set_preview_buf(tmpbuf, entry.terminal) +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index fbacb208..d9755293 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -17,13 +17,15 @@ T["actions"] = new_set({ n_retry = not helpers.IS_LINUX() and 5 or nil }) + + T["actions"]["ui don't freeze on error"] = function() + helpers.SKIP_IF_NOT_NIGHTLY() ++ helpers.SKIP_IF_WIN() + -- reload({ "hide" }) + local screen_opts = { start_line = 1, end_line = 10, ignore_text = { 28 } } + -- fix flaky hit enter prompt on windows +- exec_lua([[ +- local extui = vim.F.npcall(require, 'vim._core.ui2') or vim.F.npcall(require, 'vim._extui') +- if extui then extui.enable({}) end +- ]]) ++ -- TODO: but enable ui2 have other werid flaky ++ -- exec_lua([[ ++ -- local extui = vim.F.npcall(require, 'vim._core.ui2') or vim.F.npcall(require, 'vim._extui') ++ -- if extui then extui.enable({}) end ++ -- ]]) + exec_lua( + [[FzfLua.fzf_exec({ "aaa", "bbb" }, { + actions = { enter = { fn = error, exec_silent = true } }, diff --git a/tasks/ibhagwan__fzf-lua-2584/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2584/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2584/task.toml b/tasks/ibhagwan__fzf-lua-2584/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68e68b924775e613c9cac82ef2894cac8dfeb6e6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2584" +description = "fix(preview): copy buffer option to correctly position indent-blankline extmark (#2583)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "cc81c66dba2153f08c382565466e18d6ea5a6c50" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2584" +source_access = "auto" +built_at = "2026-11-16T16:09:56.057182+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:553b850e77eb0f352910e212bb09111adc3c01e97590499b37236bb862ccd0b8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-25T12:21:42Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", + "tests/actions_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[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:01.026302+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9ed025470da3c7ea792fe37f43228cc2f6a4139b292e89ad13b1f0d8dffe0f8c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2584/tests/capture.py b/tasks/ibhagwan__fzf-lua-2584/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2584/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2584/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94b2a34db716481e6bfd3e3bd7174e66594c405b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(preview): copy buffer option to correctly position indent-blankline extmark + +## Description + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cc81c66dba21`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2584/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2584/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..31125bb9f43eec6099179fdad52a10761542ba6e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 8982399e..c2f38ba4 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1018,6 +1018,9 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + entry.filetype = vim.bo[entry.bufnr].filetype + local lines = api.nvim_buf_get_lines(entry.bufnr, 0, -1, false) + local tmpbuf = reuse_buf or self:get_tmp_buffer() ++ vim.bo[tmpbuf].expandtab = vim.bo[entry.bufnr].expandtab ++ vim.bo[tmpbuf].shiftwidth = vim.bo[entry.bufnr].shiftwidth ++ vim.bo[tmpbuf].tabstop = vim.bo[entry.bufnr].tabstop + api.nvim_buf_set_lines(tmpbuf, 0, -1, false, lines) + -- terminal buffers use minimal window style (2nd arg) + self:set_preview_buf(tmpbuf, entry.terminal) +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index fbacb208..d9755293 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -17,13 +17,15 @@ T["actions"] = new_set({ n_retry = not helpers.IS_LINUX() and 5 or nil }) + + T["actions"]["ui don't freeze on error"] = function() + helpers.SKIP_IF_NOT_NIGHTLY() ++ helpers.SKIP_IF_WIN() + -- reload({ "hide" }) + local screen_opts = { start_line = 1, end_line = 10, ignore_text = { 28 } } + -- fix flaky hit enter prompt on windows +- exec_lua([[ +- local extui = vim.F.npcall(require, 'vim._core.ui2') or vim.F.npcall(require, 'vim._extui') +- if extui then extui.enable({}) end +- ]]) ++ -- TODO: but enable ui2 have other werid flaky ++ -- exec_lua([[ ++ -- local extui = vim.F.npcall(require, 'vim._core.ui2') or vim.F.npcall(require, 'vim._extui') ++ -- if extui then extui.enable({}) end ++ -- ]]) + exec_lua( + [[FzfLua.fzf_exec({ "aaa", "bbb" }, { + actions = { enter = { fn = error, exec_silent = true } }, diff --git a/tasks/ibhagwan__fzf-lua-2584/tests/test.sh b/tasks/ibhagwan__fzf-lua-2584/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..fedd6b4f915b1c78268dd6d8a2db876c4dc31b86 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace cc81c66dba2153f08c382565466e18d6ea5a6c50 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2584/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2584/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2584/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2585/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2585/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83573181b237019d305ba71219b8a089ef5c268e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 55f1136b125f513c667d417ec51d1cb961221914 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 55f1136b125f513c667d417ec51d1cb961221914 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 55f1136b125f513c667d417ec51d1cb961221914 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2585/instruction.md b/tasks/ibhagwan__fzf-lua-2585/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82cf207351b2134fb9d02a0a3abbda522717b6d4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(preview): don't copy virt_text when leftcol isn't sync to src buffer + +## Description + +Fix + +Upstream issue: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `55f1136b125f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2585/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2585/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d2130d75981c8d1d5315359142430037cad9ed6a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index c2f38ba4..278239ef 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -630,8 +630,13 @@ function Previewer.base:copy_extmarks() + local dst_bufnr = self.preview_bufnr + local ns = self.ns_extmarks + local win = self.win.preview_winid +- local topline = fn.line("w0", win) ++ local winview = api.nvim_win_call(win, fn.winsaveview) ++ local topline = winview.topline + local botline = fn.line("w$", win) ++ local src_winid = fn.bufwinid(src_bufnr) ++ local src_leftcol = src_winid ~= -1 and api.nvim_win_call(src_winid, fn.winsaveview).leftcol or nil ++ -- virt_text is related to screen https://github.com/neovim/neovim/issues/14050 ++ local no_virt_text = winview.leftcol ~= src_leftcol + api.nvim_buf_clear_namespace(dst_bufnr, ns, topline, botline) + for _, n in pairs(api.nvim_get_namespaces()) do + local extmarks = api.nvim_buf_get_extmarks(src_bufnr, n, { topline - 1, 0 }, +@@ -640,6 +645,7 @@ function Previewer.base:copy_extmarks() + for _, m in ipairs(extmarks) do + local _, row, col, details = unpack(m) ---@cast details -? + details.ns_id = nil ++ if no_virt_text and details.virt_text then details.virt_text = nil end + pcall(api.nvim_buf_set_extmark, dst_bufnr, ns, row, col, details) + end + end diff --git a/tasks/ibhagwan__fzf-lua-2585/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2585/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2585/task.toml b/tasks/ibhagwan__fzf-lua-2585/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e25d80974bb412c23c1fa30a068d1ee92a20ff6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2585" +description = "fix(preview): don't copy virt_text when leftcol isn't sync to src buffer" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "55f1136b125f513c667d417ec51d1cb961221914" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2585" +source_access = "auto" +built_at = "2026-11-16T16:09:56.028420+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3a6618d64cccd73557a1e3b9c9e8c7adba893a167278877c75f3dac636df5d79" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-25T17:41:16Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[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:01.026786+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a1c0ea0685fcce063068cd4d291e190312ff7c18aeb532cbb92579d0332e4082" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2585/tests/capture.py b/tasks/ibhagwan__fzf-lua-2585/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2585/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2585/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82cf207351b2134fb9d02a0a3abbda522717b6d4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(preview): don't copy virt_text when leftcol isn't sync to src buffer + +## Description + +Fix + +Upstream issue: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `55f1136b125f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2585/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2585/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d2130d75981c8d1d5315359142430037cad9ed6a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index c2f38ba4..278239ef 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -630,8 +630,13 @@ function Previewer.base:copy_extmarks() + local dst_bufnr = self.preview_bufnr + local ns = self.ns_extmarks + local win = self.win.preview_winid +- local topline = fn.line("w0", win) ++ local winview = api.nvim_win_call(win, fn.winsaveview) ++ local topline = winview.topline + local botline = fn.line("w$", win) ++ local src_winid = fn.bufwinid(src_bufnr) ++ local src_leftcol = src_winid ~= -1 and api.nvim_win_call(src_winid, fn.winsaveview).leftcol or nil ++ -- virt_text is related to screen https://github.com/neovim/neovim/issues/14050 ++ local no_virt_text = winview.leftcol ~= src_leftcol + api.nvim_buf_clear_namespace(dst_bufnr, ns, topline, botline) + for _, n in pairs(api.nvim_get_namespaces()) do + local extmarks = api.nvim_buf_get_extmarks(src_bufnr, n, { topline - 1, 0 }, +@@ -640,6 +645,7 @@ function Previewer.base:copy_extmarks() + for _, m in ipairs(extmarks) do + local _, row, col, details = unpack(m) ---@cast details -? + details.ns_id = nil ++ if no_virt_text and details.virt_text then details.virt_text = nil end + pcall(api.nvim_buf_set_extmark, dst_bufnr, ns, row, col, details) + end + end diff --git a/tasks/ibhagwan__fzf-lua-2585/tests/test.sh b/tasks/ibhagwan__fzf-lua-2585/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..86ede52eb61bb8cef9f75f97f795588bb4dac9a6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 55f1136b125f513c667d417ec51d1cb961221914 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2585/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2585/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2585/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2588/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2588/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..883ae4085a5a6cd4824e8852dac1aac19320bf2a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1653c4c599dba538fbebf9de81a96380dc2998ff 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1653c4c599dba538fbebf9de81a96380dc2998ff \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1653c4c599dba538fbebf9de81a96380dc2998ff \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2588/instruction.md b/tasks/ibhagwan__fzf-lua-2588/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75732412bd04989c70e3e5cafc00ee8228cf2f77 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** fix(win): force update fzf winhl when reuse window + +## Description + +When reuse window (cmd reload or switch to new picker), +fzf job buffer will change, so have to reapply window-local option again + +Fix regression from + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1653c4c599db`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2588/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2588/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..10c3b7530df0595df05e4b1d7ed33190ce0adbe4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/solution/patch.diff @@ -0,0 +1,199 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index ecd736b9..bffe2e5d 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -636,11 +636,16 @@ local copy_extmarks = function(src_buf, buf, win, topline, botline, ns) + api.nvim_buf_clear_namespace(buf, ns, topline, botline) + local extmarks = api.nvim_buf_get_extmarks(src_buf, -1, { topline, 0 }, { botline, -1 }, + { details = true }) ++ local namespaces = api.nvim_get_namespaces() ++ local ignore = {} ++ if namespaces["snacks.image"] then ignore[namespaces["snacks.image"]] = true end + for _, m in ipairs(extmarks) do + local _, row, col, details = unpack(m) ---@cast details -? +- details.ns_id = nil +- if no_virt_text and details.virt_text then details.virt_text = nil end +- pcall(api.nvim_buf_set_extmark, buf, ns, row, col, details) ++ if not ignore[details.ns_id] then ++ details.ns_id = nil ++ if no_virt_text and details.virt_text then details.virt_text = nil end ++ pcall(api.nvim_buf_set_extmark, buf, ns, row, col, details) ++ end + end + end + +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 71428d04..1815b0a8 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -850,6 +850,7 @@ function FzfWin:create() + self:setup_autocmds() + self:setup_keybinds() + self:treesitter_attach() ++ self:reset_winhl(self.fzf_winid) + -- also recall the user's 'on_create' (#394) + if type(self.winopts.on_create) == "function" then + self.winopts.on_create({ winid = self.fzf_winid, bufnr = self.fzf_bufnr }) +@@ -930,7 +931,6 @@ function FzfWin:create() + self:setup_autocmds() + self:setup_keybinds() + self:treesitter_attach() +- + self:reset_winhl(self.fzf_winid) + + -- potential workarond for `` freezing neovim (#1091) +diff --git a/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 b/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 +new file mode 100644 +index 00000000..27231368 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 +@@ -0,0 +1,59 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01| ++02|~ ++03|~ ╭─────────────────── Files h ────────────────────╮ ++04|~ │> 270/270 (0) │ ++05|~ │──────────────────────────────────────────────── │ ++06|~ │▌ .editorconfig ││ ++07|~ │ .emmyrc.json │ ++08|~ │ .github/ISSUE_TEMPLATE/bug.yaml │ ++09|~ │ .github/ISSUE_TEMPLATE/config.yml │ ++10|~ │ .github/ISSUE_TEMPLATE/feature.yaml │ ++11|~ │ .github/workflows/ci.yaml │ ++12|~ │ .github/workflows/lint.yaml │ ++13|~ │ .github/workflows/luarocks-release.yaml │ ++14|~ ╰─────────────────────────────────────────────────╯ ++15|~ ╭───────────────── .editorconfig ─────────────────╮ ++16|~ │ 1 # https://github.com/CppCXY/EmmyLuaCodeStyle/ ++17|~ │ 2 # see https://github.com/CppCXY/EmmyLuaCodeSt│ ++18|~ │ 3 [*.lua] │ ++19|~ │ 4 # [basic] │ ++20|~ │ 5 │ ++21|~ │ 6 # optional space/tab │ ++22|~ ╰─────────────────────────────────────────────────╯ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All ++ ++--|---------|---------|---------|---------|---------|---------|---- ++01|0000000000000000000000000000000000000000000000000000000000000000 ++02|1111111111111111111111111111111111111111111111111111111111111111 ++03|1111111222222222222222222222222222333222222222222222222222111111 ++04|1111111245222222222222222222222222222222222226666666666622111111 ++05|1111111277777777777777777777777777777777777777777777777722111111 ++06|1111111289::::::::::::::::::::::::::::::::::::::::::::::72111111 ++07|11111112;2222222222222222222222222222222222222222222222222111111 ++08|11111112;2222222222222222222222222222222222222222222222222111111 ++09|11111112;2222222222222222222222222222222222222222222222222111111 ++10|11111112;2222222222222222222222222222222222222222222222222111111 ++11|11111112;2222222222222222222222222222222222222222222222222111111 ++12|11111112;2222222222222222222222222222222222222222222222222111111 ++13|11111112;2222222222222222222222222222222222222222222222222111111 ++14|1111111222222222222222222222222222222222222222222222222222111111 ++15|1111111222222222222222222222222222222222222222222222222222111111 ++16|11111112<<<<=============================================>111111 ++17|11111112<<<<=============================================2111111 ++18|11111112<<< 270/270 (0) │ ++05|~ │──────────────────────────────────────────────── │ ++06|~ │▌ .editorconfig ││ ++07|~ │ .emmyrc.json │ ++08|~ │ .github/ISSUE_TEMPLATE/bug.yaml │ ++09|~ │ .github/ISSUE_TEMPLATE/config.yml │ ++10|~ │ .github/ISSUE_TEMPLATE/feature.yaml │ ++11|~ │ .github/workflows/ci.yaml │ ++12|~ │ .github/workflows/lint.yaml │ ++13|~ │ .github/workflows/luarocks-release.yaml │ ++14|~ ╰─────────────────────────────────────────────────╯ ++15|~ ╭───────────────── .editorconfig ─────────────────╮ ++16|~ │ 1 # https://github.com/CppCXY/EmmyLuaCodeStyle/ ++17|~ │ 2 # see https://github.com/CppCXY/EmmyLuaCodeSt│ ++18|~ │ 3 [*.lua] │ ++19|~ │ 4 # [basic] │ ++20|~ │ 5 │ ++21|~ │ 6 # optional space/tab │ ++22|~ ╰─────────────────────────────────────────────────╯ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All ++ ++--|---------|---------|---------|---------|---------|---------|---- ++01|0000000000000000000000000000000000000000000000000000000000000000 ++02|1111111111111111111111111111111111111111111111111111111111111111 ++03|1111111222222222222222222222222222333222222222222222222222111111 ++04|1111111245222222222222222222222222222222222226666666666622111111 ++05|1111111277777777777777777777777777777777777777777777777722111111 ++06|1111111289::::::::::::::::::::::::::::::::::::::::::::::72111111 ++07|11111112;2222222222222222222222222222222222222222222222222111111 ++08|11111112;2222222222222222222222222222222222222222222222222111111 ++09|11111112;2222222222222222222222222222222222222222222222222111111 ++10|11111112;2222222222222222222222222222222222222222222222222111111 ++11|11111112;2222222222222222222222222222222222222222222222222111111 ++12|11111112;2222222222222222222222222222222222222222222222222111111 ++13|11111112;2222222222222222222222222222222222222222222222222111111 ++14|1111111222222222222222222222222222222222222222222222222222111111 ++15|1111111222222222222222222222222222222222222222222222222222111111 ++16|11111112<<<<=============================================>111111 ++17|11111112<<<<=============================================2111111 ++18|11111112<<< 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()) diff --git a/tasks/ibhagwan__fzf-lua-2588/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2588/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75732412bd04989c70e3e5cafc00ee8228cf2f77 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** fix(win): force update fzf winhl when reuse window + +## Description + +When reuse window (cmd reload or switch to new picker), +fzf job buffer will change, so have to reapply window-local option again + +Fix regression from + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1653c4c599db`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2588/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2588/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..10c3b7530df0595df05e4b1d7ed33190ce0adbe4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/tests/oracle.patch @@ -0,0 +1,199 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index ecd736b9..bffe2e5d 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -636,11 +636,16 @@ local copy_extmarks = function(src_buf, buf, win, topline, botline, ns) + api.nvim_buf_clear_namespace(buf, ns, topline, botline) + local extmarks = api.nvim_buf_get_extmarks(src_buf, -1, { topline, 0 }, { botline, -1 }, + { details = true }) ++ local namespaces = api.nvim_get_namespaces() ++ local ignore = {} ++ if namespaces["snacks.image"] then ignore[namespaces["snacks.image"]] = true end + for _, m in ipairs(extmarks) do + local _, row, col, details = unpack(m) ---@cast details -? +- details.ns_id = nil +- if no_virt_text and details.virt_text then details.virt_text = nil end +- pcall(api.nvim_buf_set_extmark, buf, ns, row, col, details) ++ if not ignore[details.ns_id] then ++ details.ns_id = nil ++ if no_virt_text and details.virt_text then details.virt_text = nil end ++ pcall(api.nvim_buf_set_extmark, buf, ns, row, col, details) ++ end + end + end + +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 71428d04..1815b0a8 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -850,6 +850,7 @@ function FzfWin:create() + self:setup_autocmds() + self:setup_keybinds() + self:treesitter_attach() ++ self:reset_winhl(self.fzf_winid) + -- also recall the user's 'on_create' (#394) + if type(self.winopts.on_create) == "function" then + self.winopts.on_create({ winid = self.fzf_winid, bufnr = self.fzf_bufnr }) +@@ -930,7 +931,6 @@ function FzfWin:create() + self:setup_autocmds() + self:setup_keybinds() + self:treesitter_attach() +- + self:reset_winhl(self.fzf_winid) + + -- potential workarond for `` freezing neovim (#1091) +diff --git a/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 b/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 +new file mode 100644 +index 00000000..27231368 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---highlight---unchange-when-reuse-win-#2588 +@@ -0,0 +1,59 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01| ++02|~ ++03|~ ╭─────────────────── Files h ────────────────────╮ ++04|~ │> 270/270 (0) │ ++05|~ │──────────────────────────────────────────────── │ ++06|~ │▌ .editorconfig ││ ++07|~ │ .emmyrc.json │ ++08|~ │ .github/ISSUE_TEMPLATE/bug.yaml │ ++09|~ │ .github/ISSUE_TEMPLATE/config.yml │ ++10|~ │ .github/ISSUE_TEMPLATE/feature.yaml │ ++11|~ │ .github/workflows/ci.yaml │ ++12|~ │ .github/workflows/lint.yaml │ ++13|~ │ .github/workflows/luarocks-release.yaml │ ++14|~ ╰─────────────────────────────────────────────────╯ ++15|~ ╭───────────────── .editorconfig ─────────────────╮ ++16|~ │ 1 # https://github.com/CppCXY/EmmyLuaCodeStyle/ ++17|~ │ 2 # see https://github.com/CppCXY/EmmyLuaCodeSt│ ++18|~ │ 3 [*.lua] │ ++19|~ │ 4 # [basic] │ ++20|~ │ 5 │ ++21|~ │ 6 # optional space/tab │ ++22|~ ╰─────────────────────────────────────────────────╯ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All ++ ++--|---------|---------|---------|---------|---------|---------|---- ++01|0000000000000000000000000000000000000000000000000000000000000000 ++02|1111111111111111111111111111111111111111111111111111111111111111 ++03|1111111222222222222222222222222222333222222222222222222222111111 ++04|1111111245222222222222222222222222222222222226666666666622111111 ++05|1111111277777777777777777777777777777777777777777777777722111111 ++06|1111111289::::::::::::::::::::::::::::::::::::::::::::::72111111 ++07|11111112;2222222222222222222222222222222222222222222222222111111 ++08|11111112;2222222222222222222222222222222222222222222222222111111 ++09|11111112;2222222222222222222222222222222222222222222222222111111 ++10|11111112;2222222222222222222222222222222222222222222222222111111 ++11|11111112;2222222222222222222222222222222222222222222222222111111 ++12|11111112;2222222222222222222222222222222222222222222222222111111 ++13|11111112;2222222222222222222222222222222222222222222222222111111 ++14|1111111222222222222222222222222222222222222222222222222222111111 ++15|1111111222222222222222222222222222222222222222222222222222111111 ++16|11111112<<<<=============================================>111111 ++17|11111112<<<<=============================================2111111 ++18|11111112<<< 270/270 (0) │ ++05|~ │──────────────────────────────────────────────── │ ++06|~ │▌ .editorconfig ││ ++07|~ │ .emmyrc.json │ ++08|~ │ .github/ISSUE_TEMPLATE/bug.yaml │ ++09|~ │ .github/ISSUE_TEMPLATE/config.yml │ ++10|~ │ .github/ISSUE_TEMPLATE/feature.yaml │ ++11|~ │ .github/workflows/ci.yaml │ ++12|~ │ .github/workflows/lint.yaml │ ++13|~ │ .github/workflows/luarocks-release.yaml │ ++14|~ ╰─────────────────────────────────────────────────╯ ++15|~ ╭───────────────── .editorconfig ─────────────────╮ ++16|~ │ 1 # https://github.com/CppCXY/EmmyLuaCodeStyle/ ++17|~ │ 2 # see https://github.com/CppCXY/EmmyLuaCodeSt│ ++18|~ │ 3 [*.lua] │ ++19|~ │ 4 # [basic] │ ++20|~ │ 5 │ ++21|~ │ 6 # optional space/tab │ ++22|~ ╰─────────────────────────────────────────────────╯ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All ++ ++--|---------|---------|---------|---------|---------|---------|---- ++01|0000000000000000000000000000000000000000000000000000000000000000 ++02|1111111111111111111111111111111111111111111111111111111111111111 ++03|1111111222222222222222222222222222333222222222222222222222111111 ++04|1111111245222222222222222222222222222222222226666666666622111111 ++05|1111111277777777777777777777777777777777777777777777777722111111 ++06|1111111289::::::::::::::::::::::::::::::::::::::::::::::72111111 ++07|11111112;2222222222222222222222222222222222222222222222222111111 ++08|11111112;2222222222222222222222222222222222222222222222222111111 ++09|11111112;2222222222222222222222222222222222222222222222222111111 ++10|11111112;2222222222222222222222222222222222222222222222222111111 ++11|11111112;2222222222222222222222222222222222222222222222222111111 ++12|11111112;2222222222222222222222222222222222222222222222222111111 ++13|11111112;2222222222222222222222222222222222222222222222222111111 ++14|1111111222222222222222222222222222222222222222222222222222111111 ++15|1111111222222222222222222222222222222222222222222222222222111111 ++16|11111112<<<<=============================================>111111 ++17|11111112<<<<=============================================2111111 ++18|11111112<<< "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2588/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2588/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2588/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2592/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2592/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..434d660c731bc9d316e5cbe85e8a915a994892e2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 29ee11c06e1b8c354cc5a3212e6d24c9b8ed4f22 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 29ee11c06e1b8c354cc5a3212e6d24c9b8ed4f22 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 29ee11c06e1b8c354cc5a3212e6d24c9b8ed4f22 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2592/instruction.md b/tasks/ibhagwan__fzf-lua-2592/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0ccd6c5b03837e4b6ab265c675e138df4d07fe8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** fix(actions): set lnum=0 + valid=1 in sel_to_qf + +## Description + +For any qf entry with/without lnum, `:cnext` don't respect +`:h restore-cursor`. + +With lnum=0, user can rewrite `:cnext` in script to custom +the jump behavior, since this is a file entry. + +`valid=1` to make sure `:cfdo` can work as expected (#1560). + +e.g.: +```lua +---@param next boolean +local qf_next = function(next) + next = next ~= false + local list = fn.getqflist({ idx = 0, size = 0, items = 0 }) + local items, size, idx = list.items, list.size, list.idx + local start, stop, step = unpack(next and { idx + 1, size, 1 } or { idx - 1, 1, -1 }) + for i = start, stop, step do + local item = items[i] + if item.valid == 1 and item.lnum == 0 then + fn.setqflist({}, 'r', { idx = i }) + return vim.cmd('buffer ' .. item.bufnr) + elseif next then + return (pcall(vim.cmd.cnext) or pcall(vim.cmd.cfirst)) + else + return (pcall(vim.cmd.cprevious) or pcall(vim.cmd.clast)) + end + end + if next then + return (pcall(vim.cmd.cfirst)) + else + return (pcall(vim.cmd.clast)) + end +end + +---@param next boolean +M.next = function(next) + if vim.bo.filetype ~= 'qf' then return qf_next(next) end + return vim._with({ win = fn.win_getid(fn.winnr('#')) }, function() return qf_next(next) end) +end +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `29ee11c06e1b`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2592/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2592/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8a9f2cfc7822d78a40f75530cb491f7db5e59b57 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 6139f488..06a53403 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -314,7 +314,8 @@ local sel_to_qf = function(selected, opts, is_loclist) + table.insert(qf_list, { + bufnr = file.bufnr, + filename = file.bufname or file.path or file.uri, +- lnum = file.line > 0 and file.line or 1, ++ lnum = file.line or 0, ++ valid = 1, + col = file.col, + text = text, + }) +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 14f5e30a..c7142dfe 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -133,8 +133,9 @@ return { + local text = e.stripped:match(":%d+:%d?%d?%d?%d?:?(.*)$") or "" + table.insert(qf_items, { + filename = e.path, +- lnum = math.max(1, e.line or 1), +- col = math.max(1, e.col or 1), ++ lnum = e.line or 0, ++ col = e.col or 0, ++ valid = 1, + text = text, + }) + end diff --git a/tasks/ibhagwan__fzf-lua-2592/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2592/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2592/task.toml b/tasks/ibhagwan__fzf-lua-2592/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..03a441e8c67dabe169d855d5f0e133264b88ccd0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2592" +description = "fix(actions): set lnum=0 + valid=1 in sel_to_qf" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "29ee11c06e1b8c354cc5a3212e6d24c9b8ed4f22" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2592" +source_access = "auto" +built_at = "2026-11-16T16:09:56.031564+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6c9defe40d524262d1ad67d61f086b3aebefaaf2b8445221f8240b67c2b8032d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-02-28T07:48:09Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/profiles/cli.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[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:01.027799+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9e784cd5e7a22ba2edf8e3bb2db1833af63f4e81e3e6293620576bd8407b8ba4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2592/tests/capture.py b/tasks/ibhagwan__fzf-lua-2592/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2592/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2592/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0ccd6c5b03837e4b6ab265c675e138df4d07fe8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/tests/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** fix(actions): set lnum=0 + valid=1 in sel_to_qf + +## Description + +For any qf entry with/without lnum, `:cnext` don't respect +`:h restore-cursor`. + +With lnum=0, user can rewrite `:cnext` in script to custom +the jump behavior, since this is a file entry. + +`valid=1` to make sure `:cfdo` can work as expected (#1560). + +e.g.: +```lua +---@param next boolean +local qf_next = function(next) + next = next ~= false + local list = fn.getqflist({ idx = 0, size = 0, items = 0 }) + local items, size, idx = list.items, list.size, list.idx + local start, stop, step = unpack(next and { idx + 1, size, 1 } or { idx - 1, 1, -1 }) + for i = start, stop, step do + local item = items[i] + if item.valid == 1 and item.lnum == 0 then + fn.setqflist({}, 'r', { idx = i }) + return vim.cmd('buffer ' .. item.bufnr) + elseif next then + return (pcall(vim.cmd.cnext) or pcall(vim.cmd.cfirst)) + else + return (pcall(vim.cmd.cprevious) or pcall(vim.cmd.clast)) + end + end + if next then + return (pcall(vim.cmd.cfirst)) + else + return (pcall(vim.cmd.clast)) + end +end + +---@param next boolean +M.next = function(next) + if vim.bo.filetype ~= 'qf' then return qf_next(next) end + return vim._with({ win = fn.win_getid(fn.winnr('#')) }, function() return qf_next(next) end) +end +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `29ee11c06e1b`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2592/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2592/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8a9f2cfc7822d78a40f75530cb491f7db5e59b57 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 6139f488..06a53403 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -314,7 +314,8 @@ local sel_to_qf = function(selected, opts, is_loclist) + table.insert(qf_list, { + bufnr = file.bufnr, + filename = file.bufname or file.path or file.uri, +- lnum = file.line > 0 and file.line or 1, ++ lnum = file.line or 0, ++ valid = 1, + col = file.col, + text = text, + }) +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 14f5e30a..c7142dfe 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -133,8 +133,9 @@ return { + local text = e.stripped:match(":%d+:%d?%d?%d?%d?:?(.*)$") or "" + table.insert(qf_items, { + filename = e.path, +- lnum = math.max(1, e.line or 1), +- col = math.max(1, e.col or 1), ++ lnum = e.line or 0, ++ col = e.col or 0, ++ valid = 1, + text = text, + }) + end diff --git a/tasks/ibhagwan__fzf-lua-2592/tests/test.sh b/tasks/ibhagwan__fzf-lua-2592/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..38b5a81eed00e01d310d1b1acd112d11c169ebf0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 29ee11c06e1b8c354cc5a3212e6d24c9b8ed4f22 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2592/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2592/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2592/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2593/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2593/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..595755da70d1151e05bc85a3d05ad3780fc8cdbe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 531092c73d8a09d98113bd84ae3e12121af0fdbd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 531092c73d8a09d98113bd84ae3e12121af0fdbd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 531092c73d8a09d98113bd84ae3e12121af0fdbd \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2593/instruction.md b/tasks/ibhagwan__fzf-lua-2593/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec2eb152db0faf400aa4589ab8111fd4670afceb --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(global): transform with-nth with fzf>= 0.69 + +## Description + +fix #2515 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `531092c73d8a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2593/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2593/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bb29475ad502988995c53e8e260967c3383db98d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/solution/patch.diff @@ -0,0 +1,58 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index e59327f8..8e6d73f6 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -557,6 +557,7 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + end) + return { + { "files", desc = "Files" }, ++ -- { "blines", desc = "blines", prefix = "/" }, + { "buffers", desc = "Bufs", prefix = "$" }, + doc_sym_supported and { + "lsp_document_symbols", +@@ -591,10 +592,11 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + }, + } + end, +- fzf_opts = { ["--nth"] = false, ["--with-nth"] = false }, ++ fzf_opts = { ["--delimiter"] = "[\t]", ["--with-nth"] = ".." }, + winopts = { preview = { winopts = { cursorline = true } } }, + _ctx = { includeBuflist = true }, -- we include a buffer picker + _fzf_nth_devicons = false, ++ _treesitter = true, + }) + + +diff --git a/lua/fzf-lua/providers/meta.lua b/lua/fzf-lua/providers/meta.lua +index 9419d27f..30f99fc4 100644 +--- a/lua/fzf-lua/providers/meta.lua ++++ b/lua/fzf-lua/providers/meta.lua +@@ -190,6 +190,13 @@ M.global = function(opts) + or opts_copy) + pickers[name] = def + end ++ -- HACK: inherit fzf_opts from the normalized picker opts so we have ++ -- with-nth for the transform (e.g. for blines) ++ -- TODO: we can probably inerit all opts but I'm not sure what would be ++ -- the effects of that, this entire picker needs refactoring ++ local picker_opts = config.normalize_opts(t.opts, name:gsub("^lsp_", "lsp.")) ++ if not utils.map_get(def, "opts.fzf_opts") then utils.map_set(def, "opts.fzf_opts", {}) end ++ def.opts.fzf_opts = vim.tbl_deep_extend("force", def.opts.fzf_opts, picker_opts.fzf_opts) + -- Instantiate the previewer, opts isn't guaranteed if the picker + -- isn't avilable, e.g. `tags` when not tags file exists + if def.opts and def.opts.previewer then +@@ -249,6 +256,14 @@ M.global = function(opts) + win:redraw_preview() + end + reload = string.format("reload(%s)+", new_picker.contents) ++ -- fzf >= 0.69 supports `change-with-nth` to dynamically change `--with-nth` ++ -- dynamically update `--with-nth` per-picker (fzf >= 0.69) ++ -- e.g. blines uses `--with-nth=4..` to hide buffer numbers ++ if utils.has(opts, "fzf", { 0, 69 }) then ++ -- `false|nil` defaults to all fields (..) ++ local with_nth = utils.map_get(new_picker, "opts.fzf_opts.--with-nth") ++ reload = reload .. string.format("change-with-nth(%s)+", with_nth or "..") ++ end + cur_sub = new_sub + cur_picker = new_picker + end diff --git a/tasks/ibhagwan__fzf-lua-2593/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2593/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2593/task.toml b/tasks/ibhagwan__fzf-lua-2593/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..357573a5a8d82068874f075824690af8549cf86e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2593" +description = "fix(global): transform with-nth with fzf>= 0.69" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "531092c73d8a09d98113bd84ae3e12121af0fdbd" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2593" +source_access = "auto" +built_at = "2026-11-16T16:09:56.054766+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a36f52f1419ad28c4d7a87bf549b3fa88189adbff37e9e4c97397328bbcc0a0a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-01T18:29:57Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/meta.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[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:01.028295+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3fe57d8be3b49f9b96d94ff706a4188d61ace40cff9963c72cc6c193a054fa51" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2593/tests/capture.py b/tasks/ibhagwan__fzf-lua-2593/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2593/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2593/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec2eb152db0faf400aa4589ab8111fd4670afceb --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(global): transform with-nth with fzf>= 0.69 + +## Description + +fix #2515 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `531092c73d8a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2593/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2593/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bb29475ad502988995c53e8e260967c3383db98d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/tests/oracle.patch @@ -0,0 +1,58 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index e59327f8..8e6d73f6 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -557,6 +557,7 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + end) + return { + { "files", desc = "Files" }, ++ -- { "blines", desc = "blines", prefix = "/" }, + { "buffers", desc = "Bufs", prefix = "$" }, + doc_sym_supported and { + "lsp_document_symbols", +@@ -591,10 +592,11 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + }, + } + end, +- fzf_opts = { ["--nth"] = false, ["--with-nth"] = false }, ++ fzf_opts = { ["--delimiter"] = "[\t]", ["--with-nth"] = ".." }, + winopts = { preview = { winopts = { cursorline = true } } }, + _ctx = { includeBuflist = true }, -- we include a buffer picker + _fzf_nth_devicons = false, ++ _treesitter = true, + }) + + +diff --git a/lua/fzf-lua/providers/meta.lua b/lua/fzf-lua/providers/meta.lua +index 9419d27f..30f99fc4 100644 +--- a/lua/fzf-lua/providers/meta.lua ++++ b/lua/fzf-lua/providers/meta.lua +@@ -190,6 +190,13 @@ M.global = function(opts) + or opts_copy) + pickers[name] = def + end ++ -- HACK: inherit fzf_opts from the normalized picker opts so we have ++ -- with-nth for the transform (e.g. for blines) ++ -- TODO: we can probably inerit all opts but I'm not sure what would be ++ -- the effects of that, this entire picker needs refactoring ++ local picker_opts = config.normalize_opts(t.opts, name:gsub("^lsp_", "lsp.")) ++ if not utils.map_get(def, "opts.fzf_opts") then utils.map_set(def, "opts.fzf_opts", {}) end ++ def.opts.fzf_opts = vim.tbl_deep_extend("force", def.opts.fzf_opts, picker_opts.fzf_opts) + -- Instantiate the previewer, opts isn't guaranteed if the picker + -- isn't avilable, e.g. `tags` when not tags file exists + if def.opts and def.opts.previewer then +@@ -249,6 +256,14 @@ M.global = function(opts) + win:redraw_preview() + end + reload = string.format("reload(%s)+", new_picker.contents) ++ -- fzf >= 0.69 supports `change-with-nth` to dynamically change `--with-nth` ++ -- dynamically update `--with-nth` per-picker (fzf >= 0.69) ++ -- e.g. blines uses `--with-nth=4..` to hide buffer numbers ++ if utils.has(opts, "fzf", { 0, 69 }) then ++ -- `false|nil` defaults to all fields (..) ++ local with_nth = utils.map_get(new_picker, "opts.fzf_opts.--with-nth") ++ reload = reload .. string.format("change-with-nth(%s)+", with_nth or "..") ++ end + cur_sub = new_sub + cur_picker = new_picker + end diff --git a/tasks/ibhagwan__fzf-lua-2593/tests/test.sh b/tasks/ibhagwan__fzf-lua-2593/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd9a9544572231cceceea2023c6c2d69b834779f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 531092c73d8a09d98113bd84ae3e12121af0fdbd > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2593/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2593/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2593/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2594/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2594/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..37b97fa70825273bbfba3810e75e9f406a23f9b8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2847700c65b542d7686806cfee6b5fc2acb7b65d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2847700c65b542d7686806cfee6b5fc2acb7b65d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2847700c65b542d7686806cfee6b5fc2acb7b65d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2594/instruction.md b/tasks/ibhagwan__fzf-lua-2594/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7094f50645b3dec9643abba30c0df4b43c0dc40 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(global): convert other nest config + +## Description + +`FzfLua global` error on cli +``` +~ master ❯ E5113: Lua chunk: lua/fzf-lua/config.lua:193: attempt to index local 'picker_opts' (a nil value) +stack traceback: + lua/fzf-lua/config.lua:193: in function + lua/fzf-lua/config.lua:195: in function 'normalize_opts' + lua/fzf-lua/providers/meta.lua:197: in function + lua/fzf-lua/cmd.lua:38: in function 'run_command' + scripts/cli.lua:66: in main chunk +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2847700c65b5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2594/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2594/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7fb8c8b6bc71ef8dd3a2c978c89d474541c78d30 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/providers/meta.lua b/lua/fzf-lua/providers/meta.lua +index 30f99fc4..6dcd7155 100644 +--- a/lua/fzf-lua/providers/meta.lua ++++ b/lua/fzf-lua/providers/meta.lua +@@ -194,7 +194,8 @@ M.global = function(opts) + -- with-nth for the transform (e.g. for blines) + -- TODO: we can probably inerit all opts but I'm not sure what would be + -- the effects of that, this entire picker needs refactoring +- local picker_opts = config.normalize_opts(t.opts, name:gsub("^lsp_", "lsp.")) ++ local picker_opts = config.normalize_opts(t.opts, ++ name:gsub("^lsp_", "lsp."):gsub("^git_", "git."):gsub("^dap_", "dap.")) + if not utils.map_get(def, "opts.fzf_opts") then utils.map_set(def, "opts.fzf_opts", {}) end + def.opts.fzf_opts = vim.tbl_deep_extend("force", def.opts.fzf_opts, picker_opts.fzf_opts) + -- Instantiate the previewer, opts isn't guaranteed if the picker diff --git a/tasks/ibhagwan__fzf-lua-2594/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2594/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2594/task.toml b/tasks/ibhagwan__fzf-lua-2594/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..329876dcd98f5d21e753469d97dad123ddf47f23 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2594" +description = "fix(global): convert other nest config" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "2847700c65b542d7686806cfee6b5fc2acb7b65d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2594" +source_access = "auto" +built_at = "2026-11-16T16:09:56.033163+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6fef3cfc8837a8240e64a09a6ed77133569f6f3325ae92cc0994f92083e3d446" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-02T01:53:42Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/meta.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.028798+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:cc8e291579aba9d6ae75f9cc0ddf5952cf83a620ae4d7907693302d3d7665c84" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2594/tests/capture.py b/tasks/ibhagwan__fzf-lua-2594/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2594/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2594/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7094f50645b3dec9643abba30c0df4b43c0dc40 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(global): convert other nest config + +## Description + +`FzfLua global` error on cli +``` +~ master ❯ E5113: Lua chunk: lua/fzf-lua/config.lua:193: attempt to index local 'picker_opts' (a nil value) +stack traceback: + lua/fzf-lua/config.lua:193: in function + lua/fzf-lua/config.lua:195: in function 'normalize_opts' + lua/fzf-lua/providers/meta.lua:197: in function + lua/fzf-lua/cmd.lua:38: in function 'run_command' + scripts/cli.lua:66: in main chunk +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2847700c65b5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2594/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2594/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7fb8c8b6bc71ef8dd3a2c978c89d474541c78d30 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/providers/meta.lua b/lua/fzf-lua/providers/meta.lua +index 30f99fc4..6dcd7155 100644 +--- a/lua/fzf-lua/providers/meta.lua ++++ b/lua/fzf-lua/providers/meta.lua +@@ -194,7 +194,8 @@ M.global = function(opts) + -- with-nth for the transform (e.g. for blines) + -- TODO: we can probably inerit all opts but I'm not sure what would be + -- the effects of that, this entire picker needs refactoring +- local picker_opts = config.normalize_opts(t.opts, name:gsub("^lsp_", "lsp.")) ++ local picker_opts = config.normalize_opts(t.opts, ++ name:gsub("^lsp_", "lsp."):gsub("^git_", "git."):gsub("^dap_", "dap.")) + if not utils.map_get(def, "opts.fzf_opts") then utils.map_set(def, "opts.fzf_opts", {}) end + def.opts.fzf_opts = vim.tbl_deep_extend("force", def.opts.fzf_opts, picker_opts.fzf_opts) + -- Instantiate the previewer, opts isn't guaranteed if the picker diff --git a/tasks/ibhagwan__fzf-lua-2594/tests/test.sh b/tasks/ibhagwan__fzf-lua-2594/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c64dd7be678779796fc83c52761508c9fa8aa49f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2847700c65b542d7686806cfee6b5fc2acb7b65d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2594/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2594/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2594/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2599/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2599/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76b9156659dce2c8b6dfc7c1515b21508008449a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b56cd2ffbce57bfd9133a645bd02cd86895a7e3f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b56cd2ffbce57bfd9133a645bd02cd86895a7e3f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b56cd2ffbce57bfd9133a645bd02cd86895a7e3f \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2599/instruction.md b/tasks/ibhagwan__fzf-lua-2599/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36b3a2ce23873af26188e225e51df0a416cc6e11 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(win): abort when winobj is closing with sigwinch at the same time + +## Description + +Maybe fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b56cd2ffbce5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2599/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2599/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4262526187acc4e4f66e3512de61eeba6239e81b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 4750a6f7..769043e5 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -384,7 +384,7 @@ M.fzf = function(contents, opts) + if not tonumber(args[1]) then return end + -- NOTE: do not use local ref `fzf_win` as it my change on resume (#2255) + local winobj = utils.fzf_winobj() +- if not winobj then return end ++ if not winobj or winobj.closing then return end + return string.format("change-preview-window(%s)", winobj:normalize_preview_layout().str) + end) + end +diff --git a/lua/fzf-lua/fzf.lua b/lua/fzf-lua/fzf.lua +index 6468acef..43dc2819 100644 +--- a/lua/fzf-lua/fzf.lua ++++ b/lua/fzf-lua/fzf.lua +@@ -179,11 +179,11 @@ function M.raw_fzf(contents, fzf_cli_args, opts) + + -- fzf-tmux spawns outside neovim, don't set filetype/insert mode + if not opts.is_fzf_tmux then +- vim.bo.filetype = "fzf" +- + local fzfwin = utils.fzf_winobj() + if fzfwin then fzfwin:update_statusline() end + ++ vim.bo.filetype = "fzf" ++ + -- See note in "ModeChanged" above + -- NOTE: feedkeys hack not required since + -- https://github.com/neovim/neovim/commit/3621af9b970c80d2a6ff36569d7495391599c334 diff --git a/tasks/ibhagwan__fzf-lua-2599/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2599/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2599/task.toml b/tasks/ibhagwan__fzf-lua-2599/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f3c15cf55a408fac81b40d423c45259587e19ca0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2599" +description = "fix(win): abort when winobj is closing with sigwinch at the same time" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b56cd2ffbce57bfd9133a645bd02cd86895a7e3f" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2599" +source_access = "auto" +built_at = "2026-11-16T16:09:56.034578+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ca883737ff4f992bdaee8523560b97706f5688bb87d097f9047c8ca160a6cd40" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-04T11:54:57Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/core.lua", + "lua/fzf-lua/fzf.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.029314+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6a2ced9dfa7eb52879fc8c0b636c9f60230bd23d1a5295ca7f1ca252f97c187" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2599/tests/capture.py b/tasks/ibhagwan__fzf-lua-2599/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2599/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2599/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36b3a2ce23873af26188e225e51df0a416cc6e11 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(win): abort when winobj is closing with sigwinch at the same time + +## Description + +Maybe fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b56cd2ffbce5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2599/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2599/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4262526187acc4e4f66e3512de61eeba6239e81b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 4750a6f7..769043e5 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -384,7 +384,7 @@ M.fzf = function(contents, opts) + if not tonumber(args[1]) then return end + -- NOTE: do not use local ref `fzf_win` as it my change on resume (#2255) + local winobj = utils.fzf_winobj() +- if not winobj then return end ++ if not winobj or winobj.closing then return end + return string.format("change-preview-window(%s)", winobj:normalize_preview_layout().str) + end) + end +diff --git a/lua/fzf-lua/fzf.lua b/lua/fzf-lua/fzf.lua +index 6468acef..43dc2819 100644 +--- a/lua/fzf-lua/fzf.lua ++++ b/lua/fzf-lua/fzf.lua +@@ -179,11 +179,11 @@ function M.raw_fzf(contents, fzf_cli_args, opts) + + -- fzf-tmux spawns outside neovim, don't set filetype/insert mode + if not opts.is_fzf_tmux then +- vim.bo.filetype = "fzf" +- + local fzfwin = utils.fzf_winobj() + if fzfwin then fzfwin:update_statusline() end + ++ vim.bo.filetype = "fzf" ++ + -- See note in "ModeChanged" above + -- NOTE: feedkeys hack not required since + -- https://github.com/neovim/neovim/commit/3621af9b970c80d2a6ff36569d7495391599c334 diff --git a/tasks/ibhagwan__fzf-lua-2599/tests/test.sh b/tasks/ibhagwan__fzf-lua-2599/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..befad4ec16126f1eda0ee847c38a800ae906a799 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b56cd2ffbce57bfd9133a645bd02cd86895a7e3f > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2599/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2599/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2599/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2600/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2600/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76b9156659dce2c8b6dfc7c1515b21508008449a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b56cd2ffbce57bfd9133a645bd02cd86895a7e3f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b56cd2ffbce57bfd9133a645bd02cd86895a7e3f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b56cd2ffbce57bfd9133a645bd02cd86895a7e3f \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2600/instruction.md b/tasks/ibhagwan__fzf-lua-2600/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e004beeb3ddbf190cdb84c441c25fa705d1e3fb7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** feat(cli): nvim bin/runtime from custom path + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b56cd2ffbce5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2600/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2600/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a78a645fa7c0313c232be5d9b0cf2d0825c1bd05 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index c7142dfe..9e615ec5 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -1,3 +1,7 @@ ++local NVIM_BIN = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath ++local NVIM_RUNTIME = os.getenv("FZF_LUA_NVIM_RUNTIME") or os.getenv("VIMRUNTIME") ++if NVIM_RUNTIME then vim.env.VIMRUNTIME = NVIM_RUNTIME end ++ + ---@diagnostic disable-next-line: deprecated + local api, uv, fn = vim.api, vim.uv or vim.loop, vim.fn + ---@module 'ffi'? +@@ -124,7 +128,7 @@ return { + if ffi and #entries == 1 then + local lnum = entries[1].line > 0 and entries[1].line or nil + local col = entries[1].col > 0 and entries[1].col or nil +- posix_exec(fn.exepath("nvim"), entries[1].path, ++ posix_exec(NVIM_BIN, entries[1].path, + lnum and ("+" .. entries[1].line) or nil, + col and ("+norm! %s|"):format(col) or nil) + elseif ffi and #entries > 1 then +@@ -140,7 +144,7 @@ return { + }) + end + local qf_str = vim.inspect(qf_items):gsub("\n%s*", " ") +- posix_exec(fn.exepath("nvim"), "-c", string.format( ++ posix_exec(NVIM_BIN, "-c", string.format( + "lua vim.o.hidden=false; vim.fn.setqflist(%s); vim.cmd('cfirst | set hidden&')", + qf_str)) + end +@@ -173,7 +177,7 @@ return { + vim.uv.kill(pid, vim.uv.constants.SIGTERM) + end + enable_stdio_inheritance() +- posix_exec(fn.exepath("nvim"), "--remote-ui", "--server", remote) ++ posix_exec(NVIM_BIN, "--remote-ui", "--server", remote) + end + } + } diff --git a/tasks/ibhagwan__fzf-lua-2600/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2600/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2600/task.toml b/tasks/ibhagwan__fzf-lua-2600/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..769b0e27aebcd784c9cb3af690a54db8443c24f3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2600" +description = "feat(cli): nvim bin/runtime from custom path" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b56cd2ffbce57bfd9133a645bd02cd86895a7e3f" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2600" +source_access = "auto" +built_at = "2026-11-16T16:09:56.053470+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b67a121546344203949de840e4b61a7fd7d84625418db0083c48e1750780c5fb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-03T14:38:01Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/profiles/cli.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[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:01.029881+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6a2ced9dfa7eb52879fc8c0b636c9f60230bd23d1a5295ca7f1ca252f97c187" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2600/tests/capture.py b/tasks/ibhagwan__fzf-lua-2600/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2600/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2600/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e004beeb3ddbf190cdb84c441c25fa705d1e3fb7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** feat(cli): nvim bin/runtime from custom path + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b56cd2ffbce5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2600/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2600/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a78a645fa7c0313c232be5d9b0cf2d0825c1bd05 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index c7142dfe..9e615ec5 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -1,3 +1,7 @@ ++local NVIM_BIN = os.getenv("FZF_LUA_NVIM_BIN") or vim.v.progpath ++local NVIM_RUNTIME = os.getenv("FZF_LUA_NVIM_RUNTIME") or os.getenv("VIMRUNTIME") ++if NVIM_RUNTIME then vim.env.VIMRUNTIME = NVIM_RUNTIME end ++ + ---@diagnostic disable-next-line: deprecated + local api, uv, fn = vim.api, vim.uv or vim.loop, vim.fn + ---@module 'ffi'? +@@ -124,7 +128,7 @@ return { + if ffi and #entries == 1 then + local lnum = entries[1].line > 0 and entries[1].line or nil + local col = entries[1].col > 0 and entries[1].col or nil +- posix_exec(fn.exepath("nvim"), entries[1].path, ++ posix_exec(NVIM_BIN, entries[1].path, + lnum and ("+" .. entries[1].line) or nil, + col and ("+norm! %s|"):format(col) or nil) + elseif ffi and #entries > 1 then +@@ -140,7 +144,7 @@ return { + }) + end + local qf_str = vim.inspect(qf_items):gsub("\n%s*", " ") +- posix_exec(fn.exepath("nvim"), "-c", string.format( ++ posix_exec(NVIM_BIN, "-c", string.format( + "lua vim.o.hidden=false; vim.fn.setqflist(%s); vim.cmd('cfirst | set hidden&')", + qf_str)) + end +@@ -173,7 +177,7 @@ return { + vim.uv.kill(pid, vim.uv.constants.SIGTERM) + end + enable_stdio_inheritance() +- posix_exec(fn.exepath("nvim"), "--remote-ui", "--server", remote) ++ posix_exec(NVIM_BIN, "--remote-ui", "--server", remote) + end + } + } diff --git a/tasks/ibhagwan__fzf-lua-2600/tests/test.sh b/tasks/ibhagwan__fzf-lua-2600/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..befad4ec16126f1eda0ee847c38a800ae906a799 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b56cd2ffbce57bfd9133a645bd02cd86895a7e3f > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2600/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2600/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2600/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2602/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2602/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afeabb002445d9e6e968581f0bd4efee7e582478 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1eba927866251bae1b61dffc5b673b8dbd0f3f48 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1eba927866251bae1b61dffc5b673b8dbd0f3f48 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1eba927866251bae1b61dffc5b673b8dbd0f3f48 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2602/instruction.md b/tasks/ibhagwan__fzf-lua-2602/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc38ca0f1c312cf1419e6645c659a8e35f69c068 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(previewer): always call base:close + +## Description + +@phanen, any comments? + +Regression from recent refactor `swiper.base:close()` was never called, not clearing the highlights/restoring cursor position. + +I believe this is the right way to fix it post refactor but any comments are welcome. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eba92786625`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2602/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2602/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..71098935cc21e6b3e33b1d4b5ddfd447f5c542fa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index b57dec03..729890fd 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -780,8 +780,12 @@ function FzfWin:attach_previewer(previewer) + if not self._previewer.preview_bufnr and self:validate_preview() then + self._previewer.preview_bufnr = api.nvim_win_get_buf(self.preview_winid) + end +- self:close_preview() ++ if self.on_closes.preview then self.on_closes.preview() end + end ++ -- This makes sure previewer.base:close is always called on :close ++ -- (1) Used by swiper/ivy/custom previewers ++ -- (2) Overwritten (extended) in builtin previewer (in :redraw_preview) ++ self.on_closes.preview = function(hide) self:close_preview(hide) end + self._previewer = previewer + self.previewer_is_builtin = previewer and previewer.type == "builtin" + self.toggle_behavior = previewer and previewer.toggle_behavior or self.toggle_behavior diff --git a/tasks/ibhagwan__fzf-lua-2602/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2602/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2602/task.toml b/tasks/ibhagwan__fzf-lua-2602/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c2390841d356a05e1a0886b6214c63b5a61aeb3f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2602" +description = "fix(previewer): always call base:close" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "1eba927866251bae1b61dffc5b673b8dbd0f3f48" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2602" +source_access = "auto" +built_at = "2026-11-16T16:09:56.052126+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:054ad159eefd8cac385569e5403472306f2f215c084943218f78b3fc4cda099c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-08T02:02:13Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.030378+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:60955bab4b7dbaa2a81fcb1a107cd8002375523d39022b16f2eb243827f8664e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2602/tests/capture.py b/tasks/ibhagwan__fzf-lua-2602/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2602/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2602/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc38ca0f1c312cf1419e6645c659a8e35f69c068 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(previewer): always call base:close + +## Description + +@phanen, any comments? + +Regression from recent refactor `swiper.base:close()` was never called, not clearing the highlights/restoring cursor position. + +I believe this is the right way to fix it post refactor but any comments are welcome. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eba92786625`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2602/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2602/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..71098935cc21e6b3e33b1d4b5ddfd447f5c542fa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index b57dec03..729890fd 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -780,8 +780,12 @@ function FzfWin:attach_previewer(previewer) + if not self._previewer.preview_bufnr and self:validate_preview() then + self._previewer.preview_bufnr = api.nvim_win_get_buf(self.preview_winid) + end +- self:close_preview() ++ if self.on_closes.preview then self.on_closes.preview() end + end ++ -- This makes sure previewer.base:close is always called on :close ++ -- (1) Used by swiper/ivy/custom previewers ++ -- (2) Overwritten (extended) in builtin previewer (in :redraw_preview) ++ self.on_closes.preview = function(hide) self:close_preview(hide) end + self._previewer = previewer + self.previewer_is_builtin = previewer and previewer.type == "builtin" + self.toggle_behavior = previewer and previewer.toggle_behavior or self.toggle_behavior diff --git a/tasks/ibhagwan__fzf-lua-2602/tests/test.sh b/tasks/ibhagwan__fzf-lua-2602/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..35db64a392e02bbd150f83375d0802fe7ee82564 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1eba927866251bae1b61dffc5b673b8dbd0f3f48 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2602/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2602/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2602/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2605/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2605/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afeabb002445d9e6e968581f0bd4efee7e582478 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1eba927866251bae1b61dffc5b673b8dbd0f3f48 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1eba927866251bae1b61dffc5b673b8dbd0f3f48 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1eba927866251bae1b61dffc5b673b8dbd0f3f48 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2605/instruction.md b/tasks/ibhagwan__fzf-lua-2605/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15bf71902505ab07bf562a336078e478ed42796e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(win): relative=cursor layout + +## Description + +Fix https://github.com/ibhagwan/fzf-lua/discussions/2603 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eba92786625`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2605/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2605/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0a20ff76dc1d12e16eeae815280039dd1d5c8bdf --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/solution/patch.diff @@ -0,0 +1,132 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index b57dec03..8a6e4471 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -612,13 +612,12 @@ function FzfWin:normalize_winopts() + winopts.row = math.floor((winopts.row or 0) + screenpos.row - 1) + winopts.col = math.floor((winopts.col or 0) + screenpos.col - 1) + winopts.relative = nil +- else +- -- make row close to the center of screen (include cmdheight) +- -- avoid breaking existing test +- winopts.row = self:normalize_size(assert(tonumber(winopts.row)), vim.o.lines - winopts.height) +- winopts.col = self:normalize_size(assert(tonumber(winopts.col)), max_width - winopts.width) +- winopts.row = math.min(winopts.row, max_height - winopts.height) + end ++ -- make row close to the center of screen (include cmdheight) ++ -- avoid breaking existing test ++ winopts.row = self:normalize_size(assert(tonumber(winopts.row)), vim.o.lines - winopts.height) ++ winopts.col = self:normalize_size(assert(tonumber(winopts.col)), max_width - winopts.width) ++ winopts.row = math.min(winopts.row, max_height - winopts.height) + -- width/height can be used for text area + winopts.width = math.max(1, winopts.width - w) + winopts.height = math.max(1, winopts.height - h) +diff --git a/tests/screenshots/tests-win_spec.lua---win---relative=cursor b/tests/screenshots/tests-win_spec.lua---win---relative=cursor +new file mode 100644 +index 00000000..f1947356 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---relative=cursor +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|╭──────────foo──────────╮╭────────────────────────╮ ++02|│ 1 SELECTED FILE: foo ││> 3/3 │ ++03|│ ││─────────────────────── │ ++04|│ ││▌ foo │ ++05|│ ││ bar │ ++06|│ ││ baz │ ++07|│ ││ │ ++08|│ ││ │ ++09|│ ││ │ ++10|│ ││ │ ++11|│ ││ │ ++12|│ ││ │ ++13|│ ││ │ ++14|│ ││ │ ++15|│ ││ │ ++16|│ ││ │ ++17|│ ││ │ ++18|│ ││ │ ++19|│ ││ │ ++20|╰───────────────────────╯╰────────────────────────╯ ++21|~ ++22|~ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All +diff --git a/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 b/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 +new file mode 100644 +index 00000000..800c9a32 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|aaaaaaaaaaaaa╭──────────foo──────────╮╭────────────────────────╮ ++02|~ │ 1 SELECTED FILE: foo ││> 3/3 │ ++03|~ │ ││─────────────────────── │ ++04|~ │ ││▌ foo │ ++05|~ │ ││ bar │ ++06|~ │ ││ baz │ ++07|~ │ ││ │ ++08|~ │ ││ │ ++09|~ │ ││ │ ++10|~ │ ││ │ ++11|~ │ ││ │ ++12|~ │ ││ │ ++13|~ │ ││ │ ++14|~ │ ││ │ ++15|~ │ ││ │ ++16|~ │ ││ │ ++17|~ │ ││ │ ++18|~ │ ││ │ ++19|~ │ ││ │ ++20|~ ╰───────────────────────╯╰────────────────────────╯ ++21|~ ++22|~ ++23|~ ++24|[No Name] [+] 1,64 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All +diff --git a/tests/win_spec.lua b/tests/win_spec.lua +index 3c3618e0..1a8c23b3 100644 +--- a/tests/win_spec.lua ++++ b/tests/win_spec.lua +@@ -310,6 +310,34 @@ T["win"]["toggle"][""] = new_set( + end + }) + ++T["win"]["relative=cursor"] = function() ++ -- Ignore terminal command line with process number ++ local screen_opts = { ignore_text = { 24, 28 }, normalize_paths = helpers.IS_WIN() } ++ local opts = { ++ __expect_lines = true, ++ __screen_opts = screen_opts, ++ winopts = { ++ relative = "cursor", ++ preview = { layout = "horizontal", horizontal = "left:50%" } ++ }, ++ previewer = function() return require("fzf-lua.test.previewer").builtin end, ++ __after_open = function() ++ child.wait_until(function() return child.lua_get([[_G._fzf_load_called]]) == true end) ++ if helpers.IS_WIN() then vim.uv.sleep(250) end ++ end, ++ } ++ helpers.FzfLua.fzf_exec(child, { "foo", "bar", "baz" }, opts) ++ child.cmd([[enew]]) ++ set_lines({ ("a"):rep(child.o.columns) }) ++ type_keys("g$") ++ -- pretend we closed the window to make helpers won't wait for new open ++ exec_lua([[_G._fzf_lua_on_create = nil]]) ++ exec_lua([[_G._fzf_load_called = nil]]) ++ helpers.FzfLua.fzf_exec(child, { "foo", "bar", "baz" }, opts) ++ child.cmd([[bwipe!]]) ++end ++ ++ + T["win"]["reuse"] = new_set({ + parametrize = { + { {} }, diff --git a/tasks/ibhagwan__fzf-lua-2605/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2605/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2605/task.toml b/tasks/ibhagwan__fzf-lua-2605/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f819b8d71af885853896d2d3ea3061f8e5d6683e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2605" +description = "fix(win): relative=cursor layout" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "1eba927866251bae1b61dffc5b673b8dbd0f3f48" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2605" +source_access = "auto" +built_at = "2026-11-16T16:09:56.036042+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9a3463262f8b85ff3c1dcad71e303c943b8125fbe950224a38f0367d856c2df8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-08T02:42:19Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", + "tests/screenshots/tests-win_spec.lua---win---relative=cursor", + "tests/screenshots/tests-win_spec.lua---win---relative=cursor-002", + "tests/win_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 97 +difficulty = "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:01.030888+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:60955bab4b7dbaa2a81fcb1a107cd8002375523d39022b16f2eb243827f8664e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2605/tests/capture.py b/tasks/ibhagwan__fzf-lua-2605/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2605/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2605/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15bf71902505ab07bf562a336078e478ed42796e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(win): relative=cursor layout + +## Description + +Fix https://github.com/ibhagwan/fzf-lua/discussions/2603 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eba92786625`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2605/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2605/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0a20ff76dc1d12e16eeae815280039dd1d5c8bdf --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/tests/oracle.patch @@ -0,0 +1,132 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index b57dec03..8a6e4471 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -612,13 +612,12 @@ function FzfWin:normalize_winopts() + winopts.row = math.floor((winopts.row or 0) + screenpos.row - 1) + winopts.col = math.floor((winopts.col or 0) + screenpos.col - 1) + winopts.relative = nil +- else +- -- make row close to the center of screen (include cmdheight) +- -- avoid breaking existing test +- winopts.row = self:normalize_size(assert(tonumber(winopts.row)), vim.o.lines - winopts.height) +- winopts.col = self:normalize_size(assert(tonumber(winopts.col)), max_width - winopts.width) +- winopts.row = math.min(winopts.row, max_height - winopts.height) + end ++ -- make row close to the center of screen (include cmdheight) ++ -- avoid breaking existing test ++ winopts.row = self:normalize_size(assert(tonumber(winopts.row)), vim.o.lines - winopts.height) ++ winopts.col = self:normalize_size(assert(tonumber(winopts.col)), max_width - winopts.width) ++ winopts.row = math.min(winopts.row, max_height - winopts.height) + -- width/height can be used for text area + winopts.width = math.max(1, winopts.width - w) + winopts.height = math.max(1, winopts.height - h) +diff --git a/tests/screenshots/tests-win_spec.lua---win---relative=cursor b/tests/screenshots/tests-win_spec.lua---win---relative=cursor +new file mode 100644 +index 00000000..f1947356 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---relative=cursor +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|╭──────────foo──────────╮╭────────────────────────╮ ++02|│ 1 SELECTED FILE: foo ││> 3/3 │ ++03|│ ││─────────────────────── │ ++04|│ ││▌ foo │ ++05|│ ││ bar │ ++06|│ ││ baz │ ++07|│ ││ │ ++08|│ ││ │ ++09|│ ││ │ ++10|│ ││ │ ++11|│ ││ │ ++12|│ ││ │ ++13|│ ││ │ ++14|│ ││ │ ++15|│ ││ │ ++16|│ ││ │ ++17|│ ││ │ ++18|│ ││ │ ++19|│ ││ │ ++20|╰───────────────────────╯╰────────────────────────╯ ++21|~ ++22|~ ++23|~ ++24|[No Name] 0,0-1 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All +diff --git a/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 b/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 +new file mode 100644 +index 00000000..800c9a32 +--- /dev/null ++++ b/tests/screenshots/tests-win_spec.lua---win---relative=cursor-002 +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|aaaaaaaaaaaaa╭──────────foo──────────╮╭────────────────────────╮ ++02|~ │ 1 SELECTED FILE: foo ││> 3/3 │ ++03|~ │ ││─────────────────────── │ ++04|~ │ ││▌ foo │ ++05|~ │ ││ bar │ ++06|~ │ ││ baz │ ++07|~ │ ││ │ ++08|~ │ ││ │ ++09|~ │ ││ │ ++10|~ │ ││ │ ++11|~ │ ││ │ ++12|~ │ ││ │ ++13|~ │ ││ │ ++14|~ │ ││ │ ++15|~ │ ││ │ ++16|~ │ ││ │ ++17|~ │ ││ │ ++18|~ │ ││ │ ++19|~ │ ││ │ ++20|~ ╰───────────────────────╯╰────────────────────────╯ ++21|~ ++22|~ ++23|~ ++24|[No Name] [+] 1,64 All ++25| ++26| ++27| ++28|-- TERMINAL -- 1,3 All +diff --git a/tests/win_spec.lua b/tests/win_spec.lua +index 3c3618e0..1a8c23b3 100644 +--- a/tests/win_spec.lua ++++ b/tests/win_spec.lua +@@ -310,6 +310,34 @@ T["win"]["toggle"][""] = new_set( + end + }) + ++T["win"]["relative=cursor"] = function() ++ -- Ignore terminal command line with process number ++ local screen_opts = { ignore_text = { 24, 28 }, normalize_paths = helpers.IS_WIN() } ++ local opts = { ++ __expect_lines = true, ++ __screen_opts = screen_opts, ++ winopts = { ++ relative = "cursor", ++ preview = { layout = "horizontal", horizontal = "left:50%" } ++ }, ++ previewer = function() return require("fzf-lua.test.previewer").builtin end, ++ __after_open = function() ++ child.wait_until(function() return child.lua_get([[_G._fzf_load_called]]) == true end) ++ if helpers.IS_WIN() then vim.uv.sleep(250) end ++ end, ++ } ++ helpers.FzfLua.fzf_exec(child, { "foo", "bar", "baz" }, opts) ++ child.cmd([[enew]]) ++ set_lines({ ("a"):rep(child.o.columns) }) ++ type_keys("g$") ++ -- pretend we closed the window to make helpers won't wait for new open ++ exec_lua([[_G._fzf_lua_on_create = nil]]) ++ exec_lua([[_G._fzf_load_called = nil]]) ++ helpers.FzfLua.fzf_exec(child, { "foo", "bar", "baz" }, opts) ++ child.cmd([[bwipe!]]) ++end ++ ++ + T["win"]["reuse"] = new_set({ + parametrize = { + { {} }, diff --git a/tasks/ibhagwan__fzf-lua-2605/tests/test.sh b/tasks/ibhagwan__fzf-lua-2605/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..35db64a392e02bbd150f83375d0802fe7ee82564 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1eba927866251bae1b61dffc5b673b8dbd0f3f48 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2605/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2605/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2605/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2617/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2617/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ded2065132ad2a8d7edb01413e81ed7b57dd4cf3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 30ba09afbc0eac5fc5ec8823418d1e45d0712b9f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 30ba09afbc0eac5fc5ec8823418d1e45d0712b9f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 30ba09afbc0eac5fc5ec8823418d1e45d0712b9f \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2617/instruction.md b/tasks/ibhagwan__fzf-lua-2617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbda10236e64b959c5fbdbb99eaee5d985191d85 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(git_diff): logic to match git diff command + +## Description + +fix #2615 + + +## Summary by CodeRabbit + +* **Improvements** + * More flexible diff references: multi-value refs and explicit base ref support, with validation and smarter defaults. + * Diff previews and commands updated to use the new reference behavior. + * File lists and headers now include an "actions" column and display ref/ref1 when present. + * Added parameter/return annotations for a git-path helper. + +* **New Features** + * Search in stash browsing. + * New shortcuts: Ctrl-Q opens commit view; Ctrl-D runs a diff against the previous commit. + +* **Documentation** + * Notes updated to reflect renamed/expanded reference fields. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `30ba09afbc0e`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2617/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2617/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eb6f1a907dd3a4c190d25769c37f8d1e867080ed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/solution/patch.diff @@ -0,0 +1,213 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 769043e5..055eea5d 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -836,6 +836,22 @@ M.set_header = function(opts) + return opts.search and #opts.search > 0 and opts.search + end, + }, ++ ref = { ++ hdr_txt_opt = "ref_header_txt", ++ hdr_txt_str = "ref: ", ++ hdr_txt_col = opts.hls.header_text, ++ val = function() ++ return opts.ref and #opts.ref > 0 and opts.ref ++ end, ++ }, ++ ref1 = { ++ hdr_txt_opt = "ref1_header_txt", ++ hdr_txt_str = "ref1: ", ++ hdr_txt_col = opts.hls.header_text, ++ val = function() ++ return opts.ref1 and #opts.ref1 > 0 and opts.ref1 ++ end, ++ }, + lsp_query = { + hdr_txt_opt = "lsp_query_header_txt", + hdr_txt_str = "Query: ", +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 8e6d73f6..e9e0c19a 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -666,15 +666,16 @@ M.defaults.git = { + }, + ---Git diff (changed files vs a git ref). + ---@class fzf-lua.config.GitDiff: fzf-lua.config.GitBase +- ---Git reference to compare against. +- ---@field ref? string ++ ---Git reference(s) to compare against. ++ ---@field ref? string|string[] + ---Git reference used as the base for the comparison. +- ---@field compare_against? string ++ -- `compare_against` was renamed to `ref1` ++ ---@field ref1? string + diff = { +- cmd = "git --no-pager diff --name-only {compare_against} {ref}", +- ref = "HEAD", +- compare_against = "", +- preview = "git diff {compare_against} {ref} {file}", ++ cmd = "git --no-pager diff --name-only {ref1} {ref}", ++ ref = nil, ++ ref1 = nil, ++ preview = "git diff {ref1} {ref} {file}", + preview_pager = M._preview_pager_fn, + multiprocess = 1, ---@type integer|boolean + _type = "file", +@@ -683,7 +684,14 @@ M.defaults.git = { + fzf_opts = { ["--multi"] = true }, + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, +- _headers = { "cwd" }, ++ _headers = { "cwd", "actions" }, ++ actions = { ++ ["ctrl-q"] = { ++ fn = function() FzfLua.git_commits() end, ++ reuse = true, ++ header = "git commits" ++ }, ++ }, + }, + ---Git diff hunks (changed lines). + ---@class fzf-lua.config.GitHunks: fzf-lua.config.GitBase +@@ -717,6 +725,17 @@ M.defaults.git = { + actions = { + ["enter"] = actions.git_checkout, + ["ctrl-y"] = { fn = actions.git_yank_commit, exec_silent = true }, ++ ["ctrl-d"] = { ++ fn = function(s, _o) ++ if not s[1] then return FzfLua.utils.fzf_exit() end ++ local o = vim.deepcopy(_o.__call_opts) ++ o.ref = s[1]:match("[^ ]+") ++ o.ref1 = o.ref .. "~" ++ FzfLua.git_diff(o) ++ end, ++ reuse = true, ++ header = "git diff" ++ }, + }, + fzf_opts = { ["--no-multi"] = true }, + _headers = { "actions", "cwd" }, +@@ -816,6 +835,7 @@ M.defaults.git = { + }, + ---Git stashes. + ---@class fzf-lua.config.GitStash: fzf-lua.config.GitBase ++ ---@field search? string + stash = { + cmd = "git --no-pager stash list", + preview = "git --no-pager stash show --patch --color {1}", +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index ad02c405..0ec879c2 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -563,6 +563,9 @@ end + + ---@overload fun(cmd: string, opts: table): string + ---@overload fun(cmd: string[], opts: table): string[] ++---@param cmd string|string[] ++---@param opts table ++---@return string|string[] + function M.git_cwd(cmd, opts) + local git_args = { + { "cwd", "-C" }, +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 81823147..e541a55a 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -91,39 +91,61 @@ local function git_preview(opts, file) + return opts.preview + end + ++---@param opts fzf-lua.config.GitBase|{}? ++---@param ref string ++---@return boolean ++local git_validate_ref = function(opts, ref) ++ local cmd = path.git_cwd({ "git", "rev-parse", "--verify", ref }, opts --[[@as table]]) ++ local _, exit_code = utils.io_systemlist(cmd --[[@as string[] ]]) ++ if exit_code ~= 0 then ++ utils.warn("Invalid git ref %s", ref) ++ return false ++ end ++ return true ++end ++ + ---@param opts fzf-lua.config.GitDiff|{}? + ---@return thread?, string?, table? + M.diff = function(opts) + ---@type fzf-lua.config.GitDiff + opts = config.normalize_opts(opts, "git.diff") + if not opts then return end +- -- Ensure that ref is a commit hash in this git repository. +- local validation_ref = path.git_cwd({ "git", "rev-parse", "--verify", opts.ref }, opts) +- local _, exit_status_code_ref = utils.io_systemlist(validation_ref) +- if exit_status_code_ref ~= 0 then +- utils.warn("Invalid git ref %s", opts.ref) +- return ++ -- Backward compat `compare_against` -> `ref1` ++ ---@diagnostic disable-next-line: undefined-field ++ opts.ref1 = opts.compare_against or opts.ref1 ++ -- Convinience: ref as string array ++ if type(opts.ref) == "table" then ++ opts.ref, opts.ref1 = opts.ref[1], (opts.ref[2] or opts.ref1) + end +- -- If compare_against is given, ensure that it is a commit hash in this git repository. +- if type(opts.compare_against) == "string" and #opts.compare_against > 0 then +- local validation_comp = path.git_cwd({ "git", "rev-parse", "--verify", opts.compare_against }, +- opts) +- local _, exit_code_status_comp = utils.io_systemlist(validation_comp) +- if exit_code_status_comp ~= 0 then +- utils.warn("Invalid git ref %s", opts.compare_against) ++ -- Ensure supplied refs are valid in this git repository. ++ for _, r in ipairs({ "ref", "ref1" }) do ++ if type(opts[r]) == "string" and #opts[r] > 0 and not git_validate_ref(opts, opts[r]) then + return + end +- else +- -- Default to diffing against ref and its direct parent commit. +- opts.compare_against = opts.ref .. "^" + end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref) +- opts.cmd = opts.cmd:gsub("[<{]compare_against[}>]", opts.compare_against) +- opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref) +- opts.preview = opts.preview:gsub("[<{]compare_against[}>]", opts.compare_against) ++ -- If no ref was supplied default to last commit, otherwise compare against the index ++ if not opts.ref and not opts.ref1 then ++ local cmd = path.git_cwd( ++ { "git", "-c", "color.status=false", "--no-optional-locks", "status", "--porcelain=v1" }, ++ opts --[[@as table]]) ++ local out, exit_code = utils.io_systemlist(cmd --[[@as string[] ]]) ++ if exit_code == 0 and #out == 0 then ++ opts.ref = "HEAD^" ++ else ++ opts.ref = "HEAD" ++ end ++ end ++ opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.cmd = opts.cmd:gsub("[<{]ref1[}>]", opts.ref1 or "") ++ opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") + opts = set_git_cwd_args(opts) + if not opts.cwd then return end + opts.preview = git_preview(opts, "{-1}") ++ if type(opts._headers) == "table" then ++ table.insert(opts._headers, "ref") ++ table.insert(opts._headers, "ref1") ++ end + return core.fzf_exec(opts.cmd, opts) + end + +@@ -301,13 +323,10 @@ M.hunks = function(opts) + ---@type fzf-lua.config.GitHunks + opts = config.normalize_opts(opts, "git.hunks") + if not opts then return end +- local cmd = path.git_cwd({ "git", "rev-parse", "--verify", opts.ref }, opts) +- local _, err = utils.io_systemlist(cmd) +- if err ~= 0 then +- utils.warn("Invalid git ref %s", opts.ref) ++ if type(opts.ref) == "string" and #opts.ref > 0 and not git_validate_ref(opts, opts.ref) then + return + end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref) ++ opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") + opts = set_git_cwd_args(opts) + if not opts.cwd then return end + diff --git a/tasks/ibhagwan__fzf-lua-2617/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2617/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2617/task.toml b/tasks/ibhagwan__fzf-lua-2617/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f03479fa43294633e38308dbe2706c38a41aa0d7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2617" +description = "fix(git_diff): logic to match git diff command" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "30ba09afbc0eac5fc5ec8823418d1e45d0712b9f" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2617" +source_access = "auto" +built_at = "2026-11-16T16:09:56.047259+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f309ebe57acac7a9d28d599eef45510d30cc9925e0e52b2f966adeb6c6f1419b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-14T02:16:27Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/core.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/path.lua", + "lua/fzf-lua/providers/git.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 124 +difficulty = "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:01.031439+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29465b3d5e624c540f97a61fc5cd293a6a98132adf6a404355b002e04cfbca7d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2617/tests/capture.py b/tasks/ibhagwan__fzf-lua-2617/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2617/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2617/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbda10236e64b959c5fbdbb99eaee5d985191d85 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(git_diff): logic to match git diff command + +## Description + +fix #2615 + + +## Summary by CodeRabbit + +* **Improvements** + * More flexible diff references: multi-value refs and explicit base ref support, with validation and smarter defaults. + * Diff previews and commands updated to use the new reference behavior. + * File lists and headers now include an "actions" column and display ref/ref1 when present. + * Added parameter/return annotations for a git-path helper. + +* **New Features** + * Search in stash browsing. + * New shortcuts: Ctrl-Q opens commit view; Ctrl-D runs a diff against the previous commit. + +* **Documentation** + * Notes updated to reflect renamed/expanded reference fields. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `30ba09afbc0e`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2617/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2617/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eb6f1a907dd3a4c190d25769c37f8d1e867080ed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/tests/oracle.patch @@ -0,0 +1,213 @@ +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 769043e5..055eea5d 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -836,6 +836,22 @@ M.set_header = function(opts) + return opts.search and #opts.search > 0 and opts.search + end, + }, ++ ref = { ++ hdr_txt_opt = "ref_header_txt", ++ hdr_txt_str = "ref: ", ++ hdr_txt_col = opts.hls.header_text, ++ val = function() ++ return opts.ref and #opts.ref > 0 and opts.ref ++ end, ++ }, ++ ref1 = { ++ hdr_txt_opt = "ref1_header_txt", ++ hdr_txt_str = "ref1: ", ++ hdr_txt_col = opts.hls.header_text, ++ val = function() ++ return opts.ref1 and #opts.ref1 > 0 and opts.ref1 ++ end, ++ }, + lsp_query = { + hdr_txt_opt = "lsp_query_header_txt", + hdr_txt_str = "Query: ", +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 8e6d73f6..e9e0c19a 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -666,15 +666,16 @@ M.defaults.git = { + }, + ---Git diff (changed files vs a git ref). + ---@class fzf-lua.config.GitDiff: fzf-lua.config.GitBase +- ---Git reference to compare against. +- ---@field ref? string ++ ---Git reference(s) to compare against. ++ ---@field ref? string|string[] + ---Git reference used as the base for the comparison. +- ---@field compare_against? string ++ -- `compare_against` was renamed to `ref1` ++ ---@field ref1? string + diff = { +- cmd = "git --no-pager diff --name-only {compare_against} {ref}", +- ref = "HEAD", +- compare_against = "", +- preview = "git diff {compare_against} {ref} {file}", ++ cmd = "git --no-pager diff --name-only {ref1} {ref}", ++ ref = nil, ++ ref1 = nil, ++ preview = "git diff {ref1} {ref} {file}", + preview_pager = M._preview_pager_fn, + multiprocess = 1, ---@type integer|boolean + _type = "file", +@@ -683,7 +684,14 @@ M.defaults.git = { + fzf_opts = { ["--multi"] = true }, + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, +- _headers = { "cwd" }, ++ _headers = { "cwd", "actions" }, ++ actions = { ++ ["ctrl-q"] = { ++ fn = function() FzfLua.git_commits() end, ++ reuse = true, ++ header = "git commits" ++ }, ++ }, + }, + ---Git diff hunks (changed lines). + ---@class fzf-lua.config.GitHunks: fzf-lua.config.GitBase +@@ -717,6 +725,17 @@ M.defaults.git = { + actions = { + ["enter"] = actions.git_checkout, + ["ctrl-y"] = { fn = actions.git_yank_commit, exec_silent = true }, ++ ["ctrl-d"] = { ++ fn = function(s, _o) ++ if not s[1] then return FzfLua.utils.fzf_exit() end ++ local o = vim.deepcopy(_o.__call_opts) ++ o.ref = s[1]:match("[^ ]+") ++ o.ref1 = o.ref .. "~" ++ FzfLua.git_diff(o) ++ end, ++ reuse = true, ++ header = "git diff" ++ }, + }, + fzf_opts = { ["--no-multi"] = true }, + _headers = { "actions", "cwd" }, +@@ -816,6 +835,7 @@ M.defaults.git = { + }, + ---Git stashes. + ---@class fzf-lua.config.GitStash: fzf-lua.config.GitBase ++ ---@field search? string + stash = { + cmd = "git --no-pager stash list", + preview = "git --no-pager stash show --patch --color {1}", +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index ad02c405..0ec879c2 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -563,6 +563,9 @@ end + + ---@overload fun(cmd: string, opts: table): string + ---@overload fun(cmd: string[], opts: table): string[] ++---@param cmd string|string[] ++---@param opts table ++---@return string|string[] + function M.git_cwd(cmd, opts) + local git_args = { + { "cwd", "-C" }, +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 81823147..e541a55a 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -91,39 +91,61 @@ local function git_preview(opts, file) + return opts.preview + end + ++---@param opts fzf-lua.config.GitBase|{}? ++---@param ref string ++---@return boolean ++local git_validate_ref = function(opts, ref) ++ local cmd = path.git_cwd({ "git", "rev-parse", "--verify", ref }, opts --[[@as table]]) ++ local _, exit_code = utils.io_systemlist(cmd --[[@as string[] ]]) ++ if exit_code ~= 0 then ++ utils.warn("Invalid git ref %s", ref) ++ return false ++ end ++ return true ++end ++ + ---@param opts fzf-lua.config.GitDiff|{}? + ---@return thread?, string?, table? + M.diff = function(opts) + ---@type fzf-lua.config.GitDiff + opts = config.normalize_opts(opts, "git.diff") + if not opts then return end +- -- Ensure that ref is a commit hash in this git repository. +- local validation_ref = path.git_cwd({ "git", "rev-parse", "--verify", opts.ref }, opts) +- local _, exit_status_code_ref = utils.io_systemlist(validation_ref) +- if exit_status_code_ref ~= 0 then +- utils.warn("Invalid git ref %s", opts.ref) +- return ++ -- Backward compat `compare_against` -> `ref1` ++ ---@diagnostic disable-next-line: undefined-field ++ opts.ref1 = opts.compare_against or opts.ref1 ++ -- Convinience: ref as string array ++ if type(opts.ref) == "table" then ++ opts.ref, opts.ref1 = opts.ref[1], (opts.ref[2] or opts.ref1) + end +- -- If compare_against is given, ensure that it is a commit hash in this git repository. +- if type(opts.compare_against) == "string" and #opts.compare_against > 0 then +- local validation_comp = path.git_cwd({ "git", "rev-parse", "--verify", opts.compare_against }, +- opts) +- local _, exit_code_status_comp = utils.io_systemlist(validation_comp) +- if exit_code_status_comp ~= 0 then +- utils.warn("Invalid git ref %s", opts.compare_against) ++ -- Ensure supplied refs are valid in this git repository. ++ for _, r in ipairs({ "ref", "ref1" }) do ++ if type(opts[r]) == "string" and #opts[r] > 0 and not git_validate_ref(opts, opts[r]) then + return + end +- else +- -- Default to diffing against ref and its direct parent commit. +- opts.compare_against = opts.ref .. "^" + end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref) +- opts.cmd = opts.cmd:gsub("[<{]compare_against[}>]", opts.compare_against) +- opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref) +- opts.preview = opts.preview:gsub("[<{]compare_against[}>]", opts.compare_against) ++ -- If no ref was supplied default to last commit, otherwise compare against the index ++ if not opts.ref and not opts.ref1 then ++ local cmd = path.git_cwd( ++ { "git", "-c", "color.status=false", "--no-optional-locks", "status", "--porcelain=v1" }, ++ opts --[[@as table]]) ++ local out, exit_code = utils.io_systemlist(cmd --[[@as string[] ]]) ++ if exit_code == 0 and #out == 0 then ++ opts.ref = "HEAD^" ++ else ++ opts.ref = "HEAD" ++ end ++ end ++ opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.cmd = opts.cmd:gsub("[<{]ref1[}>]", opts.ref1 or "") ++ opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") + opts = set_git_cwd_args(opts) + if not opts.cwd then return end + opts.preview = git_preview(opts, "{-1}") ++ if type(opts._headers) == "table" then ++ table.insert(opts._headers, "ref") ++ table.insert(opts._headers, "ref1") ++ end + return core.fzf_exec(opts.cmd, opts) + end + +@@ -301,13 +323,10 @@ M.hunks = function(opts) + ---@type fzf-lua.config.GitHunks + opts = config.normalize_opts(opts, "git.hunks") + if not opts then return end +- local cmd = path.git_cwd({ "git", "rev-parse", "--verify", opts.ref }, opts) +- local _, err = utils.io_systemlist(cmd) +- if err ~= 0 then +- utils.warn("Invalid git ref %s", opts.ref) ++ if type(opts.ref) == "string" and #opts.ref > 0 and not git_validate_ref(opts, opts.ref) then + return + end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref) ++ opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") + opts = set_git_cwd_args(opts) + if not opts.cwd then return end + diff --git a/tasks/ibhagwan__fzf-lua-2617/tests/test.sh b/tasks/ibhagwan__fzf-lua-2617/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56199f62f4cc6e710a1c141147e08bf1a4c2d4fc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 30ba09afbc0eac5fc5ec8823418d1e45d0712b9f > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2617/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2617/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2617/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2622/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2622/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..687d9ade8de142a06846c6bd3583dca34dad87ef --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6e41ba7505f35a6f054ca682b043aa0cea36c2ef 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6e41ba7505f35a6f054ca682b043aa0cea36c2ef \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6e41ba7505f35a6f054ca682b043aa0cea36c2ef \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2622/instruction.md b/tasks/ibhagwan__fzf-lua-2622/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1029ced4e00463fc730aa1cfb3185350a38802b6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feaT(git): binds for commits <-> diff <-> hunks + +## Description + +full diff lifecycle commtis -> diff -> hunks (and back) + + +## Summary by CodeRabbit + +* **New Features** + * File-specific diffs with multi-ref comparison and direct navigation between diffs, hunks, and commits. + * New key actions (Ctrl-D / Ctrl-Q) that jump into hunks/diffs/commits while preserving per-command cursor position. + +* **Bug Fixes & Improvements** + * Unified option normalization for diff/hunk flows and safer default refs. + * More reliable per-command positional tracking, improved locate/preview behavior, and stronger working-directory validation. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6e41ba7505f3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2622/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2622/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d0c9286c0aa26eaed1dda4d811f2cab42c26db93 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/solution/patch.diff @@ -0,0 +1,207 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index f27590ba..19cce6cd 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -983,6 +983,12 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + opts.fn_preprocess = [[return require("fzf-lua.make_entry").preprocess]] + end + ++ -- set by git_{commits|diff|hunks} actions ++ if opts["__pos_" .. utils.get_info().cmd] then ++ opts.locate = opts.locate == nil and true or opts.locate ++ opts.__locate_pos = opts.__locate_pos or opts["__pos_" .. utils.get_info().cmd] ++ end ++ + if opts.locate and utils.has(opts, "fzf", { 0, 36 }) then + table.insert(opts._fzf_cli_args, "--bind=" .. libuv.shellescape("load:+transform:" + .. FzfLua.shell.stringify_data(function(_, _, _) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 018061b8..a7c70148 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -668,11 +668,8 @@ M.defaults.git = { + ---@class fzf-lua.config.GitDiff: fzf-lua.config.GitBase + ---Git reference(s) to compare against. + ---@field ref? string|string[] +- -- `compare_against` was renamed to `ref1` + ---Git reference used as the base for the comparison. + ---@field ref1? string +- ---Fzf cursor start position for ctrl-q git_commits +- ---@field _pos? number + diff = { + cmd = "git --no-pager diff --name-only {ref1} {ref}", + ref = nil, +@@ -688,14 +685,22 @@ M.defaults.git = { + _actions = function() return M.globals.actions.files end, + _headers = { "cwd", "actions" }, + actions = { ++ ["ctrl-d"] = { ++ fn = function(s, _o) ++ if not s[1] then return FzfLua.utils.fzf_exit() end ++ local o = vim.deepcopy(_o.__call_opts) ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) ++ o.file = FzfLua.path.entry_to_file(s[1], _o).path ++ FzfLua.git_hunks(o) ++ end, ++ header = "git hunks", ++ exec_silent = true, ++ field_index = "{} $FZF_POS", ++ }, + ["ctrl-q"] = { +- fn = function(_, _o) ++ fn = function(s, _o) + local o = vim.deepcopy(_o.__call_opts) +- if o._pos then +- o._fzf_cli_args = o._fzf_cli_args or {} +- table.insert(o._fzf_cli_args, "--bind=" +- .. FzfLua.libuv.shellescape(string.format("load:+pos(%d)", o._pos))) +- end ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) + FzfLua.git_commits(o) + end, + reuse = true, +@@ -705,12 +710,17 @@ M.defaults.git = { + }, + ---Git diff hunks (changed lines). + ---@class fzf-lua.config.GitHunks: fzf-lua.config.GitBase +- ---Git reference to compare against. +- ---@field ref? string ++ ---Git file to diff ++ ---@field file? string ++ ---Git reference(s) to compare against. ++ ---@field ref? string|string[] ++ ---Git reference used as the base for the comparison. ++ ---@field ref1? string + hunks = { + previewer = M._default_previewer_fn, +- cmd = "git --no-pager diff --color=always {ref}", +- ref = "HEAD", ++ cmd = "git --no-pager diff --color=always {ref1} {ref} {file}", ++ ref = nil, ++ ref1 = nil, + multiprocess = true, ---@type integer|boolean + fn_transform = [[return require("fzf-lua.make_entry").git_hunk]], + fn_preprocess = [[return require("fzf-lua.make_entry").preprocess]], +@@ -723,7 +733,14 @@ M.defaults.git = { + }, + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, +- _headers = { "cwd" }, ++ _headers = { "cwd", "actions" }, ++ actions = { ++ ["ctrl-q"] = { ++ fn = function(_, _o) FzfLua.git_diff(vim.deepcopy(_o.__call_opts)) end, ++ reuse = true, ++ header = "git diff" ++ }, ++ }, + }, + ---Git commits (project). + ---@class fzf-lua.config.GitCommits: fzf-lua.config.GitBase +@@ -741,7 +758,7 @@ M.defaults.git = { + local o = vim.deepcopy(_o.__call_opts) + o.ref = s[1]:match("[^ ]+") + o.ref1 = o.ref .. "~" +- o._pos = tonumber(s[2]) ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) + FzfLua.git_diff(o) + end, + header = "git diff", +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index e541a55a..6dbee2a3 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -104,12 +104,9 @@ local git_validate_ref = function(opts, ref) + return true + end + +----@param opts fzf-lua.config.GitDiff|{}? +----@return thread?, string?, table? +-M.diff = function(opts) +- ---@type fzf-lua.config.GitDiff +- opts = config.normalize_opts(opts, "git.diff") +- if not opts then return end ++---@param opts fzf-lua.config.GitDiff|fzf-lua.config.GitHunks ++---@return table? ++local normalize_diff_opts = function(opts) + -- Backward compat `compare_against` -> `ref1` + ---@diagnostic disable-next-line: undefined-field + opts.ref1 = opts.compare_against or opts.ref1 +@@ -137,15 +134,44 @@ M.diff = function(opts) + end + opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") + opts.cmd = opts.cmd:gsub("[<{]ref1[}>]", opts.ref1 or "") +- opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") +- opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") +- opts = set_git_cwd_args(opts) +- if not opts.cwd then return end +- opts.preview = git_preview(opts, "{-1}") ++ opts.cmd = opts.cmd:gsub("[<{]file[}>]", opts.file and libuv.shellescape(opts.file) or "") ++ if type(opts.preview) == "string" then ++ opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") ++ opts.preview = git_preview(opts, "{-1}") ++ end + if type(opts._headers) == "table" then + table.insert(opts._headers, "ref") + table.insert(opts._headers, "ref1") + end ++ return set_git_cwd_args(opts) ++end ++ ++---@param opts fzf-lua.config.GitDiff|{}? ++---@return thread?, string?, table? ++M.diff = function(opts) ++ ---@type fzf-lua.config.GitDiff ++ opts = config.normalize_opts(opts, "git.diff") ++ if not opts then return end ++ opts = normalize_diff_opts(opts) ++ if not opts or not opts.cwd then return end ++ return core.fzf_exec(opts.cmd, opts) ++end ++ ++ ++---@param opts fzf-lua.config.GitHunks|{}? ++---@return thread?, string?, table? ++M.hunks = function(opts) ++ ---@type fzf-lua.config.GitHunks ++ opts = config.normalize_opts(opts, "git.hunks") ++ if not opts then return end ++ opts = normalize_diff_opts(opts) ++ if not opts or not opts.cwd then return end ++ ++ -- we don't need git icons since we get them ++ -- as part of our `git status -s` ++ opts.git_icons = false ++ + return core.fzf_exec(opts.cmd, opts) + end + +@@ -317,27 +343,4 @@ M.stash = function(opts) + return core.fzf_exec(opts.cmd, opts) + end + +----@param opts fzf-lua.config.GitHunks|{}? +----@return thread?, string?, table? +-M.hunks = function(opts) +- ---@type fzf-lua.config.GitHunks +- opts = config.normalize_opts(opts, "git.hunks") +- if not opts then return end +- if type(opts.ref) == "string" and #opts.ref > 0 and not git_validate_ref(opts, opts.ref) then +- return +- end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") +- opts = set_git_cwd_args(opts) +- if not opts.cwd then return end +- +- -- we don't need git icons since we get them +- -- as part of our `git status -s` +- opts.git_icons = false +- +- opts.header_prefix = opts.header_prefix or "+ - " +- opts.header_separator = opts.header_separator or "|" +- +- return core.fzf_exec(opts.cmd, opts) +-end +- + return M diff --git a/tasks/ibhagwan__fzf-lua-2622/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2622/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2622/task.toml b/tasks/ibhagwan__fzf-lua-2622/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6df4bedd4ed281495fd6ddac4307c5b9c643a729 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2622" +description = "feaT(git): binds for commits <-> diff <-> hunks" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "6e41ba7505f35a6f054ca682b043aa0cea36c2ef" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2622" +source_access = "auto" +built_at = "2026-11-16T16:09:56.044049+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c9b2b0b1ae5de590949cfc22d8bf72f6c2ab06f419ae7626d9ca802ebc996806" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-18T00:23:40Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/config.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/git.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 124 +difficulty = "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:01.032011+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fae5b34e1e4a8a7448a9fe49fc7242dc15a9e031169a0429da0d9b195569c2db" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2622/tests/capture.py b/tasks/ibhagwan__fzf-lua-2622/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2622/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2622/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1029ced4e00463fc730aa1cfb3185350a38802b6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feaT(git): binds for commits <-> diff <-> hunks + +## Description + +full diff lifecycle commtis -> diff -> hunks (and back) + + +## Summary by CodeRabbit + +* **New Features** + * File-specific diffs with multi-ref comparison and direct navigation between diffs, hunks, and commits. + * New key actions (Ctrl-D / Ctrl-Q) that jump into hunks/diffs/commits while preserving per-command cursor position. + +* **Bug Fixes & Improvements** + * Unified option normalization for diff/hunk flows and safer default refs. + * More reliable per-command positional tracking, improved locate/preview behavior, and stronger working-directory validation. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6e41ba7505f3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2622/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2622/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d0c9286c0aa26eaed1dda4d811f2cab42c26db93 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/tests/oracle.patch @@ -0,0 +1,207 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index f27590ba..19cce6cd 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -983,6 +983,12 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + opts.fn_preprocess = [[return require("fzf-lua.make_entry").preprocess]] + end + ++ -- set by git_{commits|diff|hunks} actions ++ if opts["__pos_" .. utils.get_info().cmd] then ++ opts.locate = opts.locate == nil and true or opts.locate ++ opts.__locate_pos = opts.__locate_pos or opts["__pos_" .. utils.get_info().cmd] ++ end ++ + if opts.locate and utils.has(opts, "fzf", { 0, 36 }) then + table.insert(opts._fzf_cli_args, "--bind=" .. libuv.shellescape("load:+transform:" + .. FzfLua.shell.stringify_data(function(_, _, _) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 018061b8..a7c70148 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -668,11 +668,8 @@ M.defaults.git = { + ---@class fzf-lua.config.GitDiff: fzf-lua.config.GitBase + ---Git reference(s) to compare against. + ---@field ref? string|string[] +- -- `compare_against` was renamed to `ref1` + ---Git reference used as the base for the comparison. + ---@field ref1? string +- ---Fzf cursor start position for ctrl-q git_commits +- ---@field _pos? number + diff = { + cmd = "git --no-pager diff --name-only {ref1} {ref}", + ref = nil, +@@ -688,14 +685,22 @@ M.defaults.git = { + _actions = function() return M.globals.actions.files end, + _headers = { "cwd", "actions" }, + actions = { ++ ["ctrl-d"] = { ++ fn = function(s, _o) ++ if not s[1] then return FzfLua.utils.fzf_exit() end ++ local o = vim.deepcopy(_o.__call_opts) ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) ++ o.file = FzfLua.path.entry_to_file(s[1], _o).path ++ FzfLua.git_hunks(o) ++ end, ++ header = "git hunks", ++ exec_silent = true, ++ field_index = "{} $FZF_POS", ++ }, + ["ctrl-q"] = { +- fn = function(_, _o) ++ fn = function(s, _o) + local o = vim.deepcopy(_o.__call_opts) +- if o._pos then +- o._fzf_cli_args = o._fzf_cli_args or {} +- table.insert(o._fzf_cli_args, "--bind=" +- .. FzfLua.libuv.shellescape(string.format("load:+pos(%d)", o._pos))) +- end ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) + FzfLua.git_commits(o) + end, + reuse = true, +@@ -705,12 +710,17 @@ M.defaults.git = { + }, + ---Git diff hunks (changed lines). + ---@class fzf-lua.config.GitHunks: fzf-lua.config.GitBase +- ---Git reference to compare against. +- ---@field ref? string ++ ---Git file to diff ++ ---@field file? string ++ ---Git reference(s) to compare against. ++ ---@field ref? string|string[] ++ ---Git reference used as the base for the comparison. ++ ---@field ref1? string + hunks = { + previewer = M._default_previewer_fn, +- cmd = "git --no-pager diff --color=always {ref}", +- ref = "HEAD", ++ cmd = "git --no-pager diff --color=always {ref1} {ref} {file}", ++ ref = nil, ++ ref1 = nil, + multiprocess = true, ---@type integer|boolean + fn_transform = [[return require("fzf-lua.make_entry").git_hunk]], + fn_preprocess = [[return require("fzf-lua.make_entry").preprocess]], +@@ -723,7 +733,14 @@ M.defaults.git = { + }, + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, +- _headers = { "cwd" }, ++ _headers = { "cwd", "actions" }, ++ actions = { ++ ["ctrl-q"] = { ++ fn = function(_, _o) FzfLua.git_diff(vim.deepcopy(_o.__call_opts)) end, ++ reuse = true, ++ header = "git diff" ++ }, ++ }, + }, + ---Git commits (project). + ---@class fzf-lua.config.GitCommits: fzf-lua.config.GitBase +@@ -741,7 +758,7 @@ M.defaults.git = { + local o = vim.deepcopy(_o.__call_opts) + o.ref = s[1]:match("[^ ]+") + o.ref1 = o.ref .. "~" +- o._pos = tonumber(s[2]) ++ o["__pos_" .. FzfLua.get_info().cmd] = tonumber(s[2]) + FzfLua.git_diff(o) + end, + header = "git diff", +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index e541a55a..6dbee2a3 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -104,12 +104,9 @@ local git_validate_ref = function(opts, ref) + return true + end + +----@param opts fzf-lua.config.GitDiff|{}? +----@return thread?, string?, table? +-M.diff = function(opts) +- ---@type fzf-lua.config.GitDiff +- opts = config.normalize_opts(opts, "git.diff") +- if not opts then return end ++---@param opts fzf-lua.config.GitDiff|fzf-lua.config.GitHunks ++---@return table? ++local normalize_diff_opts = function(opts) + -- Backward compat `compare_against` -> `ref1` + ---@diagnostic disable-next-line: undefined-field + opts.ref1 = opts.compare_against or opts.ref1 +@@ -137,15 +134,44 @@ M.diff = function(opts) + end + opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") + opts.cmd = opts.cmd:gsub("[<{]ref1[}>]", opts.ref1 or "") +- opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") +- opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") +- opts = set_git_cwd_args(opts) +- if not opts.cwd then return end +- opts.preview = git_preview(opts, "{-1}") ++ opts.cmd = opts.cmd:gsub("[<{]file[}>]", opts.file and libuv.shellescape(opts.file) or "") ++ if type(opts.preview) == "string" then ++ opts.preview = opts.preview:gsub("[<{]ref[}>]", opts.ref or "") ++ opts.preview = opts.preview:gsub("[<{]ref1[}>]", opts.ref1 or "") ++ opts.preview = git_preview(opts, "{-1}") ++ end + if type(opts._headers) == "table" then + table.insert(opts._headers, "ref") + table.insert(opts._headers, "ref1") + end ++ return set_git_cwd_args(opts) ++end ++ ++---@param opts fzf-lua.config.GitDiff|{}? ++---@return thread?, string?, table? ++M.diff = function(opts) ++ ---@type fzf-lua.config.GitDiff ++ opts = config.normalize_opts(opts, "git.diff") ++ if not opts then return end ++ opts = normalize_diff_opts(opts) ++ if not opts or not opts.cwd then return end ++ return core.fzf_exec(opts.cmd, opts) ++end ++ ++ ++---@param opts fzf-lua.config.GitHunks|{}? ++---@return thread?, string?, table? ++M.hunks = function(opts) ++ ---@type fzf-lua.config.GitHunks ++ opts = config.normalize_opts(opts, "git.hunks") ++ if not opts then return end ++ opts = normalize_diff_opts(opts) ++ if not opts or not opts.cwd then return end ++ ++ -- we don't need git icons since we get them ++ -- as part of our `git status -s` ++ opts.git_icons = false ++ + return core.fzf_exec(opts.cmd, opts) + end + +@@ -317,27 +343,4 @@ M.stash = function(opts) + return core.fzf_exec(opts.cmd, opts) + end + +----@param opts fzf-lua.config.GitHunks|{}? +----@return thread?, string?, table? +-M.hunks = function(opts) +- ---@type fzf-lua.config.GitHunks +- opts = config.normalize_opts(opts, "git.hunks") +- if not opts then return end +- if type(opts.ref) == "string" and #opts.ref > 0 and not git_validate_ref(opts, opts.ref) then +- return +- end +- opts.cmd = opts.cmd:gsub("[<{]ref[}>]", opts.ref or "") +- opts = set_git_cwd_args(opts) +- if not opts.cwd then return end +- +- -- we don't need git icons since we get them +- -- as part of our `git status -s` +- opts.git_icons = false +- +- opts.header_prefix = opts.header_prefix or "+ - " +- opts.header_separator = opts.header_separator or "|" +- +- return core.fzf_exec(opts.cmd, opts) +-end +- + return M diff --git a/tasks/ibhagwan__fzf-lua-2622/tests/test.sh b/tasks/ibhagwan__fzf-lua-2622/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2dfbf121ac22b75a1bcc957d2f1e1efcdd4b8716 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 6e41ba7505f35a6f054ca682b043aa0cea36c2ef > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2622/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2622/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2622/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2628/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2628/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9145d956f4eb0f66e1765d0973573d4749b9b7a9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3b01dc83a893749f5ae4639f1aa0af523821840a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3b01dc83a893749f5ae4639f1aa0af523821840a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3b01dc83a893749f5ae4639f1aa0af523821840a \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2628/instruction.md b/tasks/ibhagwan__fzf-lua-2628/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e9cc696808538a1759572442cd01b62f6d67cbe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(lines): show_bufname_len option + +## Description + +chore(jj): fix types, warn when jj is not found + +fix #2627 + + +## Summary by CodeRabbit + +* **New Features** + * Added Jujutsu file-picker support. + * Added configurable buffer-name truncation length for line displays (default: 15). + +* **Improvements** + * Improved handling and fallback behavior for preview selection. + * Enhanced Jujutsu integration with availability checks and safer option handling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3b01dc83a893`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2628/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2628/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b0505c4a64e6b4446c2c96595c28a202e5bd9e39 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/solution/patch.diff @@ -0,0 +1,127 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 035317fd..deb9a1a4 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -10,9 +10,10 @@ function M._default_previewer_fn() + if type(winopts) == "function" then + winopts = winopts() or {} + winopts.preview = type(winopts.preview) == "table" and winopts.preview or {} +- winopts.preview.default = winopts.preview.default or M.defaults.winopts.preview.default ++ winopts.preview.default = winopts.preview.default ++ or utils.map_get(M.defaults, "winopts.preview.default") + end +- local previewer = M.globals.default_previewer or winopts.preview.default ++ local previewer = M.globals.default_previewer or utils.map_get(winopts, "preview.default") + -- the setup function cannot have a custom previewer as deepcopy + -- fails with stack overflow while trying to copy the custom class + -- the workaround is to define the previewer as a function instead +@@ -894,11 +895,16 @@ M.defaults.git = { + }, + } + ++---Jujutsu pickers parent table. ++---@class fzf-lua.config.JJ ++---@field files fzf-lua.config.JJFiles + M.defaults.jj = { + ---Jujutsu tracked files. ++ ---@diagnostic disable-next-line: param-type-mismatch ++ ---@class fzf-lua.config.JJFiles: fzf-lua.config.GitFiles + files = vim.tbl_deep_extend("force", M.defaults.git.files, { +- cmd = "jj file list --ignore-working-copy", +- git_icons = false, ++ cmd = "jj file list --ignore-working-copy", ++ git_icons = false, + }), + } + +@@ -1173,6 +1179,8 @@ M.defaults.tabs = { + ---@class fzf-lua.config.Lines: fzf-lua.config.BufferLines + ---Show buffer name in results. Set to a number to only show if the window width exceeds this value. + ---@field show_bufname? boolean|integer ++---Show buffer name max length ++---@field show_bufname_len? integer + ---Include unloaded (not yet displayed) buffers. + ---@field show_unloaded? boolean + ---Include unlisted buffers (`:help unlisted-buffer`). +@@ -1186,6 +1194,7 @@ M.defaults.lines = { + file_icons = 1, ---@type integer|boolean + color_icons = true, + show_bufname = 120, ++ show_bufname_len = 15, + show_unloaded = true, + show_unlisted = false, + no_term_buffers = true, +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index 534c7418..6ebac2aa 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -22,6 +22,7 @@ local M = {} + ---@field end_line? integer + ---@field start? "cursor" + ---@field show_bufname? boolean|integer ++---@field show_bufname_len? integer + ---@field sort_lastused? boolean + + ---@param opts fzf-lua.config.BufferLines|{} +@@ -296,7 +297,7 @@ M.buffer_lines = function(opts) + longest_bname = math.max(longest_bname, #bname) + bnames[tostring(b)] = bname + end +- local len_bufnames = math.min(15, longest_bname) ++ local len_bufnames = math.min(tonumber(opts.show_bufname_len) or 15, longest_bname) + + for _, bufnr in ipairs(buffers) do + local data = {} +@@ -325,16 +326,17 @@ M.buffer_lines = function(opts) + local icon, hl = "", nil + local name = bnames[tostring(bufnr)] + +- if #name > len_bufnames + 1 then +- name = "…" .. name:sub(#name - len_bufnames + 2) +- end +- + if opts.file_icons then + icon, hl = devicons.get_devicon(name) + if hl and opts.color_icons then + icon = utils.ansi_from_rgb(hl, icon) + end + end ++ ++ if #name > len_bufnames + 1 then ++ name = "…" .. name:sub(#name - len_bufnames + 2) ++ end ++ + return name, icon and icon .. utils.nbsp or nil + end)() + +diff --git a/lua/fzf-lua/providers/jj.lua b/lua/fzf-lua/providers/jj.lua +index 1619c211..bd9e4c12 100644 +--- a/lua/fzf-lua/providers/jj.lua ++++ b/lua/fzf-lua/providers/jj.lua +@@ -6,6 +6,10 @@ local config = require "fzf-lua.config" + local M = {} + + local function set_jj_cwd_args(opts) ++ if vim.fn.executable("jj") ~= 1 then ++ utils.warn(string.format("'%s' requires jj (https://github.com/jj-vcs/jj).", utils.get_info().cmd)) ++ return ++ end + -- verify cwd is a jj repo, override user supplied + -- cwd if cwd isn't a jj repo, error was already + -- printed to `:messages` by 'path.jj_root' +@@ -16,13 +20,13 @@ local function set_jj_cwd_args(opts) + return opts + end + +----@param opts table|{}? ++---@param opts fzf-lua.config.JJFiles|{}? + ---@return thread?, string?, table? + M.files = function(opts) + opts = config.normalize_opts(opts, "jj.files") + if not opts then return end + opts = set_jj_cwd_args(opts) +- if not opts.cwd then return end ++ if not opts or not opts.cwd then return end + return core.fzf_exec(opts.cmd, opts) + end + diff --git a/tasks/ibhagwan__fzf-lua-2628/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2628/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2628/task.toml b/tasks/ibhagwan__fzf-lua-2628/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f672012813c362d3105f985575cf0bea8ae480fa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2628" +description = "feat(lines): show_bufname_len option" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "3b01dc83a893749f5ae4639f1aa0af523821840a" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2628" +source_access = "auto" +built_at = "2026-11-16T16:09:56.045754+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4661824707da303fdd3965eb2d17da2e049f16cc0f21eb992a938a9fb0b67a48" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-25T15:26:11Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/buffers.lua", + "lua/fzf-lua/providers/jj.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 37 +difficulty = "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:01.032564+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8726f858a8894dc2ec7c74483f0dae69314e8923f78a581a6e47733204db36e2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2628/tests/capture.py b/tasks/ibhagwan__fzf-lua-2628/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2628/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2628/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e9cc696808538a1759572442cd01b62f6d67cbe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(lines): show_bufname_len option + +## Description + +chore(jj): fix types, warn when jj is not found + +fix #2627 + + +## Summary by CodeRabbit + +* **New Features** + * Added Jujutsu file-picker support. + * Added configurable buffer-name truncation length for line displays (default: 15). + +* **Improvements** + * Improved handling and fallback behavior for preview selection. + * Enhanced Jujutsu integration with availability checks and safer option handling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3b01dc83a893`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2628/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2628/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b0505c4a64e6b4446c2c96595c28a202e5bd9e39 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/tests/oracle.patch @@ -0,0 +1,127 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 035317fd..deb9a1a4 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -10,9 +10,10 @@ function M._default_previewer_fn() + if type(winopts) == "function" then + winopts = winopts() or {} + winopts.preview = type(winopts.preview) == "table" and winopts.preview or {} +- winopts.preview.default = winopts.preview.default or M.defaults.winopts.preview.default ++ winopts.preview.default = winopts.preview.default ++ or utils.map_get(M.defaults, "winopts.preview.default") + end +- local previewer = M.globals.default_previewer or winopts.preview.default ++ local previewer = M.globals.default_previewer or utils.map_get(winopts, "preview.default") + -- the setup function cannot have a custom previewer as deepcopy + -- fails with stack overflow while trying to copy the custom class + -- the workaround is to define the previewer as a function instead +@@ -894,11 +895,16 @@ M.defaults.git = { + }, + } + ++---Jujutsu pickers parent table. ++---@class fzf-lua.config.JJ ++---@field files fzf-lua.config.JJFiles + M.defaults.jj = { + ---Jujutsu tracked files. ++ ---@diagnostic disable-next-line: param-type-mismatch ++ ---@class fzf-lua.config.JJFiles: fzf-lua.config.GitFiles + files = vim.tbl_deep_extend("force", M.defaults.git.files, { +- cmd = "jj file list --ignore-working-copy", +- git_icons = false, ++ cmd = "jj file list --ignore-working-copy", ++ git_icons = false, + }), + } + +@@ -1173,6 +1179,8 @@ M.defaults.tabs = { + ---@class fzf-lua.config.Lines: fzf-lua.config.BufferLines + ---Show buffer name in results. Set to a number to only show if the window width exceeds this value. + ---@field show_bufname? boolean|integer ++---Show buffer name max length ++---@field show_bufname_len? integer + ---Include unloaded (not yet displayed) buffers. + ---@field show_unloaded? boolean + ---Include unlisted buffers (`:help unlisted-buffer`). +@@ -1186,6 +1194,7 @@ M.defaults.lines = { + file_icons = 1, ---@type integer|boolean + color_icons = true, + show_bufname = 120, ++ show_bufname_len = 15, + show_unloaded = true, + show_unlisted = false, + no_term_buffers = true, +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index 534c7418..6ebac2aa 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -22,6 +22,7 @@ local M = {} + ---@field end_line? integer + ---@field start? "cursor" + ---@field show_bufname? boolean|integer ++---@field show_bufname_len? integer + ---@field sort_lastused? boolean + + ---@param opts fzf-lua.config.BufferLines|{} +@@ -296,7 +297,7 @@ M.buffer_lines = function(opts) + longest_bname = math.max(longest_bname, #bname) + bnames[tostring(b)] = bname + end +- local len_bufnames = math.min(15, longest_bname) ++ local len_bufnames = math.min(tonumber(opts.show_bufname_len) or 15, longest_bname) + + for _, bufnr in ipairs(buffers) do + local data = {} +@@ -325,16 +326,17 @@ M.buffer_lines = function(opts) + local icon, hl = "", nil + local name = bnames[tostring(bufnr)] + +- if #name > len_bufnames + 1 then +- name = "…" .. name:sub(#name - len_bufnames + 2) +- end +- + if opts.file_icons then + icon, hl = devicons.get_devicon(name) + if hl and opts.color_icons then + icon = utils.ansi_from_rgb(hl, icon) + end + end ++ ++ if #name > len_bufnames + 1 then ++ name = "…" .. name:sub(#name - len_bufnames + 2) ++ end ++ + return name, icon and icon .. utils.nbsp or nil + end)() + +diff --git a/lua/fzf-lua/providers/jj.lua b/lua/fzf-lua/providers/jj.lua +index 1619c211..bd9e4c12 100644 +--- a/lua/fzf-lua/providers/jj.lua ++++ b/lua/fzf-lua/providers/jj.lua +@@ -6,6 +6,10 @@ local config = require "fzf-lua.config" + local M = {} + + local function set_jj_cwd_args(opts) ++ if vim.fn.executable("jj") ~= 1 then ++ utils.warn(string.format("'%s' requires jj (https://github.com/jj-vcs/jj).", utils.get_info().cmd)) ++ return ++ end + -- verify cwd is a jj repo, override user supplied + -- cwd if cwd isn't a jj repo, error was already + -- printed to `:messages` by 'path.jj_root' +@@ -16,13 +20,13 @@ local function set_jj_cwd_args(opts) + return opts + end + +----@param opts table|{}? ++---@param opts fzf-lua.config.JJFiles|{}? + ---@return thread?, string?, table? + M.files = function(opts) + opts = config.normalize_opts(opts, "jj.files") + if not opts then return end + opts = set_jj_cwd_args(opts) +- if not opts.cwd then return end ++ if not opts or not opts.cwd then return end + return core.fzf_exec(opts.cmd, opts) + end + diff --git a/tasks/ibhagwan__fzf-lua-2628/tests/test.sh b/tasks/ibhagwan__fzf-lua-2628/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..fec2e10118dd17e8a0d6d6e4a91fe404170aa4a2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3b01dc83a893749f5ae4639f1aa0af523821840a > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2628/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2628/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2628/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2629/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2629/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2c5a5f7cfe012b80aecbf1a02ef308c274bd0450 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b2abbb7d122c94e893ed4ac359ede2af39aed989 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b2abbb7d122c94e893ed4ac359ede2af39aed989 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b2abbb7d122c94e893ed4ac359ede2af39aed989 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2629/instruction.md b/tasks/ibhagwan__fzf-lua-2629/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..58286054bbad2aaf48c748a63c7e44bdc0bb99e3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** docs(jj): fix jj for gen_option + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b2abbb7d122c`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2629/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2629/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9b71c518259ea5045660edaa25aed970e5949de1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index deb9a1a4..d7419898 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -896,12 +896,12 @@ M.defaults.git = { + } + + ---Jujutsu pickers parent table. +----@class fzf-lua.config.JJ +----@field files fzf-lua.config.JJFiles ++---@class fzf-lua.config.Jj ++---@field files fzf-lua.config.JjFiles + M.defaults.jj = { + ---Jujutsu tracked files. + ---@diagnostic disable-next-line: param-type-mismatch +- ---@class fzf-lua.config.JJFiles: fzf-lua.config.GitFiles ++ ---@class fzf-lua.config.JjFiles: fzf-lua.config.GitFiles + files = vim.tbl_deep_extend("force", M.defaults.git.files, { + cmd = "jj file list --ignore-working-copy", + git_icons = false, +diff --git a/lua/fzf-lua/providers/jj.lua b/lua/fzf-lua/providers/jj.lua +index bd9e4c12..1726051e 100644 +--- a/lua/fzf-lua/providers/jj.lua ++++ b/lua/fzf-lua/providers/jj.lua +@@ -20,7 +20,7 @@ local function set_jj_cwd_args(opts) + return opts + end + +----@param opts fzf-lua.config.JJFiles|{}? ++---@param opts fzf-lua.config.JjFiles|{}? + ---@return thread?, string?, table? + M.files = function(opts) + opts = config.normalize_opts(opts, "jj.files") +diff --git a/scripts/gen_options.lua b/scripts/gen_options.lua +index fe6b2bc9..b1d6fc04 100644 +--- a/scripts/gen_options.lua ++++ b/scripts/gen_options.lua +@@ -453,6 +453,7 @@ local SKIP_KEYS = { + -- Classes that are containers, not actual pickers + -- These have sub-pickers but shouldn't appear in docs themselves + local CONTAINER_CLASSES = { ++ ["fzf-lua.config.Jj"] = true, + ["fzf-lua.config.Git"] = true, + ["fzf-lua.config.Dap"] = true, + ["fzf-lua.config.Tmux"] = true, diff --git a/tasks/ibhagwan__fzf-lua-2629/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2629/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2629/task.toml b/tasks/ibhagwan__fzf-lua-2629/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..196707951a9f45d4f35a9016385cfca4270e50a6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2629" +description = "docs(jj): fix jj for gen_option" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b2abbb7d122c94e893ed4ac359ede2af39aed989" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2629" +source_access = "auto" +built_at = "2026-11-16T16:09:56.002665+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:53750882b104512492cebdd001c7b58896cb63c83f2f97ac56db33fc9bed4f53" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-25T16:20:11Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/jj.lua", + "scripts/gen_options.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[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:01.033115+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7771b7f612ba3f28d073a1bdac9fecbb450e2e2d2690cba64516164bf057b140" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2629/tests/capture.py b/tasks/ibhagwan__fzf-lua-2629/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2629/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2629/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..58286054bbad2aaf48c748a63c7e44bdc0bb99e3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** docs(jj): fix jj for gen_option + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b2abbb7d122c`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2629/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2629/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9b71c518259ea5045660edaa25aed970e5949de1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index deb9a1a4..d7419898 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -896,12 +896,12 @@ M.defaults.git = { + } + + ---Jujutsu pickers parent table. +----@class fzf-lua.config.JJ +----@field files fzf-lua.config.JJFiles ++---@class fzf-lua.config.Jj ++---@field files fzf-lua.config.JjFiles + M.defaults.jj = { + ---Jujutsu tracked files. + ---@diagnostic disable-next-line: param-type-mismatch +- ---@class fzf-lua.config.JJFiles: fzf-lua.config.GitFiles ++ ---@class fzf-lua.config.JjFiles: fzf-lua.config.GitFiles + files = vim.tbl_deep_extend("force", M.defaults.git.files, { + cmd = "jj file list --ignore-working-copy", + git_icons = false, +diff --git a/lua/fzf-lua/providers/jj.lua b/lua/fzf-lua/providers/jj.lua +index bd9e4c12..1726051e 100644 +--- a/lua/fzf-lua/providers/jj.lua ++++ b/lua/fzf-lua/providers/jj.lua +@@ -20,7 +20,7 @@ local function set_jj_cwd_args(opts) + return opts + end + +----@param opts fzf-lua.config.JJFiles|{}? ++---@param opts fzf-lua.config.JjFiles|{}? + ---@return thread?, string?, table? + M.files = function(opts) + opts = config.normalize_opts(opts, "jj.files") +diff --git a/scripts/gen_options.lua b/scripts/gen_options.lua +index fe6b2bc9..b1d6fc04 100644 +--- a/scripts/gen_options.lua ++++ b/scripts/gen_options.lua +@@ -453,6 +453,7 @@ local SKIP_KEYS = { + -- Classes that are containers, not actual pickers + -- These have sub-pickers but shouldn't appear in docs themselves + local CONTAINER_CLASSES = { ++ ["fzf-lua.config.Jj"] = true, + ["fzf-lua.config.Git"] = true, + ["fzf-lua.config.Dap"] = true, + ["fzf-lua.config.Tmux"] = true, diff --git a/tasks/ibhagwan__fzf-lua-2629/tests/test.sh b/tasks/ibhagwan__fzf-lua-2629/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..884622e855b1506c7b4ca78c9c57ea8b84190d87 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b2abbb7d122c94e893ed4ac359ede2af39aed989 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2629/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2629/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2629/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2630/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2630/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63c8491a4232a0ef5e10f8bbcb53343dd67047fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 14e2ebc7ed4cef90ffb4fd192ca28c33741818eb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 14e2ebc7ed4cef90ffb4fd192ca28c33741818eb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 14e2ebc7ed4cef90ffb4fd192ca28c33741818eb \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2630/instruction.md b/tasks/ibhagwan__fzf-lua-2630/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdebd7d8a42e672594af71c6d1fbdd1d5f274347 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(git): reflog picker + +## Description + +fix(cli): commits<->diff<->hunks actions +fix(hunks): with bat previewer + + +## Summary by CodeRabbit + +* **New Features** + * Added a new git reflog picker to fuzzy-search and navigate reflog entries. + * Improved git diff/commits action behavior to adapt execution to the Neovim UI environment. + * Enhanced hunk parsing for more accurate line selection. + +* **Documentation** + * README updated to include the new git reflog command reference. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `14e2ebc7ed4c`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2630/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2630/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..72792dd0914ca55ecdf2fac7d9d3d06a199ad030 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/solution/patch.diff @@ -0,0 +1,99 @@ +diff --git a/README.md b/README.md +index f9ea26ea..fc9599ad 100644 +--- a/README.md ++++ b/README.md +@@ -267,6 +267,7 @@ Fzf-Lua conveniently comes with a VS-Code like picker by default + | `git_status` | `git status` | + | `git_diff` | `git diff {ref}` | + | `git_hunks` | `git hunks {ref}` | ++| `git_reflog` | `git reflog` | + | `git_commits` | git commit log (project) | + | `git_bcommits` | git commit log (buffer) | + | `git_blame` | git blame (buffer) | +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d7419898..65769047 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -613,6 +613,7 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + ---@field status fzf-lua.config.GitStatus + ---@field diff fzf-lua.config.GitDiff + ---@field hunks fzf-lua.config.GitHunks ++---@field reflog fzf-lua.config.GitReflog + ---@field commits fzf-lua.config.GitCommits + ---@field bcommits fzf-lua.config.GitBcommits + ---@field blame fzf-lua.config.GitBlame +@@ -695,7 +696,8 @@ M.defaults.git = { + FzfLua.git_hunks(o) + end, + header = "git hunks", +- exec_silent = true, ++ reuse = #vim.api.nvim_list_uis() == 0, ++ exec_silent = #vim.api.nvim_list_uis() > 0, + field_index = "{} $FZF_POS", + }, + ["ctrl-q"] = { +@@ -732,6 +734,7 @@ M.defaults.git = { + ["--delimiter"] = ":", + ["--nth"] = "3..", + }, ++ line_field_index = "{2}", + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, + _headers = { "cwd", "actions" }, +@@ -763,7 +766,8 @@ M.defaults.git = { + FzfLua.git_diff(o) + end, + header = "git diff", +- exec_silent = true, ++ reuse = #vim.api.nvim_list_uis() == 0, ++ exec_silent = #vim.api.nvim_list_uis() > 0, + field_index = "{} $FZF_POS", + }, + }, +@@ -895,6 +899,13 @@ M.defaults.git = { + }, + } + ++---Git reflog. ++---@diagnostic disable-next-line: param-type-mismatch ++---@class fzf-lua.config.GitReflog: fzf-lua.config.GitCommits ++M.defaults.git.reflog = vim.tbl_deep_extend("force", M.defaults.git.commits, { ++ cmd = [[git reflog --color=always --format="%C(yellow)%h %C(blue)%gD%C(auto)%d %gs"]], ++}) ++ + ---Jujutsu pickers parent table. + ---@class fzf-lua.config.Jj + ---@field files fzf-lua.config.JjFiles +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index 7826edb6..9598c8dc 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -257,6 +257,7 @@ local lazyloaded_modules = { + git_diff = { "fzf-lua.providers.git", "diff" }, + git_hunks = { "fzf-lua.providers.git", "hunks" }, + git_stash = { "fzf-lua.providers.git", "stash" }, ++ git_reflog = { "fzf-lua.providers.git", "reflog" }, + git_commits = { "fzf-lua.providers.git", "commits" }, + git_bcommits = { "fzf-lua.providers.git", "bcommits" }, + git_blame = { "fzf-lua.providers.git", "blame" }, +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 6dbee2a3..5759f62f 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -185,6 +185,16 @@ M.commits = function(opts) + return git_cmd(opts) + end + ++---@param opts fzf-lua.config.GitReflog|{}? ++---@return thread?, string?, table? ++M.reflog = function(opts) ++ ---@type fzf-lua.config.GitReflog ++ opts = config.normalize_opts(opts, "git.reflog") ++ if not opts then return end ++ opts.preview = git_preview(opts) ++ return git_cmd(opts) ++end ++ + ---@param opts fzf-lua.config.GitBcommits|{}? + ---@return thread?, string?, table? + M.bcommits = function(opts) diff --git a/tasks/ibhagwan__fzf-lua-2630/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2630/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2630/task.toml b/tasks/ibhagwan__fzf-lua-2630/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9ab3070958648bf31a2beedd26ec6b86140067d6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2630" +description = "feat(git): reflog picker" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "14e2ebc7ed4cef90ffb4fd192ca28c33741818eb" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2630" +source_access = "auto" +built_at = "2026-11-16T16:09:56.042405+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:27f26bd3f7cd113a2641b97ec078cfee068866e7177a647cc1392947e533be65" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-26T01:05:03Z" +diff_format = "unified" +context_files = [ + "README.md", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/init.lua", + "lua/fzf-lua/providers/git.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 27 +difficulty = "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:01.033652+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:04c5be846a33d5f9de02e770fadd30496dea70b63cb4122477ac8284f95009c2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2630/tests/capture.py b/tasks/ibhagwan__fzf-lua-2630/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2630/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2630/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdebd7d8a42e672594af71c6d1fbdd1d5f274347 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(git): reflog picker + +## Description + +fix(cli): commits<->diff<->hunks actions +fix(hunks): with bat previewer + + +## Summary by CodeRabbit + +* **New Features** + * Added a new git reflog picker to fuzzy-search and navigate reflog entries. + * Improved git diff/commits action behavior to adapt execution to the Neovim UI environment. + * Enhanced hunk parsing for more accurate line selection. + +* **Documentation** + * README updated to include the new git reflog command reference. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `14e2ebc7ed4c`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2630/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2630/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..72792dd0914ca55ecdf2fac7d9d3d06a199ad030 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/tests/oracle.patch @@ -0,0 +1,99 @@ +diff --git a/README.md b/README.md +index f9ea26ea..fc9599ad 100644 +--- a/README.md ++++ b/README.md +@@ -267,6 +267,7 @@ Fzf-Lua conveniently comes with a VS-Code like picker by default + | `git_status` | `git status` | + | `git_diff` | `git diff {ref}` | + | `git_hunks` | `git hunks {ref}` | ++| `git_reflog` | `git reflog` | + | `git_commits` | git commit log (project) | + | `git_bcommits` | git commit log (buffer) | + | `git_blame` | git blame (buffer) | +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d7419898..65769047 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -613,6 +613,7 @@ M.defaults.global = vim.tbl_deep_extend("force", M.defaults.files, { + ---@field status fzf-lua.config.GitStatus + ---@field diff fzf-lua.config.GitDiff + ---@field hunks fzf-lua.config.GitHunks ++---@field reflog fzf-lua.config.GitReflog + ---@field commits fzf-lua.config.GitCommits + ---@field bcommits fzf-lua.config.GitBcommits + ---@field blame fzf-lua.config.GitBlame +@@ -695,7 +696,8 @@ M.defaults.git = { + FzfLua.git_hunks(o) + end, + header = "git hunks", +- exec_silent = true, ++ reuse = #vim.api.nvim_list_uis() == 0, ++ exec_silent = #vim.api.nvim_list_uis() > 0, + field_index = "{} $FZF_POS", + }, + ["ctrl-q"] = { +@@ -732,6 +734,7 @@ M.defaults.git = { + ["--delimiter"] = ":", + ["--nth"] = "3..", + }, ++ line_field_index = "{2}", + _fzf_nth_devicons = true, + _actions = function() return M.globals.actions.files end, + _headers = { "cwd", "actions" }, +@@ -763,7 +766,8 @@ M.defaults.git = { + FzfLua.git_diff(o) + end, + header = "git diff", +- exec_silent = true, ++ reuse = #vim.api.nvim_list_uis() == 0, ++ exec_silent = #vim.api.nvim_list_uis() > 0, + field_index = "{} $FZF_POS", + }, + }, +@@ -895,6 +899,13 @@ M.defaults.git = { + }, + } + ++---Git reflog. ++---@diagnostic disable-next-line: param-type-mismatch ++---@class fzf-lua.config.GitReflog: fzf-lua.config.GitCommits ++M.defaults.git.reflog = vim.tbl_deep_extend("force", M.defaults.git.commits, { ++ cmd = [[git reflog --color=always --format="%C(yellow)%h %C(blue)%gD%C(auto)%d %gs"]], ++}) ++ + ---Jujutsu pickers parent table. + ---@class fzf-lua.config.Jj + ---@field files fzf-lua.config.JjFiles +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index 7826edb6..9598c8dc 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -257,6 +257,7 @@ local lazyloaded_modules = { + git_diff = { "fzf-lua.providers.git", "diff" }, + git_hunks = { "fzf-lua.providers.git", "hunks" }, + git_stash = { "fzf-lua.providers.git", "stash" }, ++ git_reflog = { "fzf-lua.providers.git", "reflog" }, + git_commits = { "fzf-lua.providers.git", "commits" }, + git_bcommits = { "fzf-lua.providers.git", "bcommits" }, + git_blame = { "fzf-lua.providers.git", "blame" }, +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 6dbee2a3..5759f62f 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -185,6 +185,16 @@ M.commits = function(opts) + return git_cmd(opts) + end + ++---@param opts fzf-lua.config.GitReflog|{}? ++---@return thread?, string?, table? ++M.reflog = function(opts) ++ ---@type fzf-lua.config.GitReflog ++ opts = config.normalize_opts(opts, "git.reflog") ++ if not opts then return end ++ opts.preview = git_preview(opts) ++ return git_cmd(opts) ++end ++ + ---@param opts fzf-lua.config.GitBcommits|{}? + ---@return thread?, string?, table? + M.bcommits = function(opts) diff --git a/tasks/ibhagwan__fzf-lua-2630/tests/test.sh b/tasks/ibhagwan__fzf-lua-2630/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b13dda47f905182cf0410d3fa5470610595a595 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 14e2ebc7ed4cef90ffb4fd192ca28c33741818eb > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2630/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2630/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2630/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2633/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2633/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8c472b874a1008137f536c58c76ab1a90fceef50 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 28440c741e927592877514fba3db21eb188caec8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 28440c741e927592877514fba3db21eb188caec8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 28440c741e927592877514fba3db21eb188caec8 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2633/instruction.md b/tasks/ibhagwan__fzf-lua-2633/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f011200cc1049b6f9c0ebefc725c9e47964fdfc8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(tsinjector): pass lnum to line_parser + +## Description + +It's non trivial to determine where the "prompt" line is. +When we have reverse/default layout, info/header/footer border + +This is a workaround for user find the prompt hl annoying: +```lua +opts.command_history._treesitter = function(line, lnum) + if lnum == 1 then return end + return line:match("(.-):?(%d+)[: ](.+)$") +end +``` + + +## Summary by CodeRabbit + +* **Enhancements** + * Treesitter callbacks now receive optional line number information, enabling custom parsers to perform more contextual text processing. + * Existing parsing behavior remains unchanged for current configurations. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28440c741e92`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2633/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2633/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..22c709981a4f77d9ed4a363976b17e4c44973d97 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index a06e1791..4d54f224 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1389,7 +1389,7 @@ M.defaults.tags = { + -- field_index_expr = "{}", -- For `_fmt.from` to work with `bat_native` + _actions = function() return M.globals.actions.files end, + actions = { ["ctrl-g"] = { actions.grep_lgrep } }, +- _treesitter = function(line) return ctag_line_parser(line, true) end, ++ _treesitter = function(line, _) return ctag_line_parser(line, true) end, + } + + ---Search current buffer ctags. +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index f68ada7f..a799d42f 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -116,6 +116,8 @@ local FzfLua = require("fzf-lua") + ---@field get fun(self: fzf-lua.PidObject): integer + ---@field set fun(self: fzf-lua.PidObject, pid: integer?) + ++---@alias fzf-lua.treesitter.lineParser (fun(line: string, lnum?: integer):string?,string?,string|table?,string?) ++ + ---a basic config can be used by fzf_exec? + ---generated from the result of `:=FzfLua.config.normalize_opts({}, {})` + ---@class fzf-lua.config.Base +@@ -203,7 +205,7 @@ local FzfLua = require("fzf-lua") + ---@field _actions? fun():fzf-lua.config.Actions? + ---@field __ACT_TO? function + ---@field _start? boolean +----@field _treesitter? (fun(line: string):string?,string?,string|table?,string?)|boolean? ++---@field _treesitter? fzf-lua.treesitter.lineParser + ---@field help_open_win? fun(buf: integer, enter: boolean, config: vim.api.keyset.win_config): integer + ---Auto close fzf-lua interface when a terminal is opened, set to `false` to keep the interface open. + ---@field autoclose? boolean +diff --git a/lua/fzf-lua/win/tsinjector.lua b/lua/fzf-lua/win/tsinjector.lua +index a9cfe66a..f4bd1274 100644 +--- a/lua/fzf-lua/win/tsinjector.lua ++++ b/lua/fzf-lua/win/tsinjector.lua +@@ -127,14 +127,14 @@ end + + ---@param self fzf-lua.Win + ---@param buf integer +----@param line_parser (fun(line: string):string?,string?,string|table?,string?)|boolean? ++---@param line_parser? fzf-lua.treesitter.lineParser + ---@return function detach + function M.attach(self, buf, line_parser) + -- local utf8 = require("fzf-lua.lib.utf8") + local function trim(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end + ---@type fun(line: string):string?,string?,string?,string? +- local default_line_parser = function(line) return line:match("(.-):?(%d+)[: ](.+)$") end +- ---@type (fun(line: string):string?,string?,string|table?,string?) ++ local default_line_parser = function(line, _) return line:match("(.-):?(%d+)[: ](.+)$") end ++ ---@type fzf-lua.treesitter.lineParser + line_parser = vim.is_callable(line_parser) and line_parser or default_line_parser + M.cache[buf] = {} + api.nvim_buf_attach(buf, false, { +@@ -172,7 +172,7 @@ function M.attach(self, buf, line_parser) + -- file:line:text (grep_project or missing "--column" flag) + -- line:col:text (grep_curbuf) + -- linetext (lines|blines) +- local filepath, _lnum, info, _ft = line_parser(line:sub(min_col + 1)) ++ local filepath, _lnum, info, _ft = line_parser(line:sub(min_col + 1), i) + + -- info can be a string or `{ text = ..., start_col, end_col }` + info = type(info) == "table" and info or { text = info } diff --git a/tasks/ibhagwan__fzf-lua-2633/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2633/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2633/task.toml b/tasks/ibhagwan__fzf-lua-2633/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..161d44bfe596656f493b95b324b68be36985f69e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2633" +description = "fix(tsinjector): pass lnum to line_parser" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "28440c741e927592877514fba3db21eb188caec8" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2633" +source_access = "auto" +built_at = "2026-11-16T16:09:55.955897+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:754a319dab46e1a41a3f54248fb7a7069ed980e8ba52f6e5c8bba01ec779e419" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-05T09:11:19Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/types.lua", + "lua/fzf-lua/win/tsinjector.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[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:01.034227+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3792e66bb06993af867a0ebfc1013288293e2105ad7de6fd9713393fbecaa978" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2633/tests/capture.py b/tasks/ibhagwan__fzf-lua-2633/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2633/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2633/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f011200cc1049b6f9c0ebefc725c9e47964fdfc8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(tsinjector): pass lnum to line_parser + +## Description + +It's non trivial to determine where the "prompt" line is. +When we have reverse/default layout, info/header/footer border + +This is a workaround for user find the prompt hl annoying: +```lua +opts.command_history._treesitter = function(line, lnum) + if lnum == 1 then return end + return line:match("(.-):?(%d+)[: ](.+)$") +end +``` + + +## Summary by CodeRabbit + +* **Enhancements** + * Treesitter callbacks now receive optional line number information, enabling custom parsers to perform more contextual text processing. + * Existing parsing behavior remains unchanged for current configurations. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28440c741e92`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2633/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2633/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..22c709981a4f77d9ed4a363976b17e4c44973d97 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index a06e1791..4d54f224 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1389,7 +1389,7 @@ M.defaults.tags = { + -- field_index_expr = "{}", -- For `_fmt.from` to work with `bat_native` + _actions = function() return M.globals.actions.files end, + actions = { ["ctrl-g"] = { actions.grep_lgrep } }, +- _treesitter = function(line) return ctag_line_parser(line, true) end, ++ _treesitter = function(line, _) return ctag_line_parser(line, true) end, + } + + ---Search current buffer ctags. +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index f68ada7f..a799d42f 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -116,6 +116,8 @@ local FzfLua = require("fzf-lua") + ---@field get fun(self: fzf-lua.PidObject): integer + ---@field set fun(self: fzf-lua.PidObject, pid: integer?) + ++---@alias fzf-lua.treesitter.lineParser (fun(line: string, lnum?: integer):string?,string?,string|table?,string?) ++ + ---a basic config can be used by fzf_exec? + ---generated from the result of `:=FzfLua.config.normalize_opts({}, {})` + ---@class fzf-lua.config.Base +@@ -203,7 +205,7 @@ local FzfLua = require("fzf-lua") + ---@field _actions? fun():fzf-lua.config.Actions? + ---@field __ACT_TO? function + ---@field _start? boolean +----@field _treesitter? (fun(line: string):string?,string?,string|table?,string?)|boolean? ++---@field _treesitter? fzf-lua.treesitter.lineParser + ---@field help_open_win? fun(buf: integer, enter: boolean, config: vim.api.keyset.win_config): integer + ---Auto close fzf-lua interface when a terminal is opened, set to `false` to keep the interface open. + ---@field autoclose? boolean +diff --git a/lua/fzf-lua/win/tsinjector.lua b/lua/fzf-lua/win/tsinjector.lua +index a9cfe66a..f4bd1274 100644 +--- a/lua/fzf-lua/win/tsinjector.lua ++++ b/lua/fzf-lua/win/tsinjector.lua +@@ -127,14 +127,14 @@ end + + ---@param self fzf-lua.Win + ---@param buf integer +----@param line_parser (fun(line: string):string?,string?,string|table?,string?)|boolean? ++---@param line_parser? fzf-lua.treesitter.lineParser + ---@return function detach + function M.attach(self, buf, line_parser) + -- local utf8 = require("fzf-lua.lib.utf8") + local function trim(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end + ---@type fun(line: string):string?,string?,string?,string? +- local default_line_parser = function(line) return line:match("(.-):?(%d+)[: ](.+)$") end +- ---@type (fun(line: string):string?,string?,string|table?,string?) ++ local default_line_parser = function(line, _) return line:match("(.-):?(%d+)[: ](.+)$") end ++ ---@type fzf-lua.treesitter.lineParser + line_parser = vim.is_callable(line_parser) and line_parser or default_line_parser + M.cache[buf] = {} + api.nvim_buf_attach(buf, false, { +@@ -172,7 +172,7 @@ function M.attach(self, buf, line_parser) + -- file:line:text (grep_project or missing "--column" flag) + -- line:col:text (grep_curbuf) + -- linetext (lines|blines) +- local filepath, _lnum, info, _ft = line_parser(line:sub(min_col + 1)) ++ local filepath, _lnum, info, _ft = line_parser(line:sub(min_col + 1), i) + + -- info can be a string or `{ text = ..., start_col, end_col }` + info = type(info) == "table" and info or { text = info } diff --git a/tasks/ibhagwan__fzf-lua-2633/tests/test.sh b/tasks/ibhagwan__fzf-lua-2633/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ccf3ce034c3e889ac63eaafbb51912770bf98f81 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 28440c741e927592877514fba3db21eb188caec8 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2633/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2633/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2633/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2637/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2637/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6fa4530f41d10a159b0594d5fa4431c6cf79559d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bde73a6886b607246095aa59f396de5e0d036890 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bde73a6886b607246095aa59f396de5e0d036890 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bde73a6886b607246095aa59f396de5e0d036890 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2637/instruction.md b/tasks/ibhagwan__fzf-lua-2637/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd8098b75d5d04d687e9444f83a20e202bc244da --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(libuv): duplicated prev_line_content when stream EOF + +## Description + +When the stream ends (signified by `data` being `nil`), the function +checked if there was any `prev_line_content` leftover. + +prev_line_content isn't nullified and will be used again in split_lines: +``` +prev_line_content .. EOL .. prev_line_content +``` + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bde73a6886b6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2637/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2637/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..45f3016db9b0257d77c240f68af626ede6bcda4e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/libuv.lua b/lua/fzf-lua/libuv.lua +index 76ec063a..579600ed 100644 +--- a/lua/fzf-lua/libuv.lua ++++ b/lua/fzf-lua/libuv.lua +@@ -240,7 +240,10 @@ M.spawn = function(opts, fn_transform, fn_done) + --- Called with nil to process the leftover data + ---@param data string? + local process_data = function(data) +- data = data or prev_line_content and (prev_line_content .. EOL) or nil ++ if not data and prev_line_content then ++ data = prev_line_content .. EOL ++ prev_line_content = nil ++ end + if not data then + -- NOTE: this isn't called when prev_line_content is not nil but that's + -- not a problem as the write_cb will call finish once the callback is done diff --git a/tasks/ibhagwan__fzf-lua-2637/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2637/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2637/task.toml b/tasks/ibhagwan__fzf-lua-2637/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01a1e222c00e379a5b5556dc4960b870695eab6c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2637" +description = "fix(libuv): duplicated prev_line_content when stream EOF" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "bde73a6886b607246095aa59f396de5e0d036890" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2637" +source_access = "auto" +built_at = "2026-11-16T16:09:56.037569+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:db74d47d6385c097f066445e839dde6d51fe8397b84e229ae43991a10ca21a20" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-03-30T07:56:09Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/libuv.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.034778+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f0f6ec6c274147e01e774eaec835f27f2ba3cdeb1776b5f81d7fc4ab0f9f7f11" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2637/tests/capture.py b/tasks/ibhagwan__fzf-lua-2637/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2637/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2637/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dd8098b75d5d04d687e9444f83a20e202bc244da --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(libuv): duplicated prev_line_content when stream EOF + +## Description + +When the stream ends (signified by `data` being `nil`), the function +checked if there was any `prev_line_content` leftover. + +prev_line_content isn't nullified and will be used again in split_lines: +``` +prev_line_content .. EOL .. prev_line_content +``` + +Fix + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bde73a6886b6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2637/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2637/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..45f3016db9b0257d77c240f68af626ede6bcda4e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/libuv.lua b/lua/fzf-lua/libuv.lua +index 76ec063a..579600ed 100644 +--- a/lua/fzf-lua/libuv.lua ++++ b/lua/fzf-lua/libuv.lua +@@ -240,7 +240,10 @@ M.spawn = function(opts, fn_transform, fn_done) + --- Called with nil to process the leftover data + ---@param data string? + local process_data = function(data) +- data = data or prev_line_content and (prev_line_content .. EOL) or nil ++ if not data and prev_line_content then ++ data = prev_line_content .. EOL ++ prev_line_content = nil ++ end + if not data then + -- NOTE: this isn't called when prev_line_content is not nil but that's + -- not a problem as the write_cb will call finish once the callback is done diff --git a/tasks/ibhagwan__fzf-lua-2637/tests/test.sh b/tasks/ibhagwan__fzf-lua-2637/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a1e3dd7a90e54f544be4182532e28525d9768b9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bde73a6886b607246095aa59f396de5e0d036890 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2637/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2637/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2637/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2644/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2644/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6c5db9eb113e736c47170e60209a164064c994f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5cbe58ca48c4c4a2fbe5e324b854596d8242711e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5cbe58ca48c4c4a2fbe5e324b854596d8242711e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5cbe58ca48c4c4a2fbe5e324b854596d8242711e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2644/instruction.md b/tasks/ibhagwan__fzf-lua-2644/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f1fa32993be2186fa5a35c396aee22053b48b1b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(win): restore last accessed (CTRL-W p) window after closing fzf … + +## Description + +I often use a tab with 3 windows and I switch between the 2 of them with `CTRL-W p` binding. +The problem is that when I spawn a FZF window (e.g. `FzfLua lines`) and then close it, the `CTRL-W p` binding no longer works. + +~Although this PR fixes the issue, I hope there might be a better way of extracting the last window without triggering autocommands `WinEnter` and `WinLeave` on the `last_winid`.~ + +~If this change is "too aggressive", we might add a new option to the config to enable this last accessed window preserving behaviour.~ + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable window focus restoration when closing search/overlay, preventing accidental focus loss. + * Reduced focus flicker during teardown for a smoother close experience. + * Closing the overlay now consistently preserves the previously active window. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5cbe58ca48c4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2644/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2644/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b38594fda075e12323e78bdf07f1e4c08f253994 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 16852f46..6391af9a 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -11,6 +11,7 @@ local ctx + ---@field bufnr integer + ---@field bname string + ---@field winid integer ++---@field last_winid integer + ---@field alt_bufnr integer + ---@field tabnr integer + ---@field tabh integer +@@ -51,6 +52,7 @@ M.refresh = function(opts) + bufnr = vim.api.nvim_get_current_buf(), + bname = vim.api.nvim_buf_get_name(0), + winid = vim.api.nvim_get_current_win(), ++ last_winid = vim.fn.win_getid(vim.fn.winnr("#")), + alt_bufnr = vim.fn.bufnr("#"), + tabnr = vim.fn.tabpagenr(), + tabh = vim.api.nvim_win_get_tabpage(0), +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index c0635ae0..5efc061d 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1140,6 +1140,17 @@ function FzfWin:close_preview(do_not_clear_cache) + self.preview_winid = nil + end + ++---@param winid? integer ++---@param last_winid? integer ++local restore_lastwin = function(winid, last_winid) ++ if winid and last_winid and api.nvim_win_is_valid(last_winid) then ++ utils.eventignore(function() ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) ++ end) ++ end ++end ++ + ---@param buf? integer + local restore_altbuf = function(buf) + if buf and api.nvim_buf_is_valid(buf) then +@@ -1166,6 +1177,8 @@ function FzfWin:close(fzf_bufnr, hide) + local ctx = utils.__CTX() or {} + if ctx.mode == "nt" then vim.cmd "stopinsert" end + if self.fzf_winid and api.nvim_win_is_valid(self.fzf_winid) then ++ -- restore the original last window ++ restore_lastwin(ctx.winid, ctx.last_winid) + -- run in a pcall due to potential errors while closing the window + -- Vim(lua):E5108: Error executing lua + -- experienced while accessing 'vim.b[]' from my statusline code +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index dfefb787..559dc445 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -155,9 +155,9 @@ T["actions"]["vimcmd"] = new_set({ + -- Wait for previewer to load the LICENSE file entry and title to render + child.wait_until(function() + local entry = child.lua_get([[FzfLua.utils.fzf_winobj()._previewer.last_entry]]) +- return entry and entry:match("LICENSE") ~= nil ++ return entry ~= vim.NIL and entry:match("LICENSE") ~= nil + end) +- vim.uv.sleep(100) -- Allow async title update to render ++ vim.uv.sleep(100) -- Allow async title update to render + if helpers.IS_WIN() then vim.uv.sleep(250) end + end, + no_esc = true, diff --git a/tasks/ibhagwan__fzf-lua-2644/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2644/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2644/task.toml b/tasks/ibhagwan__fzf-lua-2644/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fc601a3527ff7ffd8b97467b9fa21c8fd095292 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2644" +description = "feat(win): restore last accessed (CTRL-W p) window after closing fzf …" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "5cbe58ca48c4c4a2fbe5e324b854596d8242711e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2644" +source_access = "auto" +built_at = "2026-11-16T16:09:56.039385+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7cd0657aeebc403c776bc839c562cb5f36e4a7f6b2f070a98218634539919427" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-04T12:14:39Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/ctx.lua", + "lua/fzf-lua/win.lua", + "tests/actions_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[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:01.035364+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:85a2e9797a2beaed9f92dbc5f5e9a657e9df00794430d67f9b4d4745982b9c64" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2644/tests/capture.py b/tasks/ibhagwan__fzf-lua-2644/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2644/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2644/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f1fa32993be2186fa5a35c396aee22053b48b1b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(win): restore last accessed (CTRL-W p) window after closing fzf … + +## Description + +I often use a tab with 3 windows and I switch between the 2 of them with `CTRL-W p` binding. +The problem is that when I spawn a FZF window (e.g. `FzfLua lines`) and then close it, the `CTRL-W p` binding no longer works. + +~Although this PR fixes the issue, I hope there might be a better way of extracting the last window without triggering autocommands `WinEnter` and `WinLeave` on the `last_winid`.~ + +~If this change is "too aggressive", we might add a new option to the config to enable this last accessed window preserving behaviour.~ + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable window focus restoration when closing search/overlay, preventing accidental focus loss. + * Reduced focus flicker during teardown for a smoother close experience. + * Closing the overlay now consistently preserves the previously active window. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5cbe58ca48c4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2644/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2644/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b38594fda075e12323e78bdf07f1e4c08f253994 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 16852f46..6391af9a 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -11,6 +11,7 @@ local ctx + ---@field bufnr integer + ---@field bname string + ---@field winid integer ++---@field last_winid integer + ---@field alt_bufnr integer + ---@field tabnr integer + ---@field tabh integer +@@ -51,6 +52,7 @@ M.refresh = function(opts) + bufnr = vim.api.nvim_get_current_buf(), + bname = vim.api.nvim_buf_get_name(0), + winid = vim.api.nvim_get_current_win(), ++ last_winid = vim.fn.win_getid(vim.fn.winnr("#")), + alt_bufnr = vim.fn.bufnr("#"), + tabnr = vim.fn.tabpagenr(), + tabh = vim.api.nvim_win_get_tabpage(0), +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index c0635ae0..5efc061d 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1140,6 +1140,17 @@ function FzfWin:close_preview(do_not_clear_cache) + self.preview_winid = nil + end + ++---@param winid? integer ++---@param last_winid? integer ++local restore_lastwin = function(winid, last_winid) ++ if winid and last_winid and api.nvim_win_is_valid(last_winid) then ++ utils.eventignore(function() ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) ++ end) ++ end ++end ++ + ---@param buf? integer + local restore_altbuf = function(buf) + if buf and api.nvim_buf_is_valid(buf) then +@@ -1166,6 +1177,8 @@ function FzfWin:close(fzf_bufnr, hide) + local ctx = utils.__CTX() or {} + if ctx.mode == "nt" then vim.cmd "stopinsert" end + if self.fzf_winid and api.nvim_win_is_valid(self.fzf_winid) then ++ -- restore the original last window ++ restore_lastwin(ctx.winid, ctx.last_winid) + -- run in a pcall due to potential errors while closing the window + -- Vim(lua):E5108: Error executing lua + -- experienced while accessing 'vim.b[]' from my statusline code +diff --git a/tests/actions_spec.lua b/tests/actions_spec.lua +index dfefb787..559dc445 100644 +--- a/tests/actions_spec.lua ++++ b/tests/actions_spec.lua +@@ -155,9 +155,9 @@ T["actions"]["vimcmd"] = new_set({ + -- Wait for previewer to load the LICENSE file entry and title to render + child.wait_until(function() + local entry = child.lua_get([[FzfLua.utils.fzf_winobj()._previewer.last_entry]]) +- return entry and entry:match("LICENSE") ~= nil ++ return entry ~= vim.NIL and entry:match("LICENSE") ~= nil + end) +- vim.uv.sleep(100) -- Allow async title update to render ++ vim.uv.sleep(100) -- Allow async title update to render + if helpers.IS_WIN() then vim.uv.sleep(250) end + end, + no_esc = true, diff --git a/tasks/ibhagwan__fzf-lua-2644/tests/test.sh b/tasks/ibhagwan__fzf-lua-2644/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..547794be59c84865315a54ddbd93cc9e19ea1029 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5cbe58ca48c4c4a2fbe5e324b854596d8242711e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2644/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2644/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2644/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2648/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2648/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..77cc7244f9c57fa72ee4b1a0b1eee4356d4c420b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin abacb0693d7a37de9e85e6fcb2d22d848cb75cef 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard abacb0693d7a37de9e85e6fcb2d22d848cb75cef \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base abacb0693d7a37de9e85e6fcb2d22d848cb75cef \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2648/instruction.md b/tasks/ibhagwan__fzf-lua-2648/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9fad62473a27703779cd6c3261b4d5fdc1f0eb5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** ci: autogenerate types + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * CI workflow updated to run an additional generation step after documentation is produced; the workflow now stages and commits the newly generated artifacts (including type definitions) alongside docs so generated outputs are consistently included in CI-driven commits and downstream checks. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abacb0693d7a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2648/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2648/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98339e23239c83c326175cef4dc62001e46f9160 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/solution/patch.diff @@ -0,0 +1,24 @@ +diff --git a/.github/workflows/vimdoc.yaml b/.github/workflows/vimdoc.yaml +index 0d76bd51..38aff6fe 100644 +--- a/.github/workflows/vimdoc.yaml ++++ b/.github/workflows/vimdoc.yaml +@@ -26,9 +26,10 @@ jobs: + echo "${PWD}/emmylua_doc_cli/" >> $GITHUB_PATH + export PATH="${PWD}/emmylua_doc_cli/:${PATH}" + emmylua_doc_cli --version +- - name: Generate OPTIONS.md ++ - name: Generate OPTIONS.md and types + run: | + nvim --headless -l scripts/gen_options.lua ++ make gen + - name: Setup treesitter + run: | + mkdir -p ~/.local/share/nvim/site/pack/vendor/start +@@ -54,6 +55,6 @@ jobs: + git config user.email "actions@github" + git config user.name "Github Actions" + git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git +- git add doc OPTIONS.md ++ git add doc OPTIONS.md lua/fzf-lua/types.lua + # Only commit and push if we have changes + git diff --quiet && git diff --staged --quiet || (git commit -m "${COMMIT_MSG}"; git push origin HEAD:${GITHUB_REF}) diff --git a/tasks/ibhagwan__fzf-lua-2648/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2648/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2648/task.toml b/tasks/ibhagwan__fzf-lua-2648/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b7b60c6025f361de401d3145b3998e255f13c0df --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2648" +description = "ci: autogenerate types" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "abacb0693d7a37de9e85e6fcb2d22d848cb75cef" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2648" +source_access = "auto" +built_at = "2026-11-16T16:09:56.027016+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b6bc4a7166c3950e9d8a4916fcdfb676a30a666adb20860476aaba076ae01892" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-05T06:50:06Z" +diff_format = "unified" +context_files = [ + ".github/workflows/vimdoc.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.035889+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e97634f45613cdb9313508317ceb69de4d14f2156a2db0b3360342b950212b1d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2648/tests/capture.py b/tasks/ibhagwan__fzf-lua-2648/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2648/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2648/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9fad62473a27703779cd6c3261b4d5fdc1f0eb5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** ci: autogenerate types + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * CI workflow updated to run an additional generation step after documentation is produced; the workflow now stages and commits the newly generated artifacts (including type definitions) alongside docs so generated outputs are consistently included in CI-driven commits and downstream checks. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abacb0693d7a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2648/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2648/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..98339e23239c83c326175cef4dc62001e46f9160 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/tests/oracle.patch @@ -0,0 +1,24 @@ +diff --git a/.github/workflows/vimdoc.yaml b/.github/workflows/vimdoc.yaml +index 0d76bd51..38aff6fe 100644 +--- a/.github/workflows/vimdoc.yaml ++++ b/.github/workflows/vimdoc.yaml +@@ -26,9 +26,10 @@ jobs: + echo "${PWD}/emmylua_doc_cli/" >> $GITHUB_PATH + export PATH="${PWD}/emmylua_doc_cli/:${PATH}" + emmylua_doc_cli --version +- - name: Generate OPTIONS.md ++ - name: Generate OPTIONS.md and types + run: | + nvim --headless -l scripts/gen_options.lua ++ make gen + - name: Setup treesitter + run: | + mkdir -p ~/.local/share/nvim/site/pack/vendor/start +@@ -54,6 +55,6 @@ jobs: + git config user.email "actions@github" + git config user.name "Github Actions" + git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git +- git add doc OPTIONS.md ++ git add doc OPTIONS.md lua/fzf-lua/types.lua + # Only commit and push if we have changes + git diff --quiet && git diff --staged --quiet || (git commit -m "${COMMIT_MSG}"; git push origin HEAD:${GITHUB_REF}) diff --git a/tasks/ibhagwan__fzf-lua-2648/tests/test.sh b/tasks/ibhagwan__fzf-lua-2648/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..82c4e2d626d52af84cd1dcc4b7f0f9836f2ea2dc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace abacb0693d7a37de9e85e6fcb2d22d848cb75cef > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2648/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2648/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2648/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2649/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2649/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee47502feb8379bd6fb0a38b72cd12911ac67b73 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8f5a5ae708451adc3e2ac4d965ac3452dc3ce5a6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8f5a5ae708451adc3e2ac4d965ac3452dc3ce5a6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8f5a5ae708451adc3e2ac4d965ac3452dc3ce5a6 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2649/instruction.md b/tasks/ibhagwan__fzf-lua-2649/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96c291a0643b8bf61245a92d7b26634c632c0ff6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci: nvim 0.10+ have builtin markdown parsers/queries + +## Description + + + +## Summary by CodeRabbit + +## Release Notes + +* **Chores** + * Optimized documentation generation pipeline for improved build efficiency. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f5a5ae70845`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2649/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2649/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6ae7d80c2845bd20b53beb2932f0d0ae52175b7a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/.github/workflows/vimdoc.yaml b/.github/workflows/vimdoc.yaml +index 38aff6fe..454a6df6 100644 +--- a/.github/workflows/vimdoc.yaml ++++ b/.github/workflows/vimdoc.yaml +@@ -30,17 +30,10 @@ jobs: + run: | + nvim --headless -l scripts/gen_options.lua + make gen +- - name: Setup treesitter ++ - name: Generating vimdoc + run: | + mkdir -p ~/.local/share/nvim/site/pack/vendor/start + git clone --depth 1 https://github.com/ibhagwan/ts-vimdoc.nvim ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim +- git clone --depth 1 https://github.com/nvim-treesitter/nvim-treesitter ~/.local/share/nvim/site/pack/vendor/start/nvim-treesitter +- - name: Build parser +- run: | +- export PACKPATH=$HOME/.local/share/nvim/site +- nvim --headless -u ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim/scripts/init.lua -c "TSUpdateSync markdown" -c "TSUpdateSync markdown_inline" -c "qa" +- - name: Generating vimdoc +- run: | + export PATH="${PWD}/build/:${PATH}" + export PACKPATH=$HOME/.local/share/nvim/site + nvim --headless -u ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim/scripts/init.lua -c "lua require('ts-vimdoc').docgen({input_file='README.md', output_file='doc/fzf-lua.txt', project_name='fzf-lua', version='For Neovim >= 0.9.0'})" -c "qa" diff --git a/tasks/ibhagwan__fzf-lua-2649/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2649/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2649/task.toml b/tasks/ibhagwan__fzf-lua-2649/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..17f363da9b74a2053faacb3935c18852daec8d11 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2649" +description = "ci: nvim 0.10+ have builtin markdown parsers/queries" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "8f5a5ae708451adc3e2ac4d965ac3452dc3ce5a6" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2649" +source_access = "auto" +built_at = "2026-11-16T16:09:56.025762+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3c7bfe9d2bace6b0b52bf2e98827ea7833f59e262c2ab976d85e4b6cbf2570a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-05T12:20:58Z" +diff_format = "unified" +context_files = [ + ".github/workflows/vimdoc.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[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:01.036421+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:280a592621528e30b15b92a6095a0477215e105e168c986db8ed66948ee706cc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2649/tests/capture.py b/tasks/ibhagwan__fzf-lua-2649/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2649/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2649/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96c291a0643b8bf61245a92d7b26634c632c0ff6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci: nvim 0.10+ have builtin markdown parsers/queries + +## Description + + + +## Summary by CodeRabbit + +## Release Notes + +* **Chores** + * Optimized documentation generation pipeline for improved build efficiency. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f5a5ae70845`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2649/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2649/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6ae7d80c2845bd20b53beb2932f0d0ae52175b7a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/.github/workflows/vimdoc.yaml b/.github/workflows/vimdoc.yaml +index 38aff6fe..454a6df6 100644 +--- a/.github/workflows/vimdoc.yaml ++++ b/.github/workflows/vimdoc.yaml +@@ -30,17 +30,10 @@ jobs: + run: | + nvim --headless -l scripts/gen_options.lua + make gen +- - name: Setup treesitter ++ - name: Generating vimdoc + run: | + mkdir -p ~/.local/share/nvim/site/pack/vendor/start + git clone --depth 1 https://github.com/ibhagwan/ts-vimdoc.nvim ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim +- git clone --depth 1 https://github.com/nvim-treesitter/nvim-treesitter ~/.local/share/nvim/site/pack/vendor/start/nvim-treesitter +- - name: Build parser +- run: | +- export PACKPATH=$HOME/.local/share/nvim/site +- nvim --headless -u ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim/scripts/init.lua -c "TSUpdateSync markdown" -c "TSUpdateSync markdown_inline" -c "qa" +- - name: Generating vimdoc +- run: | + export PATH="${PWD}/build/:${PATH}" + export PACKPATH=$HOME/.local/share/nvim/site + nvim --headless -u ~/.local/share/nvim/site/pack/vendor/start/ts-vimdoc.nvim/scripts/init.lua -c "lua require('ts-vimdoc').docgen({input_file='README.md', output_file='doc/fzf-lua.txt', project_name='fzf-lua', version='For Neovim >= 0.9.0'})" -c "qa" diff --git a/tasks/ibhagwan__fzf-lua-2649/tests/test.sh b/tasks/ibhagwan__fzf-lua-2649/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab0f993a68e053d807897303aa54ed517459868a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8f5a5ae708451adc3e2ac4d965ac3452dc3ce5a6 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2649/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2649/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2649/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2651/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2651/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1729242e250535c498340b4ea59ca0d23e7608c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9f0432fdd7825ab163520045831a40b6df82ea28 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9f0432fdd7825ab163520045831a40b6df82ea28 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9f0432fdd7825ab163520045831a40b6df82ea28 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2651/instruction.md b/tasks/ibhagwan__fzf-lua-2651/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15d1000d3c45bd456d893adeaf1ed3c48c8f0aed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: check if winid is valid before using it + +## Description + +If the window with id `winid` is closed before this function is called (may happen when opening fzf-lua from a `mini.files` buffer, for example), `api.nvim_set_current_win()` throws an error. + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved window restoration validation to ensure both source and target window identifiers are valid before performing operations. This prevents potential errors and edge case failures when managing multiple windows, enhancing stability and reliability in window focus restoration scenarios. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9f0432fdd782`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2651/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2651/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e5542033f38245570580231bcf9cfde2d5200929 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 5efc061d..515f0f23 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1143,12 +1143,18 @@ end + ---@param winid? integer + ---@param last_winid? integer + local restore_lastwin = function(winid, last_winid) +- if winid and last_winid and api.nvim_win_is_valid(last_winid) then +- utils.eventignore(function() +- api.nvim_set_current_win(last_winid) +- api.nvim_set_current_win(winid) +- end) ++ if ++ not winid ++ or not last_winid ++ or not api.nvim_win_is_valid(last_winid) ++ or not api.nvim_win_is_valid(winid) ++ then ++ return + end ++ utils.eventignore(function() ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) ++ end) + end + + ---@param buf? integer diff --git a/tasks/ibhagwan__fzf-lua-2651/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2651/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2651/task.toml b/tasks/ibhagwan__fzf-lua-2651/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..451cf513517b7a370ff343e344f2987edc460f1c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2651" +description = "fix: check if winid is valid before using it" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "9f0432fdd7825ab163520045831a40b6df82ea28" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2651" +source_access = "auto" +built_at = "2026-11-16T16:09:56.024390+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:18037eb35c89f626fec40b16f89092ba4617d0f1f8631b1b3afe6486bb697986" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-08T21:09:52Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[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:01.036908+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9e01784254d09269e1e2bb74d37e3e92b489507680a59b2e9747e989f434cd9f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2651/tests/capture.py b/tasks/ibhagwan__fzf-lua-2651/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2651/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2651/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15d1000d3c45bd456d893adeaf1ed3c48c8f0aed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: check if winid is valid before using it + +## Description + +If the window with id `winid` is closed before this function is called (may happen when opening fzf-lua from a `mini.files` buffer, for example), `api.nvim_set_current_win()` throws an error. + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved window restoration validation to ensure both source and target window identifiers are valid before performing operations. This prevents potential errors and edge case failures when managing multiple windows, enhancing stability and reliability in window focus restoration scenarios. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9f0432fdd782`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2651/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2651/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e5542033f38245570580231bcf9cfde2d5200929 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 5efc061d..515f0f23 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1143,12 +1143,18 @@ end + ---@param winid? integer + ---@param last_winid? integer + local restore_lastwin = function(winid, last_winid) +- if winid and last_winid and api.nvim_win_is_valid(last_winid) then +- utils.eventignore(function() +- api.nvim_set_current_win(last_winid) +- api.nvim_set_current_win(winid) +- end) ++ if ++ not winid ++ or not last_winid ++ or not api.nvim_win_is_valid(last_winid) ++ or not api.nvim_win_is_valid(winid) ++ then ++ return + end ++ utils.eventignore(function() ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) ++ end) + end + + ---@param buf? integer diff --git a/tasks/ibhagwan__fzf-lua-2651/tests/test.sh b/tasks/ibhagwan__fzf-lua-2651/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..149f7afc57fe6f0d34876d466eaeabd67b4cd158 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9f0432fdd7825ab163520045831a40b6df82ea28 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2651/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2651/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2651/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2652/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2652/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..84c7d0c15089827b857b9c902eaaed4858f8dd3e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 657c1bbb7357c61e26a20d868b53a460b05c18c0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 657c1bbb7357c61e26a20d868b53a460b05c18c0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 657c1bbb7357c61e26a20d868b53a460b05c18c0 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2652/instruction.md b/tasks/ibhagwan__fzf-lua-2652/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26f44926d4a779c59e6675390e0afa1207243f7c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat(preview): builtin can list directory content + +## Description + +The builtin preview shows this message when a directory is selected: +``` +Preview is not supported for binary files. +``` +In my use case I made it list the directory's content, so I might as well contribute this back if you feel like it's a good behaviour to add. + +I'm no nvim lua expert so there might be a better way to list a directory content? + + +## Summary by CodeRabbit + +* **New Features** + * Directory preview now shows a readable listing of folder contents in the preview pane. +* **Bug Fixes** + * If directory listing fails, a clear "Preview is not supported for this directory." message is shown. +* **Unchanged** + * Preview behavior for non-directories (binary files, size limits, and missing stat) remains the same. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `657c1bbb7357`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2652/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2652/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fd13490a0a9e3fe0c21290e02f12739183e80779 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 344ad2d2..9a36f846 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1111,6 +1111,10 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + local fs_stat = entry.path and uv.fs_stat(entry.path) + if not fs_stat then + lines = { string.format("Unable to stat file %s", entry.path) } ++ elseif fs_stat.type == "directory" then ++ local cmd = utils._if_win({ "cmd.exe", "/c", "dir" }, { "ls", "-la" }) ++ table.insert(cmd, entry.path) ++ lines, _ = utils.io_systemlist(cmd) + elseif fs_stat.size > 0 and utils.perl_file_is_binary(entry.path) then + lines = { "Preview is not supported for binary files." } + elseif tonumber(self.limit_b) > 0 and fs_stat.size > self.limit_b then diff --git a/tasks/ibhagwan__fzf-lua-2652/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2652/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2652/task.toml b/tasks/ibhagwan__fzf-lua-2652/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecaaf993be06e76c714f36b2c1487abade53bfbd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2652" +description = "feat(preview): builtin can list directory content" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "657c1bbb7357c61e26a20d868b53a460b05c18c0" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2652" +source_access = "auto" +built_at = "2026-11-16T16:09:56.022934+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:58223f2b70e44d1024631e05d359a07a340b041191db48e9e66854de520be898" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-12T09:32:10Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.037382+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c645d463f7766ecf3763a2dc8c91f850d10e2b26bbf6279ef233426e1b0b022e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2652/tests/capture.py b/tasks/ibhagwan__fzf-lua-2652/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2652/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2652/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26f44926d4a779c59e6675390e0afa1207243f7c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat(preview): builtin can list directory content + +## Description + +The builtin preview shows this message when a directory is selected: +``` +Preview is not supported for binary files. +``` +In my use case I made it list the directory's content, so I might as well contribute this back if you feel like it's a good behaviour to add. + +I'm no nvim lua expert so there might be a better way to list a directory content? + + +## Summary by CodeRabbit + +* **New Features** + * Directory preview now shows a readable listing of folder contents in the preview pane. +* **Bug Fixes** + * If directory listing fails, a clear "Preview is not supported for this directory." message is shown. +* **Unchanged** + * Preview behavior for non-directories (binary files, size limits, and missing stat) remains the same. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `657c1bbb7357`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2652/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2652/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fd13490a0a9e3fe0c21290e02f12739183e80779 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 344ad2d2..9a36f846 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1111,6 +1111,10 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + local fs_stat = entry.path and uv.fs_stat(entry.path) + if not fs_stat then + lines = { string.format("Unable to stat file %s", entry.path) } ++ elseif fs_stat.type == "directory" then ++ local cmd = utils._if_win({ "cmd.exe", "/c", "dir" }, { "ls", "-la" }) ++ table.insert(cmd, entry.path) ++ lines, _ = utils.io_systemlist(cmd) + elseif fs_stat.size > 0 and utils.perl_file_is_binary(entry.path) then + lines = { "Preview is not supported for binary files." } + elseif tonumber(self.limit_b) > 0 and fs_stat.size > self.limit_b then diff --git a/tasks/ibhagwan__fzf-lua-2652/tests/test.sh b/tasks/ibhagwan__fzf-lua-2652/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d18688a1a69e13369cd05aecd155513e3c32ab9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 657c1bbb7357c61e26a20d868b53a460b05c18c0 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2652/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2652/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2652/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2662/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2662/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a50634e8b071f38de8f86d0780ade12c7710ed71 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a16c537afcda722ac1238ff0feefc25d7bc0bf9c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a16c537afcda722ac1238ff0feefc25d7bc0bf9c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a16c537afcda722ac1238ff0feefc25d7bc0bf9c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2662/instruction.md b/tasks/ibhagwan__fzf-lua-2662/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..785beea763e818ceacf027472d13985492409490 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(utils): hide profile should not inherit default + +## Description + +fix #2661 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed profile loading behavior to prevent automatic injection of the default profile when using the "hide" profile option. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a16c537afcda`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2662/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2662/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ec6be857a5b13a7e8cb6dee9bbf33098c1684a61 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index b2c21c09..16cf9e9b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -979,10 +979,6 @@ function M.load_profiles(profiles, silent) + profiles = type(profiles) == "table" and profiles + or type(profiles) == "string" and { profiles } + or {} +- -- If the use specified only the "hide" profile, inherit the defaults +- if #profiles == 1 and profiles[1] == "hide" then +- table.insert(profiles, 1, "default") +- end + for _, profile in ipairs(profiles) do + -- backward compat, renamed "borderless_full" > "borderless-full" + if profile == "borderless_full" then profile = "borderless-full" end diff --git a/tasks/ibhagwan__fzf-lua-2662/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2662/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2662/task.toml b/tasks/ibhagwan__fzf-lua-2662/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..33c42b7737cdbdb14f15a55e714d80f767c4960e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2662" +description = "fix(utils): hide profile should not inherit default" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "a16c537afcda722ac1238ff0feefc25d7bc0bf9c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2662" +source_access = "auto" +built_at = "2026-11-16T16:09:56.021659+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4dd665576e9aaed422e937444aeb51cb95e67d9ae6b07873cf946fd1f59cea2a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-12T20:58:40Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.037851+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6ec241c97ed920a9bb98593ade21d0967f268fb4749ec7fb436f113938e48c88" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2662/tests/capture.py b/tasks/ibhagwan__fzf-lua-2662/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2662/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2662/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..785beea763e818ceacf027472d13985492409490 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(utils): hide profile should not inherit default + +## Description + +fix #2661 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed profile loading behavior to prevent automatic injection of the default profile when using the "hide" profile option. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a16c537afcda`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2662/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2662/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ec6be857a5b13a7e8cb6dee9bbf33098c1684a61 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index b2c21c09..16cf9e9b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -979,10 +979,6 @@ function M.load_profiles(profiles, silent) + profiles = type(profiles) == "table" and profiles + or type(profiles) == "string" and { profiles } + or {} +- -- If the use specified only the "hide" profile, inherit the defaults +- if #profiles == 1 and profiles[1] == "hide" then +- table.insert(profiles, 1, "default") +- end + for _, profile in ipairs(profiles) do + -- backward compat, renamed "borderless_full" > "borderless-full" + if profile == "borderless_full" then profile = "borderless-full" end diff --git a/tasks/ibhagwan__fzf-lua-2662/tests/test.sh b/tasks/ibhagwan__fzf-lua-2662/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c6734bec02e608227d9487343e55a08ca5206539 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a16c537afcda722ac1238ff0feefc25d7bc0bf9c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2662/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2662/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2662/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2663/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2663/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d87478aa48d254fee6b467f1c7490f0441225c61 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ae2e0bc885858188ef4725a02dfd5725cfc58ba2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ae2e0bc885858188ef4725a02dfd5725cfc58ba2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ae2e0bc885858188ef4725a02dfd5725cfc58ba2 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2663/instruction.md b/tasks/ibhagwan__fzf-lua-2663/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc30280d3e667754baf7abafbf0dcaf63f7c8a7b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** fix(help): use action header as desc fallback in F1 keybind help + +## Description + +## Problem + +The F1 help window shows `table:0x...` for actions that define a `header` field but not `desc`, when the action's `fn` is an anonymous function not registered in the helpstr table. + +The `get_desc` function in `win/help.lua` resolves descriptions via this chain: + +``` +v.desc -> helpstr(v[1]) -> helpstr(v.fn) -> tostring(v) +``` + +For actions like `git.commits` `ctrl-d` (which has `header = "git diff"` but no `desc`, and uses an anonymous `fn`), every step before `tostring(v)` returns `nil`, so the help window displays the unhelpful `table:0x...` string. + +## Fix + +Add `v.header` as a fallback between `config.get_action_helpstr(v.fn)` and `tostring(v)`: + +```lua +return v.desc or config.get_action_helpstr(v[1]) or config.get_action_helpstr(v.fn) or + v.header or tostring(v) +``` + +This is consistent with how `header` is already used as a human-readable label for actions (it populates the `--header` line at the top of pickers). + +## Affected actions + +6 built-in actions in `defaults.lua` that have `header` but no `desc`: + +| Picker | Key | Header (now shown in F1) | +|---|---|---| +| `git.diff` | `ctrl-q` | `"git commits"` | +| `git.commits` | `ctrl-d` | `"git diff"` | +| `spellcheck` | `ctrl-s` | `"spell suggest"` | +| `serverlist` | `ctrl-o` | `"spawn"` | +| `serverlist` | `ctrl-x` | `"kill"` | +| `serverlist` | `ctrl-r` | `"reload"` | + +Actions with `header = false` (used to suppress the header line) are unaffected since `false` is falsy and the chain continues to `tostring(v)`. + +## Before / After + +**Before:** F1 help shows `table: 0x56327a5de490` for these keybinds. + +**After:** F1 help shows the `header` string (e.g. `"git diff"`, `"spell suggest"`). + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Help/description text is now generated consistently so preview keymaps and action descriptions display correctly and reliably. + +* **New Features** + * Help text resolution supports richer action specifications (including an optional header), improving how actions are labeled and presented in UI lists. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ae2e0bc88585`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2663/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2663/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c863ead701dfb3bc5242898bf5b841ec198c4d21 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/solution/patch.diff @@ -0,0 +1,119 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 7159e63c..43b7d74d 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -1063,8 +1063,14 @@ M.set_action_helpstr = function(fn, helpstr) + M._action_to_helpstr[fn] = helpstr + end + +-M.get_action_helpstr = function(fn) +- return M._action_to_helpstr[fn] ++---@param v fzf-lua.ActionSpec|any ++---@return string ++M.get_action_helpstr = function(v) ++ local t = M._action_to_helpstr ++ if type(v) ~= "table" or t[v] then return t[v] or tostring(v) end ++ local res = v.desc or t[v[1]] or t[v.fn] or v.header ++ if res then return res end ++ return type(v[1]) == "string" and v[1] or tostring(v) + end + + M._action_to_helpstr = { +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 055eea5d..03da50da 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -1020,7 +1020,7 @@ M.convert_reload_actions = function(reload_cmd, opts) + M.can_transform(opts) and "transform" or "reload", -- contents is not "cmd" but "reload:cmd" + reload_cmd, + type(v.postfix) == "string" and v.postfix or ""), +- desc = v.desc or config.get_action_helpstr(v.fn) ++ desc = config.get_action_helpstr(v) + } + end + end +@@ -1075,7 +1075,7 @@ M.convert_exec_silent_actions = function(opts) + or string.format(":%s", cmd), + -- can't use postfix since we use "execute-silent:..." + has_fzf036 and type(v.postfix) == "string" and v.postfix or ""), +- desc = v.desc or config.get_action_helpstr(v.fn) ++ desc = config.get_action_helpstr(v) + } + end + end +diff --git a/lua/fzf-lua/profiles/hide.lua b/lua/fzf-lua/profiles/hide.lua +index 737e27c9..22944e68 100644 +--- a/lua/fzf-lua/profiles/hide.lua ++++ b/lua/fzf-lua/profiles/hide.lua +@@ -73,7 +73,7 @@ return { + then + local fn = act.fn + act.exec_silent = true +- act.desc = act.desc or fzf.config.get_action_helpstr(fn) ++ act.desc = act.desc or fzf.config.get_action_helpstr(act) + act.fn = function(...) + fzf.hide() + if fn then fn(...) end +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index a6d749c4..83cc5841 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -55,6 +55,7 @@ local FzfLua = require("fzf-lua") + ---@field reload? boolean + ---@field field_index? string + ---@field desc? string ++---@field header? string|false + ---@field prefix? string + ---@field postfix? string + ---@field reuse? boolean +diff --git a/lua/fzf-lua/win/help.lua b/lua/fzf-lua/win/help.lua +index d2225f24..906bfdec 100644 +--- a/lua/fzf-lua/win/help.lua ++++ b/lua/fzf-lua/win/help.lua +@@ -47,17 +47,13 @@ function M.toggle(keymap, actions, hls, zindex, preview_keymaps, preview_mode, h + for _, m in ipairs({ "builtin", "fzf" }) do + for k, v in pairs(keymap[m]) do + if not keymap_ignore[k] then +- -- value can be defined as a table with addl properties (help string) +- if type(v) == "table" then +- v = v.desc or v[1] +- end ++ v = config.get_action_helpstr(v) + -- only add preview keybinds respective of + -- the current preview mode +- if v and (not preview_keymaps[v] or m == preview_mode) then ++ if not preview_keymaps[v] or m == preview_mode then + if m == "builtin" then + k = utils.neovim_bind_to_fzf(k) + end +- v = type(v) == "function" and config.get_action_helpstr(v) or tostring(v) + table.insert(keymaps, + format_bind(m, k, v, opts.mode_width, opts.keybind_width, opts.name_width)) + end +@@ -65,25 +61,12 @@ function M.toggle(keymap, actions, hls, zindex, preview_keymaps, preview_mode, h + end + end + +- ---TODO: we can always parse the action into table to avoid this duplicated logic +- ---(e.g. profile/hide.lua, config.lua) +- ---@param v fzf-lua.ActionSpec +- ---@return string? +- local get_desc = function(v) +- if type(v) == "table" then +- return v.desc or config.get_action_helpstr(v[1]) or config.get_action_helpstr(v.fn) or +- tostring(v) +- elseif v then +- return config.get_action_helpstr(v) or tostring(v) +- end +- end +- + -- action keymaps + if actions then + for k, v in pairs(actions) do + if v then -- skips 'v == false' + if k == "default" then k = "enter" end +- local desc = get_desc(v) ++ local desc = config.get_action_helpstr(v) + table.insert(keymaps, + format_bind("action", k, + ("%s"):format(desc):gsub(" ", ""), diff --git a/tasks/ibhagwan__fzf-lua-2663/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2663/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2663/task.toml b/tasks/ibhagwan__fzf-lua-2663/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a56809baa8ed508190fbfb00ffb31a2d9472417 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2663" +description = "fix(help): use action header as desc fallback in F1 keybind help" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "ae2e0bc885858188ef4725a02dfd5725cfc58ba2" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2663" +source_access = "auto" +built_at = "2026-11-16T16:09:56.018342+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:107f114418e20a3792592a9df42af7c41b91db54d6d7ded7224b923ae0054ef9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-15T15:51:37Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/config.lua", + "lua/fzf-lua/core.lua", + "lua/fzf-lua/profiles/hide.lua", + "lua/fzf-lua/types.lua", + "lua/fzf-lua/win/help.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 40 +difficulty = "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:01.038336+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f47534278d4911a7ea1bdc0a33ddd666edefd3058dd3ceb34c5d28cf7a3440c2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2663/tests/capture.py b/tasks/ibhagwan__fzf-lua-2663/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2663/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2663/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc30280d3e667754baf7abafbf0dcaf63f7c8a7b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/tests/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** fix(help): use action header as desc fallback in F1 keybind help + +## Description + +## Problem + +The F1 help window shows `table:0x...` for actions that define a `header` field but not `desc`, when the action's `fn` is an anonymous function not registered in the helpstr table. + +The `get_desc` function in `win/help.lua` resolves descriptions via this chain: + +``` +v.desc -> helpstr(v[1]) -> helpstr(v.fn) -> tostring(v) +``` + +For actions like `git.commits` `ctrl-d` (which has `header = "git diff"` but no `desc`, and uses an anonymous `fn`), every step before `tostring(v)` returns `nil`, so the help window displays the unhelpful `table:0x...` string. + +## Fix + +Add `v.header` as a fallback between `config.get_action_helpstr(v.fn)` and `tostring(v)`: + +```lua +return v.desc or config.get_action_helpstr(v[1]) or config.get_action_helpstr(v.fn) or + v.header or tostring(v) +``` + +This is consistent with how `header` is already used as a human-readable label for actions (it populates the `--header` line at the top of pickers). + +## Affected actions + +6 built-in actions in `defaults.lua` that have `header` but no `desc`: + +| Picker | Key | Header (now shown in F1) | +|---|---|---| +| `git.diff` | `ctrl-q` | `"git commits"` | +| `git.commits` | `ctrl-d` | `"git diff"` | +| `spellcheck` | `ctrl-s` | `"spell suggest"` | +| `serverlist` | `ctrl-o` | `"spawn"` | +| `serverlist` | `ctrl-x` | `"kill"` | +| `serverlist` | `ctrl-r` | `"reload"` | + +Actions with `header = false` (used to suppress the header line) are unaffected since `false` is falsy and the chain continues to `tostring(v)`. + +## Before / After + +**Before:** F1 help shows `table: 0x56327a5de490` for these keybinds. + +**After:** F1 help shows the `header` string (e.g. `"git diff"`, `"spell suggest"`). + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Help/description text is now generated consistently so preview keymaps and action descriptions display correctly and reliably. + +* **New Features** + * Help text resolution supports richer action specifications (including an optional header), improving how actions are labeled and presented in UI lists. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ae2e0bc88585`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2663/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2663/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c863ead701dfb3bc5242898bf5b841ec198c4d21 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/tests/oracle.patch @@ -0,0 +1,119 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 7159e63c..43b7d74d 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -1063,8 +1063,14 @@ M.set_action_helpstr = function(fn, helpstr) + M._action_to_helpstr[fn] = helpstr + end + +-M.get_action_helpstr = function(fn) +- return M._action_to_helpstr[fn] ++---@param v fzf-lua.ActionSpec|any ++---@return string ++M.get_action_helpstr = function(v) ++ local t = M._action_to_helpstr ++ if type(v) ~= "table" or t[v] then return t[v] or tostring(v) end ++ local res = v.desc or t[v[1]] or t[v.fn] or v.header ++ if res then return res end ++ return type(v[1]) == "string" and v[1] or tostring(v) + end + + M._action_to_helpstr = { +diff --git a/lua/fzf-lua/core.lua b/lua/fzf-lua/core.lua +index 055eea5d..03da50da 100644 +--- a/lua/fzf-lua/core.lua ++++ b/lua/fzf-lua/core.lua +@@ -1020,7 +1020,7 @@ M.convert_reload_actions = function(reload_cmd, opts) + M.can_transform(opts) and "transform" or "reload", -- contents is not "cmd" but "reload:cmd" + reload_cmd, + type(v.postfix) == "string" and v.postfix or ""), +- desc = v.desc or config.get_action_helpstr(v.fn) ++ desc = config.get_action_helpstr(v) + } + end + end +@@ -1075,7 +1075,7 @@ M.convert_exec_silent_actions = function(opts) + or string.format(":%s", cmd), + -- can't use postfix since we use "execute-silent:..." + has_fzf036 and type(v.postfix) == "string" and v.postfix or ""), +- desc = v.desc or config.get_action_helpstr(v.fn) ++ desc = config.get_action_helpstr(v) + } + end + end +diff --git a/lua/fzf-lua/profiles/hide.lua b/lua/fzf-lua/profiles/hide.lua +index 737e27c9..22944e68 100644 +--- a/lua/fzf-lua/profiles/hide.lua ++++ b/lua/fzf-lua/profiles/hide.lua +@@ -73,7 +73,7 @@ return { + then + local fn = act.fn + act.exec_silent = true +- act.desc = act.desc or fzf.config.get_action_helpstr(fn) ++ act.desc = act.desc or fzf.config.get_action_helpstr(act) + act.fn = function(...) + fzf.hide() + if fn then fn(...) end +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index a6d749c4..83cc5841 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -55,6 +55,7 @@ local FzfLua = require("fzf-lua") + ---@field reload? boolean + ---@field field_index? string + ---@field desc? string ++---@field header? string|false + ---@field prefix? string + ---@field postfix? string + ---@field reuse? boolean +diff --git a/lua/fzf-lua/win/help.lua b/lua/fzf-lua/win/help.lua +index d2225f24..906bfdec 100644 +--- a/lua/fzf-lua/win/help.lua ++++ b/lua/fzf-lua/win/help.lua +@@ -47,17 +47,13 @@ function M.toggle(keymap, actions, hls, zindex, preview_keymaps, preview_mode, h + for _, m in ipairs({ "builtin", "fzf" }) do + for k, v in pairs(keymap[m]) do + if not keymap_ignore[k] then +- -- value can be defined as a table with addl properties (help string) +- if type(v) == "table" then +- v = v.desc or v[1] +- end ++ v = config.get_action_helpstr(v) + -- only add preview keybinds respective of + -- the current preview mode +- if v and (not preview_keymaps[v] or m == preview_mode) then ++ if not preview_keymaps[v] or m == preview_mode then + if m == "builtin" then + k = utils.neovim_bind_to_fzf(k) + end +- v = type(v) == "function" and config.get_action_helpstr(v) or tostring(v) + table.insert(keymaps, + format_bind(m, k, v, opts.mode_width, opts.keybind_width, opts.name_width)) + end +@@ -65,25 +61,12 @@ function M.toggle(keymap, actions, hls, zindex, preview_keymaps, preview_mode, h + end + end + +- ---TODO: we can always parse the action into table to avoid this duplicated logic +- ---(e.g. profile/hide.lua, config.lua) +- ---@param v fzf-lua.ActionSpec +- ---@return string? +- local get_desc = function(v) +- if type(v) == "table" then +- return v.desc or config.get_action_helpstr(v[1]) or config.get_action_helpstr(v.fn) or +- tostring(v) +- elseif v then +- return config.get_action_helpstr(v) or tostring(v) +- end +- end +- + -- action keymaps + if actions then + for k, v in pairs(actions) do + if v then -- skips 'v == false' + if k == "default" then k = "enter" end +- local desc = get_desc(v) ++ local desc = config.get_action_helpstr(v) + table.insert(keymaps, + format_bind("action", k, + ("%s"):format(desc):gsub(" ", ""), diff --git a/tasks/ibhagwan__fzf-lua-2663/tests/test.sh b/tasks/ibhagwan__fzf-lua-2663/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..46b55d9d9b7103355e0dfbf3b6f1715196fcbaaf --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ae2e0bc885858188ef4725a02dfd5725cfc58ba2 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2663/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2663/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2663/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2667/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2667/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3913944876bd30c9e82a56b938cc95fe5f540dfe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4be0a6923a64dc411489b57b77a6bf6f30404e66 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4be0a6923a64dc411489b57b77a6bf6f30404e66 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4be0a6923a64dc411489b57b77a6bf6f30404e66 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2667/instruction.md b/tasks/ibhagwan__fzf-lua-2667/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21198f978dbb65258fc79fba5d111a725a0f1806 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** misc previewer fixes + +## Description + +- **fix(highlights): force verbose=0 to show correct info** +- **feat(previewer): improve vimscript keymap preview** +- **feat(previewer): improve autocmds preview** +- **fix(actions): autocmd "" hacks** + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed path normalization and sentinel handling in file actions. + * Improved autocmd preview rendering and fallback when source file info is unavailable. + +* **Improvements** + * Enhanced keymap lookup and previews (now shown as Lua content for readability). + * More robust colorscheme highlight detection. +* **Documentation** + * Expanded keymap entry type to include buffer/file fields. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4be0a6923a64`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2667/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2667/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a13e9c410aefb52128b2bbcfed5db00081ad3662 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/solution/patch.diff @@ -0,0 +1,184 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 74b65c77..78cd1a1b 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -204,8 +204,6 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + (function() + -- Lua 5.1 goto compatiblity hack (function wrap) + local entry = path.entry_to_file(sel, opts, opts._uri) +- -- "" could be set by `autocmds` +- if entry.path == "" then return end + local fullpath = entry.bufname + or entry.uri and entry.uri:match("^[%a%-]+://(.*)") + or entry.path +@@ -216,17 +214,19 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + -- technically we should never get to the `uv.cwd()` fallback + fullpath = path.join({ opts.cwd or opts._cwd or utils.cwd(), fullpath }) + end ++ -- Always open files relative to the current win/tab cwd (#1854) ++ -- We normalize the path or Windows will fail with directories starting ++ -- with special characters, for example "C:\app\(web)" will be translated ++ -- by neovim to "c:\app(web)" (#1082) ++ local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) ++ -- "" could be set by `autocmds` ++ if relpath == "" then return end + -- Can't be called from term window (for example, "reload" actions) due to + -- nvim_exec2(): Vim(normal):Can't re-enter normal mode from terminal mode + -- NOTE: we do not use `opts.__CTX.bufnr` as caller might be the fzf term + if not utils.is_term_buffer(0) then + vim.cmd("normal! m`") + end +- -- Always open files relative to the current win/tab cwd (#1854) +- -- We normalize the path or Windows will fail with directories starting +- -- with special characters, for example "C:\app\(web)" will be translated +- -- by neovim to "c:\app(web)" (#1082) +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + if bufedit then + local will_replace_curbuf = #vimcmd == 0 and not buf_edited(entry.bufnr, fullpath) + if will_replace_curbuf then +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 9a4d43c2..3deeaf1e 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -666,9 +666,8 @@ function M.jj_root(opts, noerr) + end + + ---@param str string +----@param opts fzf-lua.config.Resolved +----@return fzf-lua.path.Entry|fzf-lua.keymap.Entry +-function M.keymap_to_entry(str, opts) ++---@return fzf-lua.keymap.Entry ++function M.keymap_to_entry(str) + local valid_modes = { + n = true, + i = true, +@@ -680,21 +679,19 @@ function M.keymap_to_entry(str, opts) + if not mode or not keymap then return {} end + mode, keymap = vim.trim(mode), vim.trim(keymap) + mode = valid_modes[mode] and mode or "" -- only valid modes +- local out ---@type string[] +- local vmap, cmd = nil, string.format("verbose %smap %s", mode, keymap) +- -- Run in the context of the originating buffer or keympas might return +- -- "No mapping found" +- pcall(vim.api.nvim_buf_call, opts.__CTX.bufnr, function() +- out = utils.strsplit(vim.fn.execute(cmd), "\n") +- _, vmap = next(vim.tbl_map(function(x) return #x > 0 and x or nil end, out)) +- end) +- local entry +- for i = #out, 1, -1 do +- if out[i]:match(utils.lua_regex_escape(keymap)) then +- entry = out[i]:match("<.-:%s+(.*)>") ++ local vmap = vim.fn.maparg(keymap, mode, false, true) ++ if vmap.callback then ++ local info = debug.getinfo(vmap.callback) ++ if info and info.source then ++ return { path = info.source:gsub("^@", ""), line = info.linedefined } + end + end +- return entry and M.entry_to_file(entry, opts) or { mode = mode, key = keymap, vmap = vmap } or {} ++ local cmd = ("verb %smap %s"):format(mode, keymap) ++ local output = vim.split(vim.api.nvim_exec2(cmd, { output = true }).output, "\n") ++ local file, lnum = (output[#output] or ""):match("Last set from (.-) line (%d+)") ++ if file and lnum then return { path = vim.fs.normalize(file), line = utils.tointeger(lnum) or 1 } end ++ -- if entry then return M.entry_to_file(entry, opts) end ++ return { mode = mode, key = keymap, vmap = vim.inspect(vmap) } + end + + -- Minimal functionality so we can hijack during `vim.filetype.match` +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 71e3c148..d58f94f9 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1865,38 +1865,49 @@ function Previewer.autocmds:gen_winopts() + local winopts = { + wrap = true, + cursorline = false, +- number = false ++ number = false, + } + return vim.tbl_extend("keep", winopts, self.winopts) + end + + function Previewer.autocmds:parse_entry(entry_str) +- local entry = self.super:parse_entry(entry_str) +- if not entry.path or entry.path:sub(-6) ~= "" then ++ local entry = self.super.parse_entry(self, entry_str) ++ self._is_vimL_command = entry.path and entry.path:sub(-6) == "" ++ if not self._is_vimL_command then return entry end ++ local content = {} ++ local parts = vim.tbl_map(vim.trim, vim.split(entry_str, "│")) ++ local event, pattern, group, code = unpack(parts, 2) ++ content[#content + 1] = "autocmd " .. event .. (pattern ~= "" and (" " .. pattern) or "") ++ content[#content + 1] = "\\ " .. code ++ local cmd = ("verb au %s %s %s"):format(group, event, pattern) ++ local output = vim.split(api.nvim_exec2(cmd, { output = true }).output, "\n") ++ local file, lnum = (output[#output] or ""):match("Last set from (.-) line (%d+)") ++ if file and lnum then + self._is_vimL_command = false +- return entry ++ return { path = vim.fs.normalize(file), line = utils.tointeger(lnum) or 1 } + end +- self._is_vimL_command = true +- return { +- path = entry_str:match("[^:|]+│"), +- filetype = "vim", +- content = vim.split(assert(entry_str:match("[^│]+$")), "\n") +- } ++ if group ~= "" then ++ content = vim.tbl_map(function(s) return (" "):rep(fn.shiftwidth()) .. s end, content) ++ table.insert(content, 1, "augroup " .. group) ++ content[#content + 1] = "augroup END" ++ end ++ return { cache_key = false, filetype = "vim", content = content } + end + + ---@class fzf-lua.previewer.Keymaps : fzf-lua.previewer.BufferOrFile,{} + ---@field super fzf-lua.previewer.BufferOrFile,{} + Previewer.keymaps = Previewer.buffer_or_file:extend() + ++---@diagnostic disable-next-line: unused + ---@param entry_str string +----@return fzf-lua.buffer_or_file.Entry ++---@return fzf-lua.keymap.Entry + function Previewer.keymaps:parse_entry(entry_str) +- local entry = path.keymap_to_entry(entry_str, self.opts) ++ local entry = path.keymap_to_entry(entry_str) + if not entry.vmap then return entry end + return { +- filetype = "vim", ++ filetype = "lua", + title = string.format("%s:%s", entry.mode, entry.key), +- content = utils.strsplit(assert(entry.vmap:match("[^%s]+$")), "\n"), ++ content = utils.strsplit(entry.vmap, "\n"), + } + end + +diff --git a/lua/fzf-lua/providers/colorschemes.lua b/lua/fzf-lua/providers/colorschemes.lua +index 532180d1..ee39c453 100644 +--- a/lua/fzf-lua/providers/colorschemes.lua ++++ b/lua/fzf-lua/providers/colorschemes.lua +@@ -99,8 +99,9 @@ M.highlights = function(opts) + + local contents = function(cb) + local _, hl_dir = utils.ansi_from_hl("Directory", "foo") +- local highlights = +- utils.strsplit(vim.api.nvim_exec2("highlight", { output = true }).output, "\n") ++ local highlights = utils.with({ o = { verbose = 0 } }, function() ++ return utils.strsplit(vim.api.nvim_exec2("highlight", { output = true }).output, "\n") ++ end) + + local function add_entry(line, co) + local hl = line:match("^[^%s]+") +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 73256fce..5c54e8c8 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -37,7 +37,7 @@ local FzfLua = require("fzf-lua") + ---@field end_col? integer 1-based + ---@field open_term? boolean open_term for content (cmd always open_term) + +----@class fzf-lua.keymap.Entry ++---@class fzf-lua.keymap.Entry: fzf-lua.buffer_or_file.Entry + ---@field vmap string? + ---@field mode string? + ---@field key string? diff --git a/tasks/ibhagwan__fzf-lua-2667/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2667/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2667/task.toml b/tasks/ibhagwan__fzf-lua-2667/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c4379fdbdf30cfe80b4b56586d48a30da2e7d480 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2667" +description = "misc previewer fixes" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "4be0a6923a64dc411489b57b77a6bf6f30404e66" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2667" +source_access = "auto" +built_at = "2026-11-16T16:09:56.020232+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d65c87a9ccf54c6b25440e4a955e03e755ca13cf174b828d81f95845a5114cd0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-15T10:23:25Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/path.lua", + "lua/fzf-lua/previewer/builtin.lua", + "lua/fzf-lua/providers/colorschemes.lua", + "lua/fzf-lua/types.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 89 +difficulty = "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:01.038830+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8385edc284c683c143ad81de6f842b885cf198587d8fd09b52ef7c493813acc5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2667/tests/capture.py b/tasks/ibhagwan__fzf-lua-2667/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2667/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2667/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21198f978dbb65258fc79fba5d111a725a0f1806 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** misc previewer fixes + +## Description + +- **fix(highlights): force verbose=0 to show correct info** +- **feat(previewer): improve vimscript keymap preview** +- **feat(previewer): improve autocmds preview** +- **fix(actions): autocmd "" hacks** + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed path normalization and sentinel handling in file actions. + * Improved autocmd preview rendering and fallback when source file info is unavailable. + +* **Improvements** + * Enhanced keymap lookup and previews (now shown as Lua content for readability). + * More robust colorscheme highlight detection. +* **Documentation** + * Expanded keymap entry type to include buffer/file fields. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4be0a6923a64`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2667/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2667/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a13e9c410aefb52128b2bbcfed5db00081ad3662 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/tests/oracle.patch @@ -0,0 +1,184 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 74b65c77..78cd1a1b 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -204,8 +204,6 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + (function() + -- Lua 5.1 goto compatiblity hack (function wrap) + local entry = path.entry_to_file(sel, opts, opts._uri) +- -- "" could be set by `autocmds` +- if entry.path == "" then return end + local fullpath = entry.bufname + or entry.uri and entry.uri:match("^[%a%-]+://(.*)") + or entry.path +@@ -216,17 +214,19 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + -- technically we should never get to the `uv.cwd()` fallback + fullpath = path.join({ opts.cwd or opts._cwd or utils.cwd(), fullpath }) + end ++ -- Always open files relative to the current win/tab cwd (#1854) ++ -- We normalize the path or Windows will fail with directories starting ++ -- with special characters, for example "C:\app\(web)" will be translated ++ -- by neovim to "c:\app(web)" (#1082) ++ local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) ++ -- "" could be set by `autocmds` ++ if relpath == "" then return end + -- Can't be called from term window (for example, "reload" actions) due to + -- nvim_exec2(): Vim(normal):Can't re-enter normal mode from terminal mode + -- NOTE: we do not use `opts.__CTX.bufnr` as caller might be the fzf term + if not utils.is_term_buffer(0) then + vim.cmd("normal! m`") + end +- -- Always open files relative to the current win/tab cwd (#1854) +- -- We normalize the path or Windows will fail with directories starting +- -- with special characters, for example "C:\app\(web)" will be translated +- -- by neovim to "c:\app(web)" (#1082) +- local relpath = path.normalize(path.relative_to(fullpath, utils.cwd())) + if bufedit then + local will_replace_curbuf = #vimcmd == 0 and not buf_edited(entry.bufnr, fullpath) + if will_replace_curbuf then +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 9a4d43c2..3deeaf1e 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -666,9 +666,8 @@ function M.jj_root(opts, noerr) + end + + ---@param str string +----@param opts fzf-lua.config.Resolved +----@return fzf-lua.path.Entry|fzf-lua.keymap.Entry +-function M.keymap_to_entry(str, opts) ++---@return fzf-lua.keymap.Entry ++function M.keymap_to_entry(str) + local valid_modes = { + n = true, + i = true, +@@ -680,21 +679,19 @@ function M.keymap_to_entry(str, opts) + if not mode or not keymap then return {} end + mode, keymap = vim.trim(mode), vim.trim(keymap) + mode = valid_modes[mode] and mode or "" -- only valid modes +- local out ---@type string[] +- local vmap, cmd = nil, string.format("verbose %smap %s", mode, keymap) +- -- Run in the context of the originating buffer or keympas might return +- -- "No mapping found" +- pcall(vim.api.nvim_buf_call, opts.__CTX.bufnr, function() +- out = utils.strsplit(vim.fn.execute(cmd), "\n") +- _, vmap = next(vim.tbl_map(function(x) return #x > 0 and x or nil end, out)) +- end) +- local entry +- for i = #out, 1, -1 do +- if out[i]:match(utils.lua_regex_escape(keymap)) then +- entry = out[i]:match("<.-:%s+(.*)>") ++ local vmap = vim.fn.maparg(keymap, mode, false, true) ++ if vmap.callback then ++ local info = debug.getinfo(vmap.callback) ++ if info and info.source then ++ return { path = info.source:gsub("^@", ""), line = info.linedefined } + end + end +- return entry and M.entry_to_file(entry, opts) or { mode = mode, key = keymap, vmap = vmap } or {} ++ local cmd = ("verb %smap %s"):format(mode, keymap) ++ local output = vim.split(vim.api.nvim_exec2(cmd, { output = true }).output, "\n") ++ local file, lnum = (output[#output] or ""):match("Last set from (.-) line (%d+)") ++ if file and lnum then return { path = vim.fs.normalize(file), line = utils.tointeger(lnum) or 1 } end ++ -- if entry then return M.entry_to_file(entry, opts) end ++ return { mode = mode, key = keymap, vmap = vim.inspect(vmap) } + end + + -- Minimal functionality so we can hijack during `vim.filetype.match` +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 71e3c148..d58f94f9 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1865,38 +1865,49 @@ function Previewer.autocmds:gen_winopts() + local winopts = { + wrap = true, + cursorline = false, +- number = false ++ number = false, + } + return vim.tbl_extend("keep", winopts, self.winopts) + end + + function Previewer.autocmds:parse_entry(entry_str) +- local entry = self.super:parse_entry(entry_str) +- if not entry.path or entry.path:sub(-6) ~= "" then ++ local entry = self.super.parse_entry(self, entry_str) ++ self._is_vimL_command = entry.path and entry.path:sub(-6) == "" ++ if not self._is_vimL_command then return entry end ++ local content = {} ++ local parts = vim.tbl_map(vim.trim, vim.split(entry_str, "│")) ++ local event, pattern, group, code = unpack(parts, 2) ++ content[#content + 1] = "autocmd " .. event .. (pattern ~= "" and (" " .. pattern) or "") ++ content[#content + 1] = "\\ " .. code ++ local cmd = ("verb au %s %s %s"):format(group, event, pattern) ++ local output = vim.split(api.nvim_exec2(cmd, { output = true }).output, "\n") ++ local file, lnum = (output[#output] or ""):match("Last set from (.-) line (%d+)") ++ if file and lnum then + self._is_vimL_command = false +- return entry ++ return { path = vim.fs.normalize(file), line = utils.tointeger(lnum) or 1 } + end +- self._is_vimL_command = true +- return { +- path = entry_str:match("[^:|]+│"), +- filetype = "vim", +- content = vim.split(assert(entry_str:match("[^│]+$")), "\n") +- } ++ if group ~= "" then ++ content = vim.tbl_map(function(s) return (" "):rep(fn.shiftwidth()) .. s end, content) ++ table.insert(content, 1, "augroup " .. group) ++ content[#content + 1] = "augroup END" ++ end ++ return { cache_key = false, filetype = "vim", content = content } + end + + ---@class fzf-lua.previewer.Keymaps : fzf-lua.previewer.BufferOrFile,{} + ---@field super fzf-lua.previewer.BufferOrFile,{} + Previewer.keymaps = Previewer.buffer_or_file:extend() + ++---@diagnostic disable-next-line: unused + ---@param entry_str string +----@return fzf-lua.buffer_or_file.Entry ++---@return fzf-lua.keymap.Entry + function Previewer.keymaps:parse_entry(entry_str) +- local entry = path.keymap_to_entry(entry_str, self.opts) ++ local entry = path.keymap_to_entry(entry_str) + if not entry.vmap then return entry end + return { +- filetype = "vim", ++ filetype = "lua", + title = string.format("%s:%s", entry.mode, entry.key), +- content = utils.strsplit(assert(entry.vmap:match("[^%s]+$")), "\n"), ++ content = utils.strsplit(entry.vmap, "\n"), + } + end + +diff --git a/lua/fzf-lua/providers/colorschemes.lua b/lua/fzf-lua/providers/colorschemes.lua +index 532180d1..ee39c453 100644 +--- a/lua/fzf-lua/providers/colorschemes.lua ++++ b/lua/fzf-lua/providers/colorschemes.lua +@@ -99,8 +99,9 @@ M.highlights = function(opts) + + local contents = function(cb) + local _, hl_dir = utils.ansi_from_hl("Directory", "foo") +- local highlights = +- utils.strsplit(vim.api.nvim_exec2("highlight", { output = true }).output, "\n") ++ local highlights = utils.with({ o = { verbose = 0 } }, function() ++ return utils.strsplit(vim.api.nvim_exec2("highlight", { output = true }).output, "\n") ++ end) + + local function add_entry(line, co) + local hl = line:match("^[^%s]+") +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 73256fce..5c54e8c8 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -37,7 +37,7 @@ local FzfLua = require("fzf-lua") + ---@field end_col? integer 1-based + ---@field open_term? boolean open_term for content (cmd always open_term) + +----@class fzf-lua.keymap.Entry ++---@class fzf-lua.keymap.Entry: fzf-lua.buffer_or_file.Entry + ---@field vmap string? + ---@field mode string? + ---@field key string? diff --git a/tasks/ibhagwan__fzf-lua-2667/tests/test.sh b/tasks/ibhagwan__fzf-lua-2667/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9441e729e6dd84bb0253368c8e121c397fb50fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4be0a6923a64dc411489b57b77a6bf6f30404e66 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2667/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2667/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2667/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2671/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2671/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e1fc08bacc66918caf3a3409e43a629eed228354 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 26dd5e39222250f751f733b1dafca9bae60cf8bb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 26dd5e39222250f751f733b1dafca9bae60cf8bb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 26dd5e39222250f751f733b1dafca9bae60cf8bb \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2671/instruction.md b/tasks/ibhagwan__fzf-lua-2671/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41c0d49be53df1503ebc5c787c2d2b17b8b4f134 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** fix(actions): pass nil to can_replace_buf instead of 0 + +## Description + +## Problem + +Fixing + +When `hidden` is not set (default), selecting a file from fzf-lua pickers (e.g. `files`, `grep`) fails with: + +``` +Unable to add buffer +``` + +This happens because `can_replace_buf` is called with `0` as the buffer argument at `actions.lua:242`. In Lua, `0` is truthy, so the fallback `buf = buf or nvim_get_current_buf()` inside `can_replace_buf` never triggers — the function proceeds with `buf = 0`. + +This propagates down to `buffer_is_dirty` → `getbufinfo(0)`, which returns an empty table (no buffer with id 0 exists). The `changed` field on that empty table is `nil`, and since `nil ~= 0` evaluates to `true`, the function always reports the buffer as dirty, causing `can_replace_buf` to always return `false`. + +## Fix + +Pass `nil` instead of `0` so that `can_replace_buf` correctly falls back to `nvim_get_current_buf()` and checks the actual current buffer's dirty state. + + + +## Summary by CodeRabbit + +* **Refactor** + * Improved internal buffer selection handling to more consistently manage buffer references across operations. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26dd5e392222`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2671/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2671/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..37de3081514a4f3a03efa35ba3cc472e08da5cba --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index a1df624f..a2745f70 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -192,7 +192,6 @@ end + + ---@return boolean + local can_replace_buf = function(buf) +- buf = buf or vim.api.nvim_get_current_buf() + return vim.o.hidden + or vim.o.confirm + or vim.o.autowriteall +@@ -239,7 +238,7 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + end + if layoutcmd then + vim.cmd(layoutcmd) +- elseif not is_curbuf(entry.bufnr, fullpath) and not can_replace_buf(0) then ++ elseif not is_curbuf(entry.bufnr, fullpath) and not can_replace_buf() then + return utils.warn("Unable to add buffer %s", fullpath) + end + -- NOTE: URI entries only execute new buffers (new|vnew|tabnew) +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index adec0a1b..d3c8a49b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1116,7 +1116,7 @@ end + ---@param only_if_last_buffer? boolean + ---@return boolean + function M.buffer_is_dirty(bufnr, warn, only_if_last_buffer) +- bufnr = bufnr or vim.api.nvim_get_current_buf() ++ bufnr = (bufnr == nil or bufnr == 0) and vim.api.nvim_get_current_buf() or bufnr + local info = bufnr and M.getbufinfo(bufnr) + if info and info.changed ~= 0 then + if only_if_last_buffer and 1 < #vim.fn.win_findbuf(bufnr) then diff --git a/tasks/ibhagwan__fzf-lua-2671/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2671/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2671/task.toml b/tasks/ibhagwan__fzf-lua-2671/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68f2b0cefcad2b2c120e4b20c0cf26ac918bf403 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2671" +description = "fix(actions): pass nil to can_replace_buf instead of 0" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "26dd5e39222250f751f733b1dafca9bae60cf8bb" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2671" +source_access = "auto" +built_at = "2026-11-16T16:09:56.016747+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b59f5cabaf7e6c2eca3060913425b98369575d686948c28449aa65a5e9fc8fb2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-16T04:31:20Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.039307+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:756183971980789d4bc0bfd83449bfb9de1838154a6ca735cbc220ac0fbd779e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2671/tests/capture.py b/tasks/ibhagwan__fzf-lua-2671/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2671/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2671/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41c0d49be53df1503ebc5c787c2d2b17b8b4f134 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** fix(actions): pass nil to can_replace_buf instead of 0 + +## Description + +## Problem + +Fixing + +When `hidden` is not set (default), selecting a file from fzf-lua pickers (e.g. `files`, `grep`) fails with: + +``` +Unable to add buffer +``` + +This happens because `can_replace_buf` is called with `0` as the buffer argument at `actions.lua:242`. In Lua, `0` is truthy, so the fallback `buf = buf or nvim_get_current_buf()` inside `can_replace_buf` never triggers — the function proceeds with `buf = 0`. + +This propagates down to `buffer_is_dirty` → `getbufinfo(0)`, which returns an empty table (no buffer with id 0 exists). The `changed` field on that empty table is `nil`, and since `nil ~= 0` evaluates to `true`, the function always reports the buffer as dirty, causing `can_replace_buf` to always return `false`. + +## Fix + +Pass `nil` instead of `0` so that `can_replace_buf` correctly falls back to `nvim_get_current_buf()` and checks the actual current buffer's dirty state. + + + +## Summary by CodeRabbit + +* **Refactor** + * Improved internal buffer selection handling to more consistently manage buffer references across operations. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26dd5e392222`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2671/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2671/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..37de3081514a4f3a03efa35ba3cc472e08da5cba --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index a1df624f..a2745f70 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -192,7 +192,6 @@ end + + ---@return boolean + local can_replace_buf = function(buf) +- buf = buf or vim.api.nvim_get_current_buf() + return vim.o.hidden + or vim.o.confirm + or vim.o.autowriteall +@@ -239,7 +238,7 @@ M.vimcmd_entry = function(vimcmd, selected, opts, bufedit) + end + if layoutcmd then + vim.cmd(layoutcmd) +- elseif not is_curbuf(entry.bufnr, fullpath) and not can_replace_buf(0) then ++ elseif not is_curbuf(entry.bufnr, fullpath) and not can_replace_buf() then + return utils.warn("Unable to add buffer %s", fullpath) + end + -- NOTE: URI entries only execute new buffers (new|vnew|tabnew) +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index adec0a1b..d3c8a49b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1116,7 +1116,7 @@ end + ---@param only_if_last_buffer? boolean + ---@return boolean + function M.buffer_is_dirty(bufnr, warn, only_if_last_buffer) +- bufnr = bufnr or vim.api.nvim_get_current_buf() ++ bufnr = (bufnr == nil or bufnr == 0) and vim.api.nvim_get_current_buf() or bufnr + local info = bufnr and M.getbufinfo(bufnr) + if info and info.changed ~= 0 then + if only_if_last_buffer and 1 < #vim.fn.win_findbuf(bufnr) then diff --git a/tasks/ibhagwan__fzf-lua-2671/tests/test.sh b/tasks/ibhagwan__fzf-lua-2671/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69d32989fcfbbbc325f934de089c1dc1b6d78223 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 26dd5e39222250f751f733b1dafca9bae60cf8bb > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2671/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2671/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2671/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2675/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2675/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ccc73c4e339c9d041b8504c3c28bd581f1347857 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 69b0d5d045cc039e68ba4c82190ce471464226b6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 69b0d5d045cc039e68ba4c82190ce471464226b6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 69b0d5d045cc039e68ba4c82190ce471464226b6 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2675/instruction.md b/tasks/ibhagwan__fzf-lua-2675/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..873d4ec471631ac4406474c0dd66bbd2e57475a0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** ci: 0.11.6 -> 0.12.1 + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Updated CI test matrix and version compatibility checks to support Neovim v0.12.1 (stable) and v0.13 (nightly). + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69b0d5d045cc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2675/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2675/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d2cf436aca3f0f77f1bb1b65d3b9265181265688 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index d2274310..a9f7abcb 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -18,7 +18,7 @@ jobs: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] +- rev: [nightly, v0.11.6, puc-lua] ++ rev: [nightly, v0.12.1, puc-lua] + exclude: + - os: macos-latest + rev: puc-lua +diff --git a/lua/fzf-lua/test/helpers.lua b/lua/fzf-lua/test/helpers.lua +index 42b63fd7..ab8feb0b 100644 +--- a/lua/fzf-lua/test/helpers.lua ++++ b/lua/fzf-lua/test/helpers.lua +@@ -36,8 +36,8 @@ local os_detect = { + }, + MAC = { name = "MacOS", fn = function() return vim.fn.has("mac") == 1 end }, + LINUX = { name = "Linux", fn = function() return vim.fn.has("linux") == 1 end }, +- STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.11.6" end }, +- NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.12") == 1 end }, ++ STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.1" end }, ++ NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.13") == 1 end }, + } + + -- Creates M.IS_WIN(), M.IS_NOT_WIN(), M.SKIP_IF_WIN(), etc diff --git a/tasks/ibhagwan__fzf-lua-2675/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2675/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2675/task.toml b/tasks/ibhagwan__fzf-lua-2675/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..200b5f4275e2c612dde04c6f800e91d5a66746f9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2675" +description = "ci: 0.11.6 -> 0.12.1" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "69b0d5d045cc039e68ba4c82190ce471464226b6" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2675" +source_access = "auto" +built_at = "2026-11-16T16:09:56.005334+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6edff517278d7b28a4245845e8362aa2bfec8d56235fcbcd385cddd21ec68b05" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-17T00:23:48Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", + "lua/fzf-lua/test/helpers.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.039810+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:94c87260df680bf1c2048df1abaa4f5d0bda6915291caf4f1e0a0e19da1ceb32" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2675/tests/capture.py b/tasks/ibhagwan__fzf-lua-2675/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2675/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2675/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..873d4ec471631ac4406474c0dd66bbd2e57475a0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** ci: 0.11.6 -> 0.12.1 + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Updated CI test matrix and version compatibility checks to support Neovim v0.12.1 (stable) and v0.13 (nightly). + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69b0d5d045cc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2675/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2675/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d2cf436aca3f0f77f1bb1b65d3b9265181265688 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index d2274310..a9f7abcb 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -18,7 +18,7 @@ jobs: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] +- rev: [nightly, v0.11.6, puc-lua] ++ rev: [nightly, v0.12.1, puc-lua] + exclude: + - os: macos-latest + rev: puc-lua +diff --git a/lua/fzf-lua/test/helpers.lua b/lua/fzf-lua/test/helpers.lua +index 42b63fd7..ab8feb0b 100644 +--- a/lua/fzf-lua/test/helpers.lua ++++ b/lua/fzf-lua/test/helpers.lua +@@ -36,8 +36,8 @@ local os_detect = { + }, + MAC = { name = "MacOS", fn = function() return vim.fn.has("mac") == 1 end }, + LINUX = { name = "Linux", fn = function() return vim.fn.has("linux") == 1 end }, +- STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.11.6" end }, +- NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.12") == 1 end }, ++ STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.1" end }, ++ NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.13") == 1 end }, + } + + -- Creates M.IS_WIN(), M.IS_NOT_WIN(), M.SKIP_IF_WIN(), etc diff --git a/tasks/ibhagwan__fzf-lua-2675/tests/test.sh b/tasks/ibhagwan__fzf-lua-2675/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0ad637df320f661a251f086d698637bb129f73c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 69b0d5d045cc039e68ba4c82190ce471464226b6 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2675/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2675/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2675/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2676/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2676/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..13d27fdb5237725005b1336573f5af00d6ebaf7e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c27c398ef84f3a98185623764ba4793758b68952 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c27c398ef84f3a98185623764ba4793758b68952 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c27c398ef84f3a98185623764ba4793758b68952 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2676/instruction.md b/tasks/ibhagwan__fzf-lua-2676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9789670321abeeaa12db9d6d64bbac1b0598ab8a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(keymaps): resume precompile module path is possible + +## Description + +Fix + +https://github.com/neovim/neovim/blob/64d55b74d83d566975e269bed0810d9008119ddf/src/nvim/lua/executor.c#L671-L680 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Refined keymapping source detection with enhanced validation for more reliable results. + * Improved resolution of Neovim's internal Lua module sources to correctly map them to their runtime file paths, providing better source file tracking for keymaps. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c27c398ef84f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2676/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2676/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..78a45985ca23f2922e4cb4ee98996602639a4a32 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index e0bda2a9..95b87241 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -683,9 +683,14 @@ function M.keymap_to_entry(str) + mode = valid_modes[mode] and mode or "" -- only valid modes + local vmap = vim.fn.maparg(keymap, mode, false, true) + if vmap.callback then +- local info = debug.getinfo(vmap.callback) +- if info and info.source then +- return { path = info.source:gsub("^@", ""), line = info.linedefined } ++ local info = debug.getinfo(vmap.callback, "Sl") ++ if info and info.source and info.linedefined and info.linedefined > 0 then ++ local source = info.source:gsub("^@", "") ++ -- https://github.com/neovim/neovim/blob/64d55b74d83d566975e269bed0810d9008119ddf/src/nvim/lua/executor.c#L671-L680 ++ if source:match("vim/") and package.preload[source:gsub("%.lua$", ""):gsub("/", ".")] then ++ source = vim.env.VIMRUNTIME .. "/lua/" .. source .. ".lua" ++ end ++ return { path = source, line = info.linedefined } + end + end + local cmd = ("verb %smap %s"):format(mode, keymap) diff --git a/tasks/ibhagwan__fzf-lua-2676/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2676/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2676/task.toml b/tasks/ibhagwan__fzf-lua-2676/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af2fc42772ab7214debd82cd487ba09c890e99e2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2676" +description = "fix(keymaps): resume precompile module path is possible" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "c27c398ef84f3a98185623764ba4793758b68952" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2676" +source_access = "auto" +built_at = "2026-11-16T16:09:56.013799+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3828420fa708e9b4e51edb9268afd50445f15677deca0e347f7c730c8d119359" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-20T12:11:14Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/path.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[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:01.040334+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4db154f26619c8673a0e747c2e24319cace8f32340f570aadfd5e7dac91aa430" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2676/tests/capture.py b/tasks/ibhagwan__fzf-lua-2676/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2676/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2676/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9789670321abeeaa12db9d6d64bbac1b0598ab8a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(keymaps): resume precompile module path is possible + +## Description + +Fix + +https://github.com/neovim/neovim/blob/64d55b74d83d566975e269bed0810d9008119ddf/src/nvim/lua/executor.c#L671-L680 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Refined keymapping source detection with enhanced validation for more reliable results. + * Improved resolution of Neovim's internal Lua module sources to correctly map them to their runtime file paths, providing better source file tracking for keymaps. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c27c398ef84f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2676/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2676/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..78a45985ca23f2922e4cb4ee98996602639a4a32 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index e0bda2a9..95b87241 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -683,9 +683,14 @@ function M.keymap_to_entry(str) + mode = valid_modes[mode] and mode or "" -- only valid modes + local vmap = vim.fn.maparg(keymap, mode, false, true) + if vmap.callback then +- local info = debug.getinfo(vmap.callback) +- if info and info.source then +- return { path = info.source:gsub("^@", ""), line = info.linedefined } ++ local info = debug.getinfo(vmap.callback, "Sl") ++ if info and info.source and info.linedefined and info.linedefined > 0 then ++ local source = info.source:gsub("^@", "") ++ -- https://github.com/neovim/neovim/blob/64d55b74d83d566975e269bed0810d9008119ddf/src/nvim/lua/executor.c#L671-L680 ++ if source:match("vim/") and package.preload[source:gsub("%.lua$", ""):gsub("/", ".")] then ++ source = vim.env.VIMRUNTIME .. "/lua/" .. source .. ".lua" ++ end ++ return { path = source, line = info.linedefined } + end + end + local cmd = ("verb %smap %s"):format(mode, keymap) diff --git a/tasks/ibhagwan__fzf-lua-2676/tests/test.sh b/tasks/ibhagwan__fzf-lua-2676/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb3b54b149d83bf4c53f1f4d3cead99fc6fd5442 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c27c398ef84f3a98185623764ba4793758b68952 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2676/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2676/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2676/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2680/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2680/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..793f2ace933ced1320efc16d9a739934c608bd2e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 83f7195972538beee3a40932b38ccd86c8cc0f06 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 83f7195972538beee3a40932b38ccd86c8cc0f06 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 83f7195972538beee3a40932b38ccd86c8cc0f06 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2680/instruction.md b/tasks/ibhagwan__fzf-lua-2680/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a45adb9b5810403831807e9c0f193566cb8654c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(actions): werid issue when set verbose=1 + +## Description + +Maybe there're other similar issue, to be discovered + +Fix + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable jump-to-location behavior on Neovim 0.11+ to reduce noisy output and improve navigation. + * Improved stability on Windows by adding short delays to reduce race conditions during rapid file/preview operations. + * Consistent previewer resize behavior on Windows to prevent flaky layout changes during interactive resizing. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `83f719597253`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2680/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2680/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6214cccfcfe81a63d9821ef26dfaf10f632071a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/solution/patch.diff @@ -0,0 +1,50 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index d3c8a49b..dca84156 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1625,8 +1625,10 @@ end + ---@return boolean + function M.jump_to_location(location, offset_encoding, reuse_win) + if M.__HAS_NVIM_011 then +- return vim.lsp.util.show_document(location, offset_encoding, +- { reuse_win = reuse_win, focus = true }) ++ return M.with({ o = { verbose = 0 } }, function() ++ return vim.lsp.util.show_document(location, offset_encoding, ++ { reuse_win = reuse_win, focus = true }) ++ end) + else + ---@diagnostic disable-next-line: deprecated + return vim.lsp.util.jump_to_location(location, offset_encoding, reuse_win) +diff --git a/tests/win_spec.lua b/tests/win_spec.lua +index 93290eab..bec4a1d8 100644 +--- a/tests/win_spec.lua ++++ b/tests/win_spec.lua +@@ -151,9 +151,9 @@ T["win"]["keymap"]["no error"] = new_set({ + :map(function(key, action) return { key, action } end) + :totable() + }, { +- function(key, _action) +- local builtin = child.lua_get [[FzfLua.defaults.keymap.builtin]] ++ function(key, action) + for _, event in ipairs({ "start", "load", "result" }) do ++ if action == "toggle-preview" then helpers.SKIP_IF_WIN() end + helpers.FzfLua.files(child, { + __abort_key = key .. "", + __expect_lines = false, +@@ -184,14 +184,9 @@ T["win"]["previewer"]["split flex layout resize"] = function() + } + }, + previewer = function() return require("fzf-lua.test.previewer").builtin end, +- keymap = { +- fzf = { +- resize = function() +- _G._fzf_resize_called = true +- end +- } +- }, ++ keymap = { fzf = { resize = function() _G._fzf_resize_called = true end } }, + __after_open = function() ++ if helpers.IS_WIN() then vim.uv.sleep(250) end + child.wait_until(function() + return child.lua_get([[FzfLua.utils.fzf_winobj()._previewer.last_entry]]) == "foo" + end) diff --git a/tasks/ibhagwan__fzf-lua-2680/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2680/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2680/task.toml b/tasks/ibhagwan__fzf-lua-2680/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3473f659b9f02fabbcafe56f9772d2762f1ab4e2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2680" +description = "fix(actions): werid issue when set verbose=1" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "83f7195972538beee3a40932b38ccd86c8cc0f06" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2680" +source_access = "auto" +built_at = "2026-11-16T16:09:56.015269+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9158457b649a8246d9e3e28f69ea8d8dec76400489244dd69e126ba556419ef3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-18T07:56:48Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/utils.lua", + "tests/win_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[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:01.040839+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f39fa164b670d43b7aeb7dd429e4e3b6b015f0314062222965345d2c5d8d31ae" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2680/tests/capture.py b/tasks/ibhagwan__fzf-lua-2680/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2680/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2680/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a45adb9b5810403831807e9c0f193566cb8654c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(actions): werid issue when set verbose=1 + +## Description + +Maybe there're other similar issue, to be discovered + +Fix + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable jump-to-location behavior on Neovim 0.11+ to reduce noisy output and improve navigation. + * Improved stability on Windows by adding short delays to reduce race conditions during rapid file/preview operations. + * Consistent previewer resize behavior on Windows to prevent flaky layout changes during interactive resizing. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `83f719597253`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2680/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2680/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e6214cccfcfe81a63d9821ef26dfaf10f632071a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/tests/oracle.patch @@ -0,0 +1,50 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index d3c8a49b..dca84156 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1625,8 +1625,10 @@ end + ---@return boolean + function M.jump_to_location(location, offset_encoding, reuse_win) + if M.__HAS_NVIM_011 then +- return vim.lsp.util.show_document(location, offset_encoding, +- { reuse_win = reuse_win, focus = true }) ++ return M.with({ o = { verbose = 0 } }, function() ++ return vim.lsp.util.show_document(location, offset_encoding, ++ { reuse_win = reuse_win, focus = true }) ++ end) + else + ---@diagnostic disable-next-line: deprecated + return vim.lsp.util.jump_to_location(location, offset_encoding, reuse_win) +diff --git a/tests/win_spec.lua b/tests/win_spec.lua +index 93290eab..bec4a1d8 100644 +--- a/tests/win_spec.lua ++++ b/tests/win_spec.lua +@@ -151,9 +151,9 @@ T["win"]["keymap"]["no error"] = new_set({ + :map(function(key, action) return { key, action } end) + :totable() + }, { +- function(key, _action) +- local builtin = child.lua_get [[FzfLua.defaults.keymap.builtin]] ++ function(key, action) + for _, event in ipairs({ "start", "load", "result" }) do ++ if action == "toggle-preview" then helpers.SKIP_IF_WIN() end + helpers.FzfLua.files(child, { + __abort_key = key .. "", + __expect_lines = false, +@@ -184,14 +184,9 @@ T["win"]["previewer"]["split flex layout resize"] = function() + } + }, + previewer = function() return require("fzf-lua.test.previewer").builtin end, +- keymap = { +- fzf = { +- resize = function() +- _G._fzf_resize_called = true +- end +- } +- }, ++ keymap = { fzf = { resize = function() _G._fzf_resize_called = true end } }, + __after_open = function() ++ if helpers.IS_WIN() then vim.uv.sleep(250) end + child.wait_until(function() + return child.lua_get([[FzfLua.utils.fzf_winobj()._previewer.last_entry]]) == "foo" + end) diff --git a/tasks/ibhagwan__fzf-lua-2680/tests/test.sh b/tasks/ibhagwan__fzf-lua-2680/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ac5b4c12cbeea3347f89ba795925dc8ba17796f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 83f7195972538beee3a40932b38ccd86c8cc0f06 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2680/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2680/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2680/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2686/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2686/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6606d89568ab6742c3498d089b9ff0d002ce56b1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fcabe3cb7cfa6bd5148ffac0188997196401937d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fcabe3cb7cfa6bd5148ffac0188997196401937d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fcabe3cb7cfa6bd5148ffac0188997196401937d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2686/instruction.md b/tasks/ibhagwan__fzf-lua-2686/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3105185c6563b436069fa6f6842d330506e50bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** perf: use sendfile to forward + +## Description + +Not sure will this be faster + + +## Summary by CodeRabbit + +* **Refactor** + * Improved RPC data transfer for more reliable and efficient streaming, with better handling of end-of-stream and cleaner shutdown behavior. + * Linux-specific I/O optimizations to enhance throughput and reduce stalls during long-running transfers. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fcabe3cb7cfa`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2686/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2686/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..36b6734a4b64e9c028cc7340500ccb2c39762813 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/solution/patch.diff @@ -0,0 +1,50 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index e8e4f260..a04386a9 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -2,6 +2,7 @@ + local uv = vim.uv or vim.loop + + local _is_win = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 ++local _is_linux = vim.fn.has("linux") == 1 + + if vim.v.servername and #vim.v.servername > 0 then + pcall(vim.fn.serverstop, vim.v.servername) +@@ -34,18 +35,27 @@ local function server_listen(server_socket, server_socket_path) + if tmpdir and #tmpdir > 0 then uv.fs_rmdir(tmpdir) end + end + ++ local finish = function() ++ uv.close(receive_socket) ++ uv.close(server_socket) ++ -- on windows: ci fail when use uv.stop() ++ -- on linux: zero event can freeze ++ -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 ++ -- uv.stop() ++ os.exit(0) ++ end ++ ++ if _is_linux then ++ while true do ++ local len = uv.fs_sendfile(1, receive_socket:fileno(), 0, 1024 * 1024) ++ local eof = len == 0 ++ if eof then finish() end ++ end ++ end ++ + receive_socket:read_start(function(err, data) + assert(not err) +- if not data then +- uv.close(receive_socket) +- uv.close(server_socket) +- -- on windows: ci fail when use uv.stop() +- -- on linux: zero event can freeze +- -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 +- -- uv.stop() +- os.exit(0) +- return +- end ++ if not data then finish() end + io.write(data) + end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2686/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2686/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2686/task.toml b/tasks/ibhagwan__fzf-lua-2686/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f63aec649cff651e82185403bb76223fca99f3a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2686" +description = "perf: use sendfile to forward" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "fcabe3cb7cfa6bd5148ffac0188997196401937d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2686" +source_access = "auto" +built_at = "2026-11-16T16:09:56.010844+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3581547751186dcfc3dfc7d00a3ba351d4ab3289b8abf6d0556361730121c587" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-21T06:14:01Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/rpc.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "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:01.041333+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f50896ce6180819c7812d5b0b2a5aafc753dd27044cd7c329a1fd13218b54dbc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2686/tests/capture.py b/tasks/ibhagwan__fzf-lua-2686/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2686/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2686/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3105185c6563b436069fa6f6842d330506e50bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** perf: use sendfile to forward + +## Description + +Not sure will this be faster + + +## Summary by CodeRabbit + +* **Refactor** + * Improved RPC data transfer for more reliable and efficient streaming, with better handling of end-of-stream and cleaner shutdown behavior. + * Linux-specific I/O optimizations to enhance throughput and reduce stalls during long-running transfers. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fcabe3cb7cfa`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2686/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2686/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..36b6734a4b64e9c028cc7340500ccb2c39762813 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/tests/oracle.patch @@ -0,0 +1,50 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index e8e4f260..a04386a9 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -2,6 +2,7 @@ + local uv = vim.uv or vim.loop + + local _is_win = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 ++local _is_linux = vim.fn.has("linux") == 1 + + if vim.v.servername and #vim.v.servername > 0 then + pcall(vim.fn.serverstop, vim.v.servername) +@@ -34,18 +35,27 @@ local function server_listen(server_socket, server_socket_path) + if tmpdir and #tmpdir > 0 then uv.fs_rmdir(tmpdir) end + end + ++ local finish = function() ++ uv.close(receive_socket) ++ uv.close(server_socket) ++ -- on windows: ci fail when use uv.stop() ++ -- on linux: zero event can freeze ++ -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 ++ -- uv.stop() ++ os.exit(0) ++ end ++ ++ if _is_linux then ++ while true do ++ local len = uv.fs_sendfile(1, receive_socket:fileno(), 0, 1024 * 1024) ++ local eof = len == 0 ++ if eof then finish() end ++ end ++ end ++ + receive_socket:read_start(function(err, data) + assert(not err) +- if not data then +- uv.close(receive_socket) +- uv.close(server_socket) +- -- on windows: ci fail when use uv.stop() +- -- on linux: zero event can freeze +- -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 +- -- uv.stop() +- os.exit(0) +- return +- end ++ if not data then finish() end + io.write(data) + end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2686/tests/test.sh b/tasks/ibhagwan__fzf-lua-2686/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc701c195b0fbfb5a91fc76df44828b1ce790d3e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace fcabe3cb7cfa6bd5148ffac0188997196401937d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2686/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2686/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2686/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2688/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2688/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6c0f1adb423c875a0f776ccee0bcce272b78fce2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 423533df25c6cbc0f908676760517662996437c7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 423533df25c6cbc0f908676760517662996437c7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 423533df25c6cbc0f908676760517662996437c7 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2688/instruction.md b/tasks/ibhagwan__fzf-lua-2688/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a41a4e8108724fcb488ef937763f6e27695d82b4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix: wrong mode after :term then quickly stopi->close->new picker->starti + +## Description + +Fix + +`reuse=true` should also work, but it break previewer for some reason. + + +## Summary by CodeRabbit + +* **Refactor** + * Safer invocation flow for built-in actions, reducing launch failures and unexpected behavior when invoking features. + * Improved window-close handling with deferred mode transitions to avoid terminal/insert-mode glitches and stray mode changes during close. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `423533df25c6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2688/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2688/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..647e58c35c7af24bb5c52dc9631407abd388c232 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index d5bf73a3..47f5ebf7 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -515,7 +515,9 @@ end + M.run_builtin = function(selected) + if not selected[1] then return end + local method = selected[1] +- pcall(require "fzf-lua"[method]) ++ local func = vim.F.nil_wrap(require "fzf-lua"[method]) ++ if not _G.fzf_lua_stopinsert_hack then return func() end ++ _G.fzf_lua_stopinsert_hack(func) + end + + M.ex_run = function(selected) +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 37051ff8..36031498 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1166,6 +1166,25 @@ local restore_altbuf = function(buf) + end + end + ++local stopinsert = function(ctx) ++ _G.fzf_lua_stopinsert_hack = nil ++ if not (ctx.mode == "nt" and api.nvim_get_mode() ~= "nt") then return end ++ vim.cmd "stopinsert" ++ local pat = "FzfLuaStopInsertHack" ++ _G.fzf_lua_stopinsert_hack = function(cb) ++ api.nvim_create_autocmd("User", { pattern = pat, once = true, callback = cb }) ++ end ++ api.nvim_create_autocmd("ModeChanged", { ++ pattern = "*:nt", ++ once = true, ++ callback = function() ++ -- nvim_get_mode don't get correct mode without schedule_wrap ++ vim.schedule_wrap(api.nvim_exec_autocmds)("User", { pattern = pat, modeline = false }) ++ _G.fzf_lua_stopinsert_hack = nil ++ end, ++ }) ++end ++ + ---@param fzf_bufnr? integer + ---@param hide? boolean + function FzfWin:close(fzf_bufnr, hide) +@@ -1179,8 +1198,7 @@ function FzfWin:close(fzf_bufnr, hide) + -- switching from a term win to another term win preserves terminal mode + -- even if the target window was in normal terminal mode (#2054 #2419) + local ctx = utils.__CTX() or {} +- -- if ctx.mode and ctx.mode:match("^n") then vim.cmd "stopinsert" end +- if ctx.mode == "nt" then vim.cmd "stopinsert" end ++ stopinsert(ctx) + if self.fzf_winid and api.nvim_win_is_valid(self.fzf_winid) then + -- restore the original last window + restore_lastwin(ctx.winid, ctx.last_winid) diff --git a/tasks/ibhagwan__fzf-lua-2688/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2688/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2688/task.toml b/tasks/ibhagwan__fzf-lua-2688/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0b575e10355db2101121d9b88725e8940bc840a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2688" +description = "fix: wrong mode after :term then quickly stopi->close->new picker->starti" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "423533df25c6cbc0f908676760517662996437c7" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2688" +source_access = "auto" +built_at = "2026-11-16T16:09:56.012232+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:079fd20055c24875407983f742a3df88e3acf964557b4259ffbce8df650df1ed" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-20T14:05:53Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 26 +difficulty = "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:01.041846+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1105147c6c606a2bad2ce259337529e278e9a21c38d2b34be02a589296db9b3c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2688/tests/capture.py b/tasks/ibhagwan__fzf-lua-2688/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2688/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2688/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a41a4e8108724fcb488ef937763f6e27695d82b4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix: wrong mode after :term then quickly stopi->close->new picker->starti + +## Description + +Fix + +`reuse=true` should also work, but it break previewer for some reason. + + +## Summary by CodeRabbit + +* **Refactor** + * Safer invocation flow for built-in actions, reducing launch failures and unexpected behavior when invoking features. + * Improved window-close handling with deferred mode transitions to avoid terminal/insert-mode glitches and stray mode changes during close. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `423533df25c6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2688/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2688/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..647e58c35c7af24bb5c52dc9631407abd388c232 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index d5bf73a3..47f5ebf7 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -515,7 +515,9 @@ end + M.run_builtin = function(selected) + if not selected[1] then return end + local method = selected[1] +- pcall(require "fzf-lua"[method]) ++ local func = vim.F.nil_wrap(require "fzf-lua"[method]) ++ if not _G.fzf_lua_stopinsert_hack then return func() end ++ _G.fzf_lua_stopinsert_hack(func) + end + + M.ex_run = function(selected) +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 37051ff8..36031498 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1166,6 +1166,25 @@ local restore_altbuf = function(buf) + end + end + ++local stopinsert = function(ctx) ++ _G.fzf_lua_stopinsert_hack = nil ++ if not (ctx.mode == "nt" and api.nvim_get_mode() ~= "nt") then return end ++ vim.cmd "stopinsert" ++ local pat = "FzfLuaStopInsertHack" ++ _G.fzf_lua_stopinsert_hack = function(cb) ++ api.nvim_create_autocmd("User", { pattern = pat, once = true, callback = cb }) ++ end ++ api.nvim_create_autocmd("ModeChanged", { ++ pattern = "*:nt", ++ once = true, ++ callback = function() ++ -- nvim_get_mode don't get correct mode without schedule_wrap ++ vim.schedule_wrap(api.nvim_exec_autocmds)("User", { pattern = pat, modeline = false }) ++ _G.fzf_lua_stopinsert_hack = nil ++ end, ++ }) ++end ++ + ---@param fzf_bufnr? integer + ---@param hide? boolean + function FzfWin:close(fzf_bufnr, hide) +@@ -1179,8 +1198,7 @@ function FzfWin:close(fzf_bufnr, hide) + -- switching from a term win to another term win preserves terminal mode + -- even if the target window was in normal terminal mode (#2054 #2419) + local ctx = utils.__CTX() or {} +- -- if ctx.mode and ctx.mode:match("^n") then vim.cmd "stopinsert" end +- if ctx.mode == "nt" then vim.cmd "stopinsert" end ++ stopinsert(ctx) + if self.fzf_winid and api.nvim_win_is_valid(self.fzf_winid) then + -- restore the original last window + restore_lastwin(ctx.winid, ctx.last_winid) diff --git a/tasks/ibhagwan__fzf-lua-2688/tests/test.sh b/tasks/ibhagwan__fzf-lua-2688/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb081d66a310b8790d24b978d1e64221b6567a14 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 423533df25c6cbc0f908676760517662996437c7 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2688/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2688/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2688/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2691/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2691/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3e4bfc80b9f742eeec31a278c6a745889456bfe3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7b3a7390d01db93d422a4d6d6cf3771038577858 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7b3a7390d01db93d422a4d6d6cf3771038577858 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7b3a7390d01db93d422a4d6d6cf3771038577858 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2691/instruction.md b/tasks/ibhagwan__fzf-lua-2691/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50c872c6351332c92fb48935e2074efb7bded240 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(previewer): make "smartcase" work again + +## Description + +No flags for case sensitive, and flags like "\C" may break previous +smartcase hack + +Related: + + + +## Summary by CodeRabbit + +* **Refactor** + * Optimized preview highlighting logic by precomputing case sensitivity once instead of repeatedly checking it during regex matching, improving efficiency when displaying search results with case-sensitive and case-insensitive patterns. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b3a7390d01d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2691/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2691/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..65f168190d423f45998fb81d175a1f275b2da42c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index e6074f6d..37412085 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1252,6 +1252,7 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + end)() + end + ++ local case_sensitive = regex and regex:lower() ~= regex + -- If called from tags previewer, can happen when using ctags cmd + -- "ctags -R --c++-kinds=+p --fields=+iaS --extras=+q --excmd=combine" + -- vim.regex is always magic, see `:help vim.regex` +@@ -1307,7 +1308,7 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + ---@diagnostic disable-next-line: param-type-mismatch + local reg = utils.vim_regex(regex, { silent = true }) + if reg then +- if regex ~= regex:lower() then ++ if case_sensitive then + regex_start, regex_end = reg:match_line(buf, lnum - 1, col - 1) + else + local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" diff --git a/tasks/ibhagwan__fzf-lua-2691/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2691/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2691/task.toml b/tasks/ibhagwan__fzf-lua-2691/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..22d9062baa6c33198d0bf5f67f62547aa2b34123 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2691" +description = "fix(previewer): make \"smartcase\" work again" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "7b3a7390d01db93d422a4d6d6cf3771038577858" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2691" +source_access = "auto" +built_at = "2026-11-16T16:09:56.004007+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c592116b6c2c5fc4181938f0e5d429a27d9af8a6159272237bc915a7cc86eb6e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-22T05:16:51Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.042350+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:cb1c774e0f70efd37302e4911cfd5b4f767ede1937867b0faa6b81efc8ab0e7e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2691/tests/capture.py b/tasks/ibhagwan__fzf-lua-2691/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2691/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2691/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50c872c6351332c92fb48935e2074efb7bded240 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(previewer): make "smartcase" work again + +## Description + +No flags for case sensitive, and flags like "\C" may break previous +smartcase hack + +Related: + + + +## Summary by CodeRabbit + +* **Refactor** + * Optimized preview highlighting logic by precomputing case sensitivity once instead of repeatedly checking it during regex matching, improving efficiency when displaying search results with case-sensitive and case-insensitive patterns. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b3a7390d01d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2691/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2691/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..65f168190d423f45998fb81d175a1f275b2da42c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index e6074f6d..37412085 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1252,6 +1252,7 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + end)() + end + ++ local case_sensitive = regex and regex:lower() ~= regex + -- If called from tags previewer, can happen when using ctags cmd + -- "ctags -R --c++-kinds=+p --fields=+iaS --extras=+q --excmd=combine" + -- vim.regex is always magic, see `:help vim.regex` +@@ -1307,7 +1308,7 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + ---@diagnostic disable-next-line: param-type-mismatch + local reg = utils.vim_regex(regex, { silent = true }) + if reg then +- if regex ~= regex:lower() then ++ if case_sensitive then + regex_start, regex_end = reg:match_line(buf, lnum - 1, col - 1) + else + local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" diff --git a/tasks/ibhagwan__fzf-lua-2691/tests/test.sh b/tasks/ibhagwan__fzf-lua-2691/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..22c20a312b82b3e0c8bd42a6838b0d8c4a7e09f0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7b3a7390d01db93d422a4d6d6cf3771038577858 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2691/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2691/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2691/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2696/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2696/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..821d4f1540dc853235f68567e8bcad8a7bf66478 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8223eb24a7adf72c4b24e04b751486b492775414 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2696/instruction.md b/tasks/ibhagwan__fzf-lua-2696/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ae8b72341643c2d2b3786191b393a5768ce26ff0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/instruction.md @@ -0,0 +1,60 @@ +# Issue + +**Title:** feat(git): consistent highlighting in branches/worktrees pickers + +## Description + +Adds an `fn_transform` to `git_branches` and `git_worktrees` so delimiters render grey and content picks up a semantic color, yellowing SHAs to match `commits`/`bcommits`/`reflog`/`tags`/`stash`. `git_blame` is intentionally skipped since `--color-lines` already encodes same-commit grouping via `color.blame.repeatedLines`. + +## worktrees + +highlight diff: + +| token | before | after | +| ------------------- | ------ | ---------------------------------- | +| path | plain | blue | +| SHA | plain | yellow | +| `[branch]` | plain | grey `[` · green branch · grey `]` | +| `(detached HEAD)` | plain | grey `(` · green text · grey `)` | +| `(bare)` | plain | grey `(` · grey text · grey `)` | +| trailing `locked` | plain | magenta | +| trailing `prunable` | plain | red | + +before/after (my config. vs. vanilla patch) + +image + +## branches + +highlight diff: + +| token | before | after | +| -------------------------------------- | ------------------ | --------------------------------------------------- | +| branch: current `*` | green | green (unchanged) | +| branch: used in another wt `+` | cyan | cyan (unchanged) | +| branch: remote | red | red (unchanged) | +| SHA | plain | yellow | +| `[origin/ref]` | blue refname | grey `[` · blue refname · grey `]` | +| `[origin/ref: ahead/behind/gone]` | blue refname | grey `[` · blue refname · grey `:status` · grey `]` | +| `(HEAD detached at X)` | green (incl. `()`) | grey `(` · green text · grey `)` | +| `(no branch)` / `(no branch, bisect…)` | green (incl. `()`) | grey `(` · green text · grey `)` | +| `(/path/to/worktree)` annotation | cyan inside | grey `(` · cyan path · grey `)` | +| `remotes/.../HEAD -> origin/X` | unchanged | unchanged | + +before/after (my config. vs. vanilla patch) + +image + + + +## Summary by CodeRabbit + +* **New Features** + * Automatic syntax highlighting now applied to git branch lists, with color-coded branch names, commit identifiers, tracking status, and reference indicators for improved readability. + * Automatic syntax highlighting now applied to git worktree lists, with color-coded worktree names, commit references, and status details for enhanced visual clarity. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2696/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2696/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8c5437095858bbe1aff0e8ac49fd9af9e6d1d1ab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/solution/patch.diff @@ -0,0 +1,131 @@ +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 5759f62f..f855a499 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -267,12 +267,118 @@ M.blame = function(opts) + return git_cmd(opts) + end + ++---@param line string ++---@return string ++local function highlight_branch_line(line) ++ local u = FzfLua.utils ++ local ansi = u.ansi_codes ++ line = u.strip_ansi_coloring(line) ++ local leader = line:sub(1, 2) ++ local rest = line:sub(3) ++ ++ local detached_inner = rest:match("^%(([^)]+)%)") ++ if detached_inner and ++ (detached_inner:match("^HEAD detached") or detached_inner:match("^no branch")) then ++ local head = ansi.grey("(") .. ansi.green(detached_inner) .. ansi.grey(")") ++ local after = rest:sub(#detached_inner + 3) ++ local ws, sha, subject_ws, subject = after:match("^(%s+)(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if ws and sha then ++ return leader .. head .. ws .. ansi.yellow(sha) .. subject_ws .. subject ++ end ++ return leader .. head .. after ++ end ++ ++ local branch_name, ws_after_name, after = rest:match("^(%S+)(%s+)(.*)$") ++ if not branch_name then return line end ++ ++ local colored_branch ++ if leader:sub(1, 1) == "*" then ++ colored_branch = ansi.green(branch_name) ++ elseif leader:sub(1, 1) == "+" then ++ colored_branch = ansi.cyan(branch_name) ++ elseif branch_name:match("^remotes/") then ++ colored_branch = ansi.red(branch_name) ++ else ++ colored_branch = branch_name ++ end ++ ++ if after:match("^%->") then ++ return leader .. colored_branch .. ws_after_name .. after ++ end ++ ++ local sha, body_ws, body = after:match("^(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if not sha then ++ return leader .. colored_branch .. ws_after_name .. after ++ end ++ ++ local function color_tracking(content) ++ local ref, suffix = content:match("^([^:]+)(:.*)$") ++ if ref and suffix then ++ return ansi.grey("[") .. ansi.blue(ref) .. ansi.grey(suffix) .. ansi.grey("]") ++ end ++ return ansi.grey("[") .. ansi.blue(content) .. ansi.grey("]") ++ end ++ ++ if leader:sub(1, 1) == "+" then ++ local wt_paren, remainder = body:match("^(%b())(.*)$") ++ if wt_paren then ++ local colored_wt = ansi.grey("(") .. ansi.cyan(wt_paren:sub(2, -2)) .. ansi.grey(")") ++ remainder = remainder:gsub("^(%s*)(%[)([^%]]+)(%])", function(ws, _, content, _) ++ return ws .. color_tracking(content) ++ end) ++ body = colored_wt .. remainder ++ end ++ else ++ body = body:gsub("^(%[)([^%]]+)(%])", function(_, content, _) ++ return color_tracking(content) ++ end) ++ end ++ ++ return leader .. colored_branch .. ws_after_name .. ansi.yellow(sha) .. body_ws .. body ++end ++ ++---@param line string ++---@return string ++local function highlight_worktree_line(line) ++ local ansi = FzfLua.utils.ansi_codes ++ local path_s, padding, rest = line:match("^(%S+)(%s+)(.*)$") ++ if not path_s then return line end ++ ++ local sha, sha_ws, body = rest:match("^(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if not sha then ++ body = rest ++ end ++ ++ body = body:gsub("^(%[)([^%]]+)(%])", function(lb, name, rb) ++ return ansi.grey(lb) .. ansi.green(name) .. ansi.grey(rb) ++ end) ++ body = body:gsub("^(%()(detached HEAD)(%))", function(lp, text, rp) ++ return ansi.grey(lp) .. ansi.green(text) .. ansi.grey(rp) ++ end) ++ body = body:gsub("^(%()(bare)(%))", function(lp, text, rp) ++ return ansi.grey(lp) .. ansi.grey(text) .. ansi.grey(rp) ++ end) ++ body = body:gsub("(%s)(locked)(%s*)$", function(s1, w, s2) ++ return s1 .. ansi.magenta(w) .. s2 ++ end) ++ body = body:gsub("(%s)(prunable)(%s*)$", function(s1, w, s2) ++ return s1 .. ansi.red(w) .. s2 ++ end) ++ ++ local out = ansi.blue(path_s) .. padding ++ if sha then ++ out = out .. ansi.yellow(sha) .. sha_ws ++ end ++ return out .. body ++end ++ + ---@param opts fzf-lua.config.GitBranches|{}? + ---@return thread?, string?, table? + M.branches = function(opts) + ---@type fzf-lua.config.GitBranches + opts = config.normalize_opts(opts, "git.branches") + if not opts then return end ++ if opts.fn_transform == nil then opts.fn_transform = highlight_branch_line end + if opts.preview then + local preview = path.git_cwd(opts.preview, opts) + opts.preview = shell.stringify_cmd(function(items) +@@ -301,6 +407,7 @@ M.worktrees = function(opts) + ---@type fzf-lua.config.GitWorktrees + opts = config.normalize_opts(opts, "git.worktrees") + if not opts then return end ++ if opts.fn_transform == nil then opts.fn_transform = highlight_worktree_line end + if opts.preview then + local preview_cmd = opts.preview + opts.preview = shell.stringify_cmd(function(items) diff --git a/tasks/ibhagwan__fzf-lua-2696/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2696/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2696/task.toml b/tasks/ibhagwan__fzf-lua-2696/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5c0196f60b1ada42380cd9d83f2a916904c9391 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2696" +description = "feat(git): consistent highlighting in branches/worktrees pickers" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "8223eb24a7adf72c4b24e04b751486b492775414" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2696" +source_access = "auto" +built_at = "2026-11-16T16:09:56.001006+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2375056f498bb9bd1eba3d22d438bb69f39445ed70ffee56a3044af7656c8b24" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-28T23:04:55Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/git.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 107 +difficulty = "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:01.042823+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9097e3fcd17ba432685c95d33fedda1504aad0c7acaf5a4f658507b41d38f93a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2696/tests/capture.py b/tasks/ibhagwan__fzf-lua-2696/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2696/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2696/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ae8b72341643c2d2b3786191b393a5768ce26ff0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/tests/instruction.md @@ -0,0 +1,60 @@ +# Issue + +**Title:** feat(git): consistent highlighting in branches/worktrees pickers + +## Description + +Adds an `fn_transform` to `git_branches` and `git_worktrees` so delimiters render grey and content picks up a semantic color, yellowing SHAs to match `commits`/`bcommits`/`reflog`/`tags`/`stash`. `git_blame` is intentionally skipped since `--color-lines` already encodes same-commit grouping via `color.blame.repeatedLines`. + +## worktrees + +highlight diff: + +| token | before | after | +| ------------------- | ------ | ---------------------------------- | +| path | plain | blue | +| SHA | plain | yellow | +| `[branch]` | plain | grey `[` · green branch · grey `]` | +| `(detached HEAD)` | plain | grey `(` · green text · grey `)` | +| `(bare)` | plain | grey `(` · grey text · grey `)` | +| trailing `locked` | plain | magenta | +| trailing `prunable` | plain | red | + +before/after (my config. vs. vanilla patch) + +image + +## branches + +highlight diff: + +| token | before | after | +| -------------------------------------- | ------------------ | --------------------------------------------------- | +| branch: current `*` | green | green (unchanged) | +| branch: used in another wt `+` | cyan | cyan (unchanged) | +| branch: remote | red | red (unchanged) | +| SHA | plain | yellow | +| `[origin/ref]` | blue refname | grey `[` · blue refname · grey `]` | +| `[origin/ref: ahead/behind/gone]` | blue refname | grey `[` · blue refname · grey `:status` · grey `]` | +| `(HEAD detached at X)` | green (incl. `()`) | grey `(` · green text · grey `)` | +| `(no branch)` / `(no branch, bisect…)` | green (incl. `()`) | grey `(` · green text · grey `)` | +| `(/path/to/worktree)` annotation | cyan inside | grey `(` · cyan path · grey `)` | +| `remotes/.../HEAD -> origin/X` | unchanged | unchanged | + +before/after (my config. vs. vanilla patch) + +image + + + +## Summary by CodeRabbit + +* **New Features** + * Automatic syntax highlighting now applied to git branch lists, with color-coded branch names, commit identifiers, tracking status, and reference indicators for improved readability. + * Automatic syntax highlighting now applied to git worktree lists, with color-coded worktree names, commit references, and status details for enhanced visual clarity. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2696/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2696/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8c5437095858bbe1aff0e8ac49fd9af9e6d1d1ab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/tests/oracle.patch @@ -0,0 +1,131 @@ +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index 5759f62f..f855a499 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -267,12 +267,118 @@ M.blame = function(opts) + return git_cmd(opts) + end + ++---@param line string ++---@return string ++local function highlight_branch_line(line) ++ local u = FzfLua.utils ++ local ansi = u.ansi_codes ++ line = u.strip_ansi_coloring(line) ++ local leader = line:sub(1, 2) ++ local rest = line:sub(3) ++ ++ local detached_inner = rest:match("^%(([^)]+)%)") ++ if detached_inner and ++ (detached_inner:match("^HEAD detached") or detached_inner:match("^no branch")) then ++ local head = ansi.grey("(") .. ansi.green(detached_inner) .. ansi.grey(")") ++ local after = rest:sub(#detached_inner + 3) ++ local ws, sha, subject_ws, subject = after:match("^(%s+)(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if ws and sha then ++ return leader .. head .. ws .. ansi.yellow(sha) .. subject_ws .. subject ++ end ++ return leader .. head .. after ++ end ++ ++ local branch_name, ws_after_name, after = rest:match("^(%S+)(%s+)(.*)$") ++ if not branch_name then return line end ++ ++ local colored_branch ++ if leader:sub(1, 1) == "*" then ++ colored_branch = ansi.green(branch_name) ++ elseif leader:sub(1, 1) == "+" then ++ colored_branch = ansi.cyan(branch_name) ++ elseif branch_name:match("^remotes/") then ++ colored_branch = ansi.red(branch_name) ++ else ++ colored_branch = branch_name ++ end ++ ++ if after:match("^%->") then ++ return leader .. colored_branch .. ws_after_name .. after ++ end ++ ++ local sha, body_ws, body = after:match("^(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if not sha then ++ return leader .. colored_branch .. ws_after_name .. after ++ end ++ ++ local function color_tracking(content) ++ local ref, suffix = content:match("^([^:]+)(:.*)$") ++ if ref and suffix then ++ return ansi.grey("[") .. ansi.blue(ref) .. ansi.grey(suffix) .. ansi.grey("]") ++ end ++ return ansi.grey("[") .. ansi.blue(content) .. ansi.grey("]") ++ end ++ ++ if leader:sub(1, 1) == "+" then ++ local wt_paren, remainder = body:match("^(%b())(.*)$") ++ if wt_paren then ++ local colored_wt = ansi.grey("(") .. ansi.cyan(wt_paren:sub(2, -2)) .. ansi.grey(")") ++ remainder = remainder:gsub("^(%s*)(%[)([^%]]+)(%])", function(ws, _, content, _) ++ return ws .. color_tracking(content) ++ end) ++ body = colored_wt .. remainder ++ end ++ else ++ body = body:gsub("^(%[)([^%]]+)(%])", function(_, content, _) ++ return color_tracking(content) ++ end) ++ end ++ ++ return leader .. colored_branch .. ws_after_name .. ansi.yellow(sha) .. body_ws .. body ++end ++ ++---@param line string ++---@return string ++local function highlight_worktree_line(line) ++ local ansi = FzfLua.utils.ansi_codes ++ local path_s, padding, rest = line:match("^(%S+)(%s+)(.*)$") ++ if not path_s then return line end ++ ++ local sha, sha_ws, body = rest:match("^(%x%x%x%x%x%x%x+)(%s+)(.*)$") ++ if not sha then ++ body = rest ++ end ++ ++ body = body:gsub("^(%[)([^%]]+)(%])", function(lb, name, rb) ++ return ansi.grey(lb) .. ansi.green(name) .. ansi.grey(rb) ++ end) ++ body = body:gsub("^(%()(detached HEAD)(%))", function(lp, text, rp) ++ return ansi.grey(lp) .. ansi.green(text) .. ansi.grey(rp) ++ end) ++ body = body:gsub("^(%()(bare)(%))", function(lp, text, rp) ++ return ansi.grey(lp) .. ansi.grey(text) .. ansi.grey(rp) ++ end) ++ body = body:gsub("(%s)(locked)(%s*)$", function(s1, w, s2) ++ return s1 .. ansi.magenta(w) .. s2 ++ end) ++ body = body:gsub("(%s)(prunable)(%s*)$", function(s1, w, s2) ++ return s1 .. ansi.red(w) .. s2 ++ end) ++ ++ local out = ansi.blue(path_s) .. padding ++ if sha then ++ out = out .. ansi.yellow(sha) .. sha_ws ++ end ++ return out .. body ++end ++ + ---@param opts fzf-lua.config.GitBranches|{}? + ---@return thread?, string?, table? + M.branches = function(opts) + ---@type fzf-lua.config.GitBranches + opts = config.normalize_opts(opts, "git.branches") + if not opts then return end ++ if opts.fn_transform == nil then opts.fn_transform = highlight_branch_line end + if opts.preview then + local preview = path.git_cwd(opts.preview, opts) + opts.preview = shell.stringify_cmd(function(items) +@@ -301,6 +407,7 @@ M.worktrees = function(opts) + ---@type fzf-lua.config.GitWorktrees + opts = config.normalize_opts(opts, "git.worktrees") + if not opts then return end ++ if opts.fn_transform == nil then opts.fn_transform = highlight_worktree_line end + if opts.preview then + local preview_cmd = opts.preview + opts.preview = shell.stringify_cmd(function(items) diff --git a/tasks/ibhagwan__fzf-lua-2696/tests/test.sh b/tasks/ibhagwan__fzf-lua-2696/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f35de81d7cdd23d90786dbfe2378ae47ccd1eb1f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8223eb24a7adf72c4b24e04b751486b492775414 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2696/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2696/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2696/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2698/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2698/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..821d4f1540dc853235f68567e8bcad8a7bf66478 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8223eb24a7adf72c4b24e04b751486b492775414 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2698/instruction.md b/tasks/ibhagwan__fzf-lua-2698/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07ca8cbdb0399732b762ed0d653ebe126fb5c03d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(previewer): allow diff/git cmd syntax + +## Description + +Related + + + +## Summary by CodeRabbit + +## Bug Fixes +* Fixed syntax highlighting and treesitter context attachment in file previews—previously these were skipped for terminal buffers. +* Improved handling of diff and git file types to ensure proper syntax highlighting and file type-specific features are correctly applied. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2698/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2698/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d9dba96c80cca59df3e9ccc6e15616bf76dc1106 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 37412085..2d2711a0 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1184,6 +1184,11 @@ function Previewer.buffer_or_file:do_syntax(entry) + if not ft then return end + did_filetype_detect = true + end ++ if ft == "diff" or ft == "git" then ++ api.nvim_buf_call(bufnr, function() ++ api.nvim_exec_autocmds("FileType", { pattern = ft, modeline = false }) ++ end) ++ end + + -- Use buf local var as setting ft might have unintended consequences + -- used in `update_render_markdown`, `attach_snacks_image` +@@ -1366,25 +1371,23 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + -- set cursor highlights for line|col or tag + self:set_cursor_hl(entry) + +- if not utils.is_term_buffer(self.preview_bufnr) then +- local syntax = function() +- if self.syntax then +- self:do_syntax(entry) +- self:update_render_markdown() +- self:update_ts_context() +- self:attach_snacks_image_inline() +- end +- -- for attach_snacks_image_{inline,buf} +- -- https://github.com/folke/snacks.nvim/pull/1615 +- if self.preview_bufnr and vim.b[self.preview_bufnr].snacks_image_attached then +- utils.wo[self.win.preview_winid][0].winblend = 0 +- end ++ local syntax = function() ++ if self.syntax then ++ self:do_syntax(entry) ++ self:update_render_markdown() ++ self:update_ts_context() ++ self:attach_snacks_image_inline() ++ end ++ -- for attach_snacks_image_{inline,buf} ++ -- https://github.com/folke/snacks.nvim/pull/1615 ++ if self.preview_bufnr and vim.b[self.preview_bufnr].snacks_image_attached then ++ utils.wo[self.win.preview_winid][0].winblend = 0 + end +- +- -- syntax highlighting +- self:debounce("syntax", self.syntax_delay, syntax) + end + ++ -- syntax highlighting ++ self:debounce("syntax", self.syntax_delay, syntax) ++ + self:update_title(entry) + + if entry.no_scrollbar then diff --git a/tasks/ibhagwan__fzf-lua-2698/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2698/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2698/task.toml b/tasks/ibhagwan__fzf-lua-2698/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..282ddd8f786705911e02ae0cf4db84722a63c4d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2698" +description = "fix(previewer): allow diff/git cmd syntax" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "8223eb24a7adf72c4b24e04b751486b492775414" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2698" +source_access = "auto" +built_at = "2026-11-16T16:09:55.997417+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fb81234e763aa338382fe89682ec9d92ebfaed5084993dc3dfab6e2912434797" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-27T01:27:35Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 35 +difficulty = "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:01.043352+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9097e3fcd17ba432685c95d33fedda1504aad0c7acaf5a4f658507b41d38f93a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2698/tests/capture.py b/tasks/ibhagwan__fzf-lua-2698/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2698/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2698/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07ca8cbdb0399732b762ed0d653ebe126fb5c03d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(previewer): allow diff/git cmd syntax + +## Description + +Related + + + +## Summary by CodeRabbit + +## Bug Fixes +* Fixed syntax highlighting and treesitter context attachment in file previews—previously these were skipped for terminal buffers. +* Improved handling of diff and git file types to ensure proper syntax highlighting and file type-specific features are correctly applied. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2698/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2698/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d9dba96c80cca59df3e9ccc6e15616bf76dc1106 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 37412085..2d2711a0 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1184,6 +1184,11 @@ function Previewer.buffer_or_file:do_syntax(entry) + if not ft then return end + did_filetype_detect = true + end ++ if ft == "diff" or ft == "git" then ++ api.nvim_buf_call(bufnr, function() ++ api.nvim_exec_autocmds("FileType", { pattern = ft, modeline = false }) ++ end) ++ end + + -- Use buf local var as setting ft might have unintended consequences + -- used in `update_render_markdown`, `attach_snacks_image` +@@ -1366,25 +1371,23 @@ function Previewer.buffer_or_file:preview_buf_post(entry, min_winopts) + -- set cursor highlights for line|col or tag + self:set_cursor_hl(entry) + +- if not utils.is_term_buffer(self.preview_bufnr) then +- local syntax = function() +- if self.syntax then +- self:do_syntax(entry) +- self:update_render_markdown() +- self:update_ts_context() +- self:attach_snacks_image_inline() +- end +- -- for attach_snacks_image_{inline,buf} +- -- https://github.com/folke/snacks.nvim/pull/1615 +- if self.preview_bufnr and vim.b[self.preview_bufnr].snacks_image_attached then +- utils.wo[self.win.preview_winid][0].winblend = 0 +- end ++ local syntax = function() ++ if self.syntax then ++ self:do_syntax(entry) ++ self:update_render_markdown() ++ self:update_ts_context() ++ self:attach_snacks_image_inline() ++ end ++ -- for attach_snacks_image_{inline,buf} ++ -- https://github.com/folke/snacks.nvim/pull/1615 ++ if self.preview_bufnr and vim.b[self.preview_bufnr].snacks_image_attached then ++ utils.wo[self.win.preview_winid][0].winblend = 0 + end +- +- -- syntax highlighting +- self:debounce("syntax", self.syntax_delay, syntax) + end + ++ -- syntax highlighting ++ self:debounce("syntax", self.syntax_delay, syntax) ++ + self:update_title(entry) + + if entry.no_scrollbar then diff --git a/tasks/ibhagwan__fzf-lua-2698/tests/test.sh b/tasks/ibhagwan__fzf-lua-2698/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f35de81d7cdd23d90786dbfe2378ae47ccd1eb1f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8223eb24a7adf72c4b24e04b751486b492775414 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2698/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2698/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2698/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2700/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2700/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..821d4f1540dc853235f68567e8bcad8a7bf66478 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8223eb24a7adf72c4b24e04b751486b492775414 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8223eb24a7adf72c4b24e04b751486b492775414 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2700/instruction.md b/tasks/ibhagwan__fzf-lua-2700/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2cb219ab37172b3bfddad8d1f16664fe8ba9662 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: disable sendfile on android for cpu 100% + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Enhanced Linux platform detection to ensure server behavior is compatible with Neovim 0.12+ on Linux systems while excluding Android environments. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2700/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2700/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..487d7666549adc69598023d31ac23b56eb7a6875 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index a04386a9..fa584553 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -2,7 +2,8 @@ + local uv = vim.uv or vim.loop + + local _is_win = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 +-local _is_linux = vim.fn.has("linux") == 1 ++local _is_linux = vim.fn.has("linux") == 1 and ++ (vim.fn.has("nvim-0.12") == 1 and vim.fn.has("android") == 0) + + if vim.v.servername and #vim.v.servername > 0 then + pcall(vim.fn.serverstop, vim.v.servername) diff --git a/tasks/ibhagwan__fzf-lua-2700/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2700/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2700/task.toml b/tasks/ibhagwan__fzf-lua-2700/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b425d8eaa30d29161eb7be4a277c722cff6b7b7d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2700" +description = "fix: disable sendfile on android for cpu 100%" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "8223eb24a7adf72c4b24e04b751486b492775414" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2700" +source_access = "auto" +built_at = "2026-11-16T16:09:56.009521+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:79a69787507dce96f89337a6b09dff9fc49f73d59c2da6c79171260d69270b58" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-23T10:06:33Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/rpc.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.043861+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9097e3fcd17ba432685c95d33fedda1504aad0c7acaf5a4f658507b41d38f93a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2700/tests/capture.py b/tasks/ibhagwan__fzf-lua-2700/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2700/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2700/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d2cb219ab37172b3bfddad8d1f16664fe8ba9662 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: disable sendfile on android for cpu 100% + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Enhanced Linux platform detection to ensure server behavior is compatible with Neovim 0.12+ on Linux systems while excluding Android environments. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8223eb24a7ad`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2700/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2700/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..487d7666549adc69598023d31ac23b56eb7a6875 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index a04386a9..fa584553 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -2,7 +2,8 @@ + local uv = vim.uv or vim.loop + + local _is_win = vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 +-local _is_linux = vim.fn.has("linux") == 1 ++local _is_linux = vim.fn.has("linux") == 1 and ++ (vim.fn.has("nvim-0.12") == 1 and vim.fn.has("android") == 0) + + if vim.v.servername and #vim.v.servername > 0 then + pcall(vim.fn.serverstop, vim.v.servername) diff --git a/tasks/ibhagwan__fzf-lua-2700/tests/test.sh b/tasks/ibhagwan__fzf-lua-2700/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f35de81d7cdd23d90786dbfe2378ae47ccd1eb1f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8223eb24a7adf72c4b24e04b751486b492775414 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2700/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2700/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2700/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2702/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2702/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..35635f2c854180380c85b61d283660f203909d50 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f233cb2f4cf0bc56ae2b10d06f25345069fcf355 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f233cb2f4cf0bc56ae2b10d06f25345069fcf355 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f233cb2f4cf0bc56ae2b10d06f25345069fcf355 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2702/instruction.md b/tasks/ibhagwan__fzf-lua-2702/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1046e984d555a1d12eb4e091dbc4f5a1d8da3741 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(actions): copy edits before preview + +## Description + +Closes: + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Code action previews no longer mutate shared edit data, preserving the original edits when previewing multiple actions. + +* **Tests** + * Added tests that validate preview behavior to prevent regressions related to edit data mutation. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f233cb2f4cf0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2702/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2702/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c0d162e77bfc75e5c8c1e77cd943c4bb275d3c6c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/solution/patch.diff @@ -0,0 +1,98 @@ +diff --git a/lua/fzf-lua/previewer/codeaction.lua b/lua/fzf-lua/previewer/codeaction.lua +index 3bf333ee..d96ad889 100644 +--- a/lua/fzf-lua/previewer/codeaction.lua ++++ b/lua/fzf-lua/previewer/codeaction.lua +@@ -31,7 +31,8 @@ local function diff_text_edits(text_edits, bufnr, offset_encoding, diff_opts) + local orig_lines = get_lines(bufnr) + local tmpbuf = vim.api.nvim_create_buf(false, true) + vim.api.nvim_buf_set_lines(tmpbuf, 0, -1, false, orig_lines) +- vim.lsp.util.apply_text_edits(text_edits, tmpbuf, offset_encoding) ++ -- deepcopy is necessary due to the apply_text_edits's logic to change the passed edits. ++ vim.lsp.util.apply_text_edits(utils.deepcopy(text_edits), tmpbuf, offset_encoding) + local new_lines = get_lines(tmpbuf) + vim.api.nvim_buf_delete(tmpbuf, { force = true }) + ---@diagnostic disable-next-line: deprecated +diff --git a/tests/codeaction_spec.lua b/tests/codeaction_spec.lua +new file mode 100644 +index 00000000..62bc1e80 +--- /dev/null ++++ b/tests/codeaction_spec.lua +@@ -0,0 +1,78 @@ ++---@diagnostic disable: unused-local ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++ ++local T = new_set() ++ ++T["codeaction"] = new_set() ++ ++T["codeaction"]["preview does not mutate same-position text edits"] = function() ++ local utils = require("fzf-lua.utils") ++ local codeaction = require("fzf-lua.previewer.codeaction") ++ local original_lsp_get_clients = utils.lsp_get_clients ++ local bufnr = vim.api.nvim_create_buf(true, true) ++ local text_edits = { ++ { ++ range = { ++ start = { line = 0, character = 7 }, ++ ["end"] = { line = 0, character = 24 }, ++ }, ++ newText = "strings.CutSuffix", ++ }, ++ { ++ range = { ++ start = { line = 0, character = 7 }, ++ ["end"] = { line = 0, character = 24 }, ++ }, ++ newText = "strings.TrimSuffix", ++ }, ++ } ++ local before = vim.deepcopy(text_edits) ++ ++ vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { ++ "if strings.HasSuffix(name, suffix) {", ++ "\treturn strings.TrimSuffix(name, suffix)", ++ "}", ++ }) ++ ++ ---duplication is caused by the stubbign logic. ++ ---@diagnostic disable-next-line: duplicate-set-field ++ utils.lsp_get_clients = function(opts) ++ if opts.id == 1 then ++ return { ++ { ++ offset_encoding = "utf-16", ++ dynamic_capabilities = { get = function() end }, ++ supports_method = function() return false end, ++ server_capabilities = {}, ++ }, ++ } ++ end ++ return original_lsp_get_clients(opts) ++ end ++ ++ local ok, err = pcall(function() ++ local uri = vim.uri_from_bufnr(bufnr) ++ codeaction.builtin.preview_action_tuple({ ++ opts = { ++ _items = { ++ { ++ ctx = { client_id = 1, bufnr = bufnr }, ++ action = { edit = { changes = { [uri] = text_edits } } }, ++ }, ++ }, ++ }, ++ diff_opts = { ctxlen = 3 }, ++ _resolved_actions = { false }, ++ }, 1) ++ end) ++ utils.lsp_get_clients = original_lsp_get_clients ++ vim.api.nvim_buf_delete(bufnr, { force = true }) ++ ++ if not ok then error(err) end ++ eq(text_edits, before) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2702/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2702/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2702/task.toml b/tasks/ibhagwan__fzf-lua-2702/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd9bacd8f334cdc3b97ccc250f8d1898f87ee0df --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2702" +description = "fix(actions): copy edits before preview" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "f233cb2f4cf0bc56ae2b10d06f25345069fcf355" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2702" +source_access = "auto" +built_at = "2026-11-16T16:09:56.008147+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:506700320ba04910bc5df253dcda63cee9491ed368f0d13f63afb9f2cba6d3c7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-23T13:31:48Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/codeaction.lua", + "tests/codeaction_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 81 +difficulty = "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:01.044343+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c9d3883368e7e2b4c424539c7dad3fa221529686813ac640507d8052e065b03c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2702/tests/capture.py b/tasks/ibhagwan__fzf-lua-2702/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2702/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2702/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1046e984d555a1d12eb4e091dbc4f5a1d8da3741 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(actions): copy edits before preview + +## Description + +Closes: + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Code action previews no longer mutate shared edit data, preserving the original edits when previewing multiple actions. + +* **Tests** + * Added tests that validate preview behavior to prevent regressions related to edit data mutation. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f233cb2f4cf0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2702/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2702/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c0d162e77bfc75e5c8c1e77cd943c4bb275d3c6c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/tests/oracle.patch @@ -0,0 +1,98 @@ +diff --git a/lua/fzf-lua/previewer/codeaction.lua b/lua/fzf-lua/previewer/codeaction.lua +index 3bf333ee..d96ad889 100644 +--- a/lua/fzf-lua/previewer/codeaction.lua ++++ b/lua/fzf-lua/previewer/codeaction.lua +@@ -31,7 +31,8 @@ local function diff_text_edits(text_edits, bufnr, offset_encoding, diff_opts) + local orig_lines = get_lines(bufnr) + local tmpbuf = vim.api.nvim_create_buf(false, true) + vim.api.nvim_buf_set_lines(tmpbuf, 0, -1, false, orig_lines) +- vim.lsp.util.apply_text_edits(text_edits, tmpbuf, offset_encoding) ++ -- deepcopy is necessary due to the apply_text_edits's logic to change the passed edits. ++ vim.lsp.util.apply_text_edits(utils.deepcopy(text_edits), tmpbuf, offset_encoding) + local new_lines = get_lines(tmpbuf) + vim.api.nvim_buf_delete(tmpbuf, { force = true }) + ---@diagnostic disable-next-line: deprecated +diff --git a/tests/codeaction_spec.lua b/tests/codeaction_spec.lua +new file mode 100644 +index 00000000..62bc1e80 +--- /dev/null ++++ b/tests/codeaction_spec.lua +@@ -0,0 +1,78 @@ ++---@diagnostic disable: unused-local ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++ ++local T = new_set() ++ ++T["codeaction"] = new_set() ++ ++T["codeaction"]["preview does not mutate same-position text edits"] = function() ++ local utils = require("fzf-lua.utils") ++ local codeaction = require("fzf-lua.previewer.codeaction") ++ local original_lsp_get_clients = utils.lsp_get_clients ++ local bufnr = vim.api.nvim_create_buf(true, true) ++ local text_edits = { ++ { ++ range = { ++ start = { line = 0, character = 7 }, ++ ["end"] = { line = 0, character = 24 }, ++ }, ++ newText = "strings.CutSuffix", ++ }, ++ { ++ range = { ++ start = { line = 0, character = 7 }, ++ ["end"] = { line = 0, character = 24 }, ++ }, ++ newText = "strings.TrimSuffix", ++ }, ++ } ++ local before = vim.deepcopy(text_edits) ++ ++ vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { ++ "if strings.HasSuffix(name, suffix) {", ++ "\treturn strings.TrimSuffix(name, suffix)", ++ "}", ++ }) ++ ++ ---duplication is caused by the stubbign logic. ++ ---@diagnostic disable-next-line: duplicate-set-field ++ utils.lsp_get_clients = function(opts) ++ if opts.id == 1 then ++ return { ++ { ++ offset_encoding = "utf-16", ++ dynamic_capabilities = { get = function() end }, ++ supports_method = function() return false end, ++ server_capabilities = {}, ++ }, ++ } ++ end ++ return original_lsp_get_clients(opts) ++ end ++ ++ local ok, err = pcall(function() ++ local uri = vim.uri_from_bufnr(bufnr) ++ codeaction.builtin.preview_action_tuple({ ++ opts = { ++ _items = { ++ { ++ ctx = { client_id = 1, bufnr = bufnr }, ++ action = { edit = { changes = { [uri] = text_edits } } }, ++ }, ++ }, ++ }, ++ diff_opts = { ctxlen = 3 }, ++ _resolved_actions = { false }, ++ }, 1) ++ end) ++ utils.lsp_get_clients = original_lsp_get_clients ++ vim.api.nvim_buf_delete(bufnr, { force = true }) ++ ++ if not ok then error(err) end ++ eq(text_edits, before) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2702/tests/test.sh b/tasks/ibhagwan__fzf-lua-2702/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..75c570ed83dc6fe74253e8a0311d94db462ef4af --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f233cb2f4cf0bc56ae2b10d06f25345069fcf355 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2702/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2702/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2702/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2704/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2704/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6587db86e91a3bc712a4831fd9e64c65bf23444f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ffa44ee9470743a7697d28df3a1a216fdfe2b09d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ffa44ee9470743a7697d28df3a1a216fdfe2b09d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ffa44ee9470743a7697d28df3a1a216fdfe2b09d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2704/instruction.md b/tasks/ibhagwan__fzf-lua-2704/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c261b98e9f1bbf5d831d32e7b600a35c3f98631 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(oldfiles): customize shada file + +## Description + +Supply custom shada file to read using `:rshada!` (opts.shada), enables oldfiles from the cli. + + +## Summary by CodeRabbit + +* **New Features** + * Added an option to load a specific shada file to populate recent files; the file is validated and a warning is shown if missing. + +* **Documentation** + * Public configuration now documents an optional shada_file setting for the recent-files feature. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ffa44ee94707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2704/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2704/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68998f559b50fdf4c5cecc7f45524213e443bfb4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d5f88f7b..663447e8 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1010,6 +1010,8 @@ M.defaults.args = { + + ---File history (output of `:oldfiles`). + ---@class fzf-lua.config.Oldfiles: fzf-lua.config.Base ++---Optional shada file to read, see `:help shada` ++---@field shada_file? string + ---Only include files that still exist on disk. + ---@field stat_file? boolean + ---Include files opened during the current session. +diff --git a/lua/fzf-lua/providers/oldfiles.lua b/lua/fzf-lua/providers/oldfiles.lua +index 27b37744..c6f71956 100644 +--- a/lua/fzf-lua/providers/oldfiles.lua ++++ b/lua/fzf-lua/providers/oldfiles.lua +@@ -71,6 +71,16 @@ M.oldfiles = function(opts, globals) + local curr_file = vim.api.nvim_buf_get_name(curr_buf) + local sess_map = {} -- dedup files from current buffers + ++ -- read the optional shada file ++ if opts.shada_file then ++ local file = vim.fs.normalize(opts.shada_file) ++ if vim.uv.fs_stat(file) then ++ vim.cmd("rshada! " .. vim.fn.fnameescape(file)) ++ else ++ utils.warn("shada file '%s' does not exist, ignoring.", opts.shada_file) ++ end ++ end ++ + local function add_entry(x, co, force) + x = make_entry.file(x, + force and vim.tbl_deep_extend("force", {}, opts, { cwd_only = false }) or opts) diff --git a/tasks/ibhagwan__fzf-lua-2704/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2704/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2704/task.toml b/tasks/ibhagwan__fzf-lua-2704/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..12da52d18bf80afc2bddca0baee93bf6343e9c2f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2704" +description = "feat(oldfiles): customize shada file" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "ffa44ee9470743a7697d28df3a1a216fdfe2b09d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2704" +source_access = "auto" +built_at = "2026-11-16T16:09:56.006752+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ed9e8a4a26bca331cc95364d01c15ddb60908b51fca71846a1569123d81bf727" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-04-25T18:31:24Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/oldfiles.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[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:01.044818+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c250727e9fbdecd94f4c4c3c2bebecf91619f9239d4642ba7e29568df8b3e27d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2704/tests/capture.py b/tasks/ibhagwan__fzf-lua-2704/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2704/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2704/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c261b98e9f1bbf5d831d32e7b600a35c3f98631 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(oldfiles): customize shada file + +## Description + +Supply custom shada file to read using `:rshada!` (opts.shada), enables oldfiles from the cli. + + +## Summary by CodeRabbit + +* **New Features** + * Added an option to load a specific shada file to populate recent files; the file is validated and a warning is shown if missing. + +* **Documentation** + * Public configuration now documents an optional shada_file setting for the recent-files feature. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ffa44ee94707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2704/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2704/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68998f559b50fdf4c5cecc7f45524213e443bfb4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index d5f88f7b..663447e8 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1010,6 +1010,8 @@ M.defaults.args = { + + ---File history (output of `:oldfiles`). + ---@class fzf-lua.config.Oldfiles: fzf-lua.config.Base ++---Optional shada file to read, see `:help shada` ++---@field shada_file? string + ---Only include files that still exist on disk. + ---@field stat_file? boolean + ---Include files opened during the current session. +diff --git a/lua/fzf-lua/providers/oldfiles.lua b/lua/fzf-lua/providers/oldfiles.lua +index 27b37744..c6f71956 100644 +--- a/lua/fzf-lua/providers/oldfiles.lua ++++ b/lua/fzf-lua/providers/oldfiles.lua +@@ -71,6 +71,16 @@ M.oldfiles = function(opts, globals) + local curr_file = vim.api.nvim_buf_get_name(curr_buf) + local sess_map = {} -- dedup files from current buffers + ++ -- read the optional shada file ++ if opts.shada_file then ++ local file = vim.fs.normalize(opts.shada_file) ++ if vim.uv.fs_stat(file) then ++ vim.cmd("rshada! " .. vim.fn.fnameescape(file)) ++ else ++ utils.warn("shada file '%s' does not exist, ignoring.", opts.shada_file) ++ end ++ end ++ + local function add_entry(x, co, force) + x = make_entry.file(x, + force and vim.tbl_deep_extend("force", {}, opts, { cwd_only = false }) or opts) diff --git a/tasks/ibhagwan__fzf-lua-2704/tests/test.sh b/tasks/ibhagwan__fzf-lua-2704/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..89670294483ed8ca2b4de85767f556d6ec3dd277 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ffa44ee9470743a7697d28df3a1a216fdfe2b09d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2704/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2704/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2704/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2710/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2710/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4af376c5b68ae101bc8b22efebbf5698c06e100e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b437bafc981a180d609bb4092c56ce8999f7a2c4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b437bafc981a180d609bb4092c56ce8999f7a2c4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b437bafc981a180d609bb4092c56ce8999f7a2c4 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2710/instruction.md b/tasks/ibhagwan__fzf-lua-2710/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84c12bd03961eecdad6eb458e7c66db91522eda5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** ci: interrupt on ctrl-c + +## Description + +It used to work before + + +## Summary by CodeRabbit + +* **New Features** + * Test runner now handles interrupt (Ctrl+C) to stop running tests gracefully. +* **Bug Fixes** + * File-entry lookup made more permissive when matching existing buffers (may change which buffer is chosen); some debug output may appear. +* **Documentation** + * Clarified LSP code-action type annotation to match Neovim's LSP context. +* **Chores** + * Lint and CI workflow triggers refined; CI test matrix and test selection narrowed. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b437bafc981a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2710/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2710/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8c5c33d2bc97751084ce2ce7d3538e830c3758d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/solution/patch.diff @@ -0,0 +1,96 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index 1587a0d9..ff526391 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -1,6 +1,11 @@ +-on: [push, pull_request] + name: Lint + ++on: ++ push: ++ branches: [main, dev] ++ pull_request: ++ branches: "*" ++ + jobs: + lint: + runs-on: ubuntu-slim +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 663447e8..9c8dfc84 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1729,7 +1729,7 @@ M.defaults.lsp.finder = { + ---Callback to execute after applying a code action. + ---@field post_action_cb function + ---Code action context passed to the LSP server. +----@field context lsp.CodeActionContext ++---@field context vim.lsp.buf.code_action.context + ---Filter function to exclude certain code actions. + ---@field filter fun(x: lsp.CodeAction|lsp.Command):boolean + ---@field _ui_select? { kind: string } +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 95b87241..5d6c9e4e 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -454,6 +454,12 @@ function M.is_uri(str) + return str:match("^[%a%-]+://") ~= nil + end + ++-- path seps behavior https://github.com/neovim/neovim/pull/37729 ++-- luv use `\`, `nvim_buf_get_name` use `/` (on windows, by default) ++local buf_get_name = utils.__IS_WINDOWS and ++ function(buf) return (vim.api.nvim_buf_get_name(buf):gsub([[/]], [[\]])) end ++ or vim.api.nvim_buf_get_name ++ + ---@param entry string + ---@param opts fzf-lua.Config|{}? + ---@param force_uri boolean? +@@ -566,7 +572,7 @@ function M.entry_to_file(entry, opts, force_uri) + end + elseif file and #file > 0 then -- get bufnr from give path + local buf = vim.fn.bufnr(file) +- if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == (uv.fs_realpath(file) or file) then ++ if buf ~= -1 and buf_get_name(buf) == (uv.fs_realpath(file) or file) then + bufnr = buf + bufname = file + end +diff --git a/scripts/make_cli.lua b/scripts/make_cli.lua +index b2228fd9..9eaf7529 100644 +--- a/scripts/make_cli.lua ++++ b/scripts/make_cli.lua +@@ -33,4 +33,8 @@ if filter then + end + end + ++-- https://github.com/neovim/neovim/pull/36557 ++local sig = assert(vim.uv.new_signal()) ++sig:start(vim.uv.constants.SIGINT, function() MiniTest.stop() end) ++ + MiniTest.run({ collect = { find_files = find_files, filter_cases = filter_cases } }) +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index 2bee89fe..1b2f1ef0 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -393,14 +393,14 @@ describe("Testing path module", function() + col = 2, + }) + +- utils.__IS_WINDOWS = true +- eq(path.entry_to_file("C:\\Users\\foo:bar:12:3"), { +- col = 3, +- line = 12, +- path = "C:\\Users\\foo:bar", +- stripped = "C:\\Users\\foo:bar:12:3" +- }) +- utils.__IS_WINDOWS = false ++ if utils.__IS_WINDOWS then ++ eq(path.entry_to_file("C:\\Users\\foo:bar:12:3"), { ++ col = 3, ++ line = 12, ++ path = "C:\\Users\\foo:bar", ++ stripped = "C:\\Users\\foo:bar:12:3" ++ }) ++ end + end) + + it("tilde expansion", function() diff --git a/tasks/ibhagwan__fzf-lua-2710/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2710/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2710/task.toml b/tasks/ibhagwan__fzf-lua-2710/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97be7f10ad9df853e8b82c59e29bcdd5d189c0fc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2710" +description = "ci: interrupt on ctrl-c" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b437bafc981a180d609bb4092c56ce8999f7a2c4" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2710" +source_access = "auto" +built_at = "2026-11-16T16:09:55.995793+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:61e1add86fe66e34aa58247876fbb31310065bb42dc387a47deb10a651016907" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-01T15:17:10Z" +diff_format = "unified" +context_files = [ + ".github/workflows/lint.yaml", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/path.lua", + "scripts/make_cli.lua", + "tests/path_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 37 +difficulty = "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:01.045305+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e9baaf4dd3633b23763e02639807673b31e08c67ba9f9fd7926328f7b05c56cd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2710/tests/capture.py b/tasks/ibhagwan__fzf-lua-2710/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2710/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2710/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84c12bd03961eecdad6eb458e7c66db91522eda5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** ci: interrupt on ctrl-c + +## Description + +It used to work before + + +## Summary by CodeRabbit + +* **New Features** + * Test runner now handles interrupt (Ctrl+C) to stop running tests gracefully. +* **Bug Fixes** + * File-entry lookup made more permissive when matching existing buffers (may change which buffer is chosen); some debug output may appear. +* **Documentation** + * Clarified LSP code-action type annotation to match Neovim's LSP context. +* **Chores** + * Lint and CI workflow triggers refined; CI test matrix and test selection narrowed. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b437bafc981a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2710/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2710/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8c5c33d2bc97751084ce2ce7d3538e830c3758d5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/tests/oracle.patch @@ -0,0 +1,96 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index 1587a0d9..ff526391 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -1,6 +1,11 @@ +-on: [push, pull_request] + name: Lint + ++on: ++ push: ++ branches: [main, dev] ++ pull_request: ++ branches: "*" ++ + jobs: + lint: + runs-on: ubuntu-slim +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 663447e8..9c8dfc84 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1729,7 +1729,7 @@ M.defaults.lsp.finder = { + ---Callback to execute after applying a code action. + ---@field post_action_cb function + ---Code action context passed to the LSP server. +----@field context lsp.CodeActionContext ++---@field context vim.lsp.buf.code_action.context + ---Filter function to exclude certain code actions. + ---@field filter fun(x: lsp.CodeAction|lsp.Command):boolean + ---@field _ui_select? { kind: string } +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 95b87241..5d6c9e4e 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -454,6 +454,12 @@ function M.is_uri(str) + return str:match("^[%a%-]+://") ~= nil + end + ++-- path seps behavior https://github.com/neovim/neovim/pull/37729 ++-- luv use `\`, `nvim_buf_get_name` use `/` (on windows, by default) ++local buf_get_name = utils.__IS_WINDOWS and ++ function(buf) return (vim.api.nvim_buf_get_name(buf):gsub([[/]], [[\]])) end ++ or vim.api.nvim_buf_get_name ++ + ---@param entry string + ---@param opts fzf-lua.Config|{}? + ---@param force_uri boolean? +@@ -566,7 +572,7 @@ function M.entry_to_file(entry, opts, force_uri) + end + elseif file and #file > 0 then -- get bufnr from give path + local buf = vim.fn.bufnr(file) +- if buf ~= -1 and vim.api.nvim_buf_get_name(buf) == (uv.fs_realpath(file) or file) then ++ if buf ~= -1 and buf_get_name(buf) == (uv.fs_realpath(file) or file) then + bufnr = buf + bufname = file + end +diff --git a/scripts/make_cli.lua b/scripts/make_cli.lua +index b2228fd9..9eaf7529 100644 +--- a/scripts/make_cli.lua ++++ b/scripts/make_cli.lua +@@ -33,4 +33,8 @@ if filter then + end + end + ++-- https://github.com/neovim/neovim/pull/36557 ++local sig = assert(vim.uv.new_signal()) ++sig:start(vim.uv.constants.SIGINT, function() MiniTest.stop() end) ++ + MiniTest.run({ collect = { find_files = find_files, filter_cases = filter_cases } }) +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index 2bee89fe..1b2f1ef0 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -393,14 +393,14 @@ describe("Testing path module", function() + col = 2, + }) + +- utils.__IS_WINDOWS = true +- eq(path.entry_to_file("C:\\Users\\foo:bar:12:3"), { +- col = 3, +- line = 12, +- path = "C:\\Users\\foo:bar", +- stripped = "C:\\Users\\foo:bar:12:3" +- }) +- utils.__IS_WINDOWS = false ++ if utils.__IS_WINDOWS then ++ eq(path.entry_to_file("C:\\Users\\foo:bar:12:3"), { ++ col = 3, ++ line = 12, ++ path = "C:\\Users\\foo:bar", ++ stripped = "C:\\Users\\foo:bar:12:3" ++ }) ++ end + end) + + it("tilde expansion", function() diff --git a/tasks/ibhagwan__fzf-lua-2710/tests/test.sh b/tasks/ibhagwan__fzf-lua-2710/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5309ef4fe738d50118a825996df7f9fda66ebbd5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b437bafc981a180d609bb4092c56ce8999f7a2c4 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2710/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2710/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2710/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2712/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2712/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0b047832b6683d0b3cfa80f8e34a94aa929dfd00 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5b36002c54d647307339714cec47e89c2c2c50c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5b36002c54d647307339714cec47e89c2c2c50c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5b36002c54d647307339714cec47e89c2c2c50c1 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2712/instruction.md b/tasks/ibhagwan__fzf-lua-2712/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3467364b967d51521198ee2b291c5f89a28996f0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat: port fzf's config parser in lua + +## Description + +To respect user config from: $FZF_DEFAULTS_OPTS + +Fix + +AI-assisted: Gemini 2.5 Pro + + +## Summary by CodeRabbit + +* **New Features** + * Improved configuration parsing to better handle shell-like option strings (quotes, escapes, command substitutions and comments). + +* **Bug Fixes** + * Ensure the history option is populated from parsed defaults when previously unset. + +* **Tests** + * Added thorough tests covering tokenization, parsing, error cases, and option mappings for configuration parsing. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b36002c54d6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2712/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2712/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d38417fdd409f29d39e23d42028e9c6cfe0e0146 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/solution/patch.diff @@ -0,0 +1,306 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 43b7d74d..ce2f4294 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -407,6 +407,10 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + end + end + ++ if opts.fzf_opts["--history"] == nil then ++ opts.fzf_opts["--history"] = require("fzf-lua.config.parse").get()["--history"] ++ end ++ + -- Merge arrays from globals|defaults, can't use 'vim.tbl_xxx' + -- for these as they only work for maps, ie. '{ key = value }' + for _, k in ipairs({ "file_ignore_patterns" }) do +diff --git a/lua/fzf-lua/config/parse.lua b/lua/fzf-lua/config/parse.lua +new file mode 100644 +index 00000000..42193215 +--- /dev/null ++++ b/lua/fzf-lua/config/parse.lua +@@ -0,0 +1,182 @@ ++-- lua version of shellwords https://github.com/junegunn/fzf/blob/f7835825617bd38eb50349bd89fa2f39569c3068/src/options.go#L3854-L3857 ++local M = {} ++ ++local function isSpace(c) ++ return c == " " or c == "\t" or c == "\r" or c == "\n" ++end ++ ++local argNo = 0 ++local argSingle = 1 ++local argQuoted = 2 ++ ++--- Parses a shell string into arguments similar to Go's shellwords. ++--- @param line string ++--- @return string[]? args ++--- @return string? err ++M.shellparse = function(line) ++ if not line or type(line) ~= "string" then ++ return {} ++ end ++ ++ local args = {} ++ local buf = "" ++ local escaped, doubleQuoted, singleQuoted, backQuote, dollarQuote, comment = ++ false, false, false, false, false, false ++ ++ local got = argNo ++ ++ local i = 1 ++ while i <= #line do ++ local r = line:sub(i, i) ++ local continue = false ++ ++ if comment then ++ if r == "\n" then ++ comment = false ++ end ++ continue = true ++ end ++ ++ if not continue and escaped then ++ if r == "t" then r = "\t" end ++ if r == "n" then r = "\n" end ++ buf = buf .. r ++ escaped = false ++ got = argSingle ++ continue = true ++ end ++ ++ if not continue and r == "\\" then ++ if singleQuoted then ++ buf = buf .. r ++ else ++ escaped = true ++ end ++ continue = true ++ end ++ ++ if not continue and isSpace(r) then ++ if singleQuoted or doubleQuoted or backQuote or dollarQuote then ++ buf = buf .. r ++ elseif got ~= argNo then ++ args[#args + 1] = buf ++ buf = "" ++ got = argNo ++ end ++ continue = true ++ end ++ ++ if not continue then ++ if r == "`" then ++ if not singleQuoted and not doubleQuoted and not dollarQuote then ++ backQuote = not backQuote ++ end ++ elseif r == ")" then ++ if not singleQuoted and not doubleQuoted and not backQuote then ++ dollarQuote = not dollarQuote ++ end ++ elseif r == "(" then ++ if not singleQuoted and not doubleQuoted and not backQuote then ++ if not dollarQuote and buf:sub(-1) == "$" then ++ dollarQuote = true ++ buf = buf .. "(" ++ continue = true ++ else ++ return nil, "invalid command line string" ++ end ++ end ++ elseif r == '"' then ++ if not singleQuoted and not dollarQuote then ++ if doubleQuoted then got = argQuoted end ++ doubleQuoted = not doubleQuoted ++ continue = true ++ end ++ elseif r == "'" then ++ if not doubleQuoted and not dollarQuote then ++ if singleQuoted then got = argQuoted end ++ singleQuoted = not singleQuoted ++ continue = true ++ end ++ elseif r == ";" or r == "&" or r == "|" or r == "<" or r == ">" then ++ if not (escaped or singleQuoted or doubleQuoted or backQuote or dollarQuote) then ++ if r == ">" and #buf > 0 then ++ local c = buf:sub(1, 1) ++ if c >= "0" and c <= "9" then ++ got = argNo ++ end ++ end ++ break ++ end ++ elseif r == "#" then ++ -- ParseComment is true ++ if #buf == 0 and not (escaped or singleQuoted or doubleQuoted) then ++ comment = true ++ continue = true ++ end ++ end ++ end ++ ++ if not continue then ++ got = argSingle ++ buf = buf .. r ++ end ++ ++ i = i + 1 ++ end ++ ++ if got ~= argNo then ++ args[#args + 1] = buf ++ end ++ ++ if escaped or singleQuoted or doubleQuoted or backQuote or dollarQuote then ++ return nil, "invalid command line string" ++ end ++ ++ return args ++end ++ ++---@alias fzf-lua.FzfOpts { [string]: string } ++---@param line string ++---@return fzf-lua.FzfOpts ++M.parse = function(line) ++ local words = M.shellparse(line) ++ if not words then return {} end ++ local args = {} ++ -- https://github.com/junegunn/fzf/blob/f7835825617bd38eb50349bd89fa2f39569c3068/src/options.go#L2618-L2622 ++ local i = 1 ++ while i <= #words do ++ local word = words[i] ---@as string ++ if word:sub(1, 2) == "--" then ++ local field, value = word:match("^(.-)=(.*)$") ++ if field then ++ args[field] = value ++ else -- space-separated: --key value (next token doesn't start with '-') ++ local nxt = words[i + 1] ++ if nxt and nxt:sub(1, 1) ~= "-" then ++ args[word] = nxt ++ i = i + 1 ++ else ++ args[word] = true -- bare flag ++ end ++ end ++ end ++ i = i + 1 ++ end ++ return args ++end ++ ++ ++local parsed ---@type fzf-lua.FzfOpts? ++---@return fzf-lua.FzfOpts ++M.get = function() ++ if parsed then return parsed end ++ local default_opts = os.getenv("FZF_DEFAULT_OPTS") ++ local file = os.getenv("FZF_DEFAULT_OPTS_FILE") ++ local content = file and require("fzf-lua.utils").read_file(file) or nil ++ local opts1 = default_opts and M.parse(default_opts) or {} ++ local opts2 = content and M.parse(content) or {} ++ parsed = vim.tbl_deep_extend("keep", opts1, opts2) ++ return parsed ++end ++ ++return M +diff --git a/tests/config_spec.lua b/tests/config_spec.lua +new file mode 100644 +index 00000000..2da83e21 +--- /dev/null ++++ b/tests/config_spec.lua +@@ -0,0 +1,97 @@ ++local helpers = require("fzf-lua.test.helpers") ++local assert = helpers.assert ++ ++local parse = require("fzf-lua.config.parse") ++local eq = assert.are.equal ++local same = assert.are.same ++ ++describe("Testing config parser", function() ++ it("parses empty and simple strings", function() ++ same(parse.shellparse(""), {}) ++ same(parse.shellparse("foo"), { "foo" }) ++ same(parse.shellparse("foo bar"), { "foo", "bar" }) ++ same(parse.shellparse("foo\tbar\n"), { "foo", "bar" }) ++ end) ++ ++ it("handles single and double quotes", function() ++ same(parse.shellparse("--foo='bar baz'"), { "--foo=bar baz" }) ++ same(parse.shellparse('--foo="bar baz"'), { "--foo=bar baz" }) ++ same(parse.shellparse([[--foo="bar\"baz"]]), { [[--foo=bar"baz]] }) ++ same(parse.shellparse([[--foo=\'bar\ baz\']]), { [[--foo='bar baz']] }) ++ end) ++ ++ it("handles spaces in quotes and variables", function() ++ same(parse.shellparse("a b `ls`"), { "a", "b", "`ls`" }) ++ same(parse.shellparse("a $(echo b)"), { "a", "$(echo b)" }) ++ same(parse.shellparse([[$(echo "ab c")]]), { [[$(echo "ab c")]] }) ++ end) ++ ++ it("handles comments correctly", function() ++ same(parse.shellparse("a #b"), { "a" }) ++ same(parse.shellparse("a#b"), { "a#b" }) ++ same(parse.shellparse("a #b\nc"), { "a", "c" }) ++ same(parse.shellparse("a b#c"), { "a", "b#c" }) ++ same(parse.shellparse('--foo="bar #baz"'), { "--foo=bar #baz" }) ++ same(parse.shellparse('--foo="bar" #baz'), { "--foo=bar" }) ++ end) ++ ++ it("stops at certain operators", function() ++ same(parse.shellparse("a ; b"), { "a" }) ++ same(parse.shellparse("a & b"), { "a" }) ++ same(parse.shellparse("a | b"), { "a" }) ++ same(parse.shellparse("a < b"), { "a" }) ++ same(parse.shellparse("a > b"), { "a" }) ++ same(parse.shellparse("> file"), {}) ++ same(parse.shellparse("abc 2>"), { "abc" }) ++ same(parse.shellparse("2>"), {}) ++ same(parse.shellparse("abc2>"), { "abc2" }) ++ end) ++ ++ it("returns error on unclosed quotes", function() ++ local res, err = parse.shellparse('"abc') ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("'abc") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("a `b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("a $(b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ end) ++ ++ it("invalid unclosed bracket command", function() ++ local res, err = parse.shellparse("a (b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ end) ++ ++ it("tests config parser wrapper", function() ++ local res = parse.parse("") ++ same(res, {}) ++ ++ res = parse.parse("foo bar") ++ same(res, { foo = nil, bar = nil }) ++ ++ res = parse.parse("--foo") ++ same(res, { ["--foo"] = true }) ++ ++ res = parse.parse("--foo=bar") ++ same(res, { ["--foo"] = "bar" }) ++ ++ res = parse.parse("--foo='bar baz'") ++ same(res, { ["--foo"] = "bar baz" }) ++ ++ res = parse.parse("--foo 'bar baz'") ++ same(res, { ["--foo"] = "bar baz" }) ++ ++ -- When tokenizing multiple '=' ++ res = parse.parse([[--bind='ctrl-a:execute(echo "==")']]) ++ same(res, { ["--bind"] = [[ctrl-a:execute(echo "==")]] }) ++ end) ++end) diff --git a/tasks/ibhagwan__fzf-lua-2712/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2712/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2712/task.toml b/tasks/ibhagwan__fzf-lua-2712/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..adb3328a52a4428631e854cf8fc125bce62420bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2712" +description = "feat: port fzf's config parser in lua" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "5b36002c54d647307339714cec47e89c2c2c50c1" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2712" +source_access = "auto" +built_at = "2026-11-16T16:09:55.999194+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9b9557f9f7b6c85f6c4195375ee2425868a554d315ff4f9c3922b6f2b7da9579" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-02T07:38:12Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/config.lua", + "lua/fzf-lua/config/parse.lua", + "tests/config_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 283 +difficulty = "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:01.045772+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e6874d7726e5f1944d0b62175702e4784bcac11a4dcc663ae1e2bf625c6dfeaa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2712/tests/capture.py b/tasks/ibhagwan__fzf-lua-2712/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2712/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2712/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3467364b967d51521198ee2b291c5f89a28996f0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat: port fzf's config parser in lua + +## Description + +To respect user config from: $FZF_DEFAULTS_OPTS + +Fix + +AI-assisted: Gemini 2.5 Pro + + +## Summary by CodeRabbit + +* **New Features** + * Improved configuration parsing to better handle shell-like option strings (quotes, escapes, command substitutions and comments). + +* **Bug Fixes** + * Ensure the history option is populated from parsed defaults when previously unset. + +* **Tests** + * Added thorough tests covering tokenization, parsing, error cases, and option mappings for configuration parsing. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b36002c54d6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2712/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2712/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d38417fdd409f29d39e23d42028e9c6cfe0e0146 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/tests/oracle.patch @@ -0,0 +1,306 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 43b7d74d..ce2f4294 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -407,6 +407,10 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + end + end + ++ if opts.fzf_opts["--history"] == nil then ++ opts.fzf_opts["--history"] = require("fzf-lua.config.parse").get()["--history"] ++ end ++ + -- Merge arrays from globals|defaults, can't use 'vim.tbl_xxx' + -- for these as they only work for maps, ie. '{ key = value }' + for _, k in ipairs({ "file_ignore_patterns" }) do +diff --git a/lua/fzf-lua/config/parse.lua b/lua/fzf-lua/config/parse.lua +new file mode 100644 +index 00000000..42193215 +--- /dev/null ++++ b/lua/fzf-lua/config/parse.lua +@@ -0,0 +1,182 @@ ++-- lua version of shellwords https://github.com/junegunn/fzf/blob/f7835825617bd38eb50349bd89fa2f39569c3068/src/options.go#L3854-L3857 ++local M = {} ++ ++local function isSpace(c) ++ return c == " " or c == "\t" or c == "\r" or c == "\n" ++end ++ ++local argNo = 0 ++local argSingle = 1 ++local argQuoted = 2 ++ ++--- Parses a shell string into arguments similar to Go's shellwords. ++--- @param line string ++--- @return string[]? args ++--- @return string? err ++M.shellparse = function(line) ++ if not line or type(line) ~= "string" then ++ return {} ++ end ++ ++ local args = {} ++ local buf = "" ++ local escaped, doubleQuoted, singleQuoted, backQuote, dollarQuote, comment = ++ false, false, false, false, false, false ++ ++ local got = argNo ++ ++ local i = 1 ++ while i <= #line do ++ local r = line:sub(i, i) ++ local continue = false ++ ++ if comment then ++ if r == "\n" then ++ comment = false ++ end ++ continue = true ++ end ++ ++ if not continue and escaped then ++ if r == "t" then r = "\t" end ++ if r == "n" then r = "\n" end ++ buf = buf .. r ++ escaped = false ++ got = argSingle ++ continue = true ++ end ++ ++ if not continue and r == "\\" then ++ if singleQuoted then ++ buf = buf .. r ++ else ++ escaped = true ++ end ++ continue = true ++ end ++ ++ if not continue and isSpace(r) then ++ if singleQuoted or doubleQuoted or backQuote or dollarQuote then ++ buf = buf .. r ++ elseif got ~= argNo then ++ args[#args + 1] = buf ++ buf = "" ++ got = argNo ++ end ++ continue = true ++ end ++ ++ if not continue then ++ if r == "`" then ++ if not singleQuoted and not doubleQuoted and not dollarQuote then ++ backQuote = not backQuote ++ end ++ elseif r == ")" then ++ if not singleQuoted and not doubleQuoted and not backQuote then ++ dollarQuote = not dollarQuote ++ end ++ elseif r == "(" then ++ if not singleQuoted and not doubleQuoted and not backQuote then ++ if not dollarQuote and buf:sub(-1) == "$" then ++ dollarQuote = true ++ buf = buf .. "(" ++ continue = true ++ else ++ return nil, "invalid command line string" ++ end ++ end ++ elseif r == '"' then ++ if not singleQuoted and not dollarQuote then ++ if doubleQuoted then got = argQuoted end ++ doubleQuoted = not doubleQuoted ++ continue = true ++ end ++ elseif r == "'" then ++ if not doubleQuoted and not dollarQuote then ++ if singleQuoted then got = argQuoted end ++ singleQuoted = not singleQuoted ++ continue = true ++ end ++ elseif r == ";" or r == "&" or r == "|" or r == "<" or r == ">" then ++ if not (escaped or singleQuoted or doubleQuoted or backQuote or dollarQuote) then ++ if r == ">" and #buf > 0 then ++ local c = buf:sub(1, 1) ++ if c >= "0" and c <= "9" then ++ got = argNo ++ end ++ end ++ break ++ end ++ elseif r == "#" then ++ -- ParseComment is true ++ if #buf == 0 and not (escaped or singleQuoted or doubleQuoted) then ++ comment = true ++ continue = true ++ end ++ end ++ end ++ ++ if not continue then ++ got = argSingle ++ buf = buf .. r ++ end ++ ++ i = i + 1 ++ end ++ ++ if got ~= argNo then ++ args[#args + 1] = buf ++ end ++ ++ if escaped or singleQuoted or doubleQuoted or backQuote or dollarQuote then ++ return nil, "invalid command line string" ++ end ++ ++ return args ++end ++ ++---@alias fzf-lua.FzfOpts { [string]: string } ++---@param line string ++---@return fzf-lua.FzfOpts ++M.parse = function(line) ++ local words = M.shellparse(line) ++ if not words then return {} end ++ local args = {} ++ -- https://github.com/junegunn/fzf/blob/f7835825617bd38eb50349bd89fa2f39569c3068/src/options.go#L2618-L2622 ++ local i = 1 ++ while i <= #words do ++ local word = words[i] ---@as string ++ if word:sub(1, 2) == "--" then ++ local field, value = word:match("^(.-)=(.*)$") ++ if field then ++ args[field] = value ++ else -- space-separated: --key value (next token doesn't start with '-') ++ local nxt = words[i + 1] ++ if nxt and nxt:sub(1, 1) ~= "-" then ++ args[word] = nxt ++ i = i + 1 ++ else ++ args[word] = true -- bare flag ++ end ++ end ++ end ++ i = i + 1 ++ end ++ return args ++end ++ ++ ++local parsed ---@type fzf-lua.FzfOpts? ++---@return fzf-lua.FzfOpts ++M.get = function() ++ if parsed then return parsed end ++ local default_opts = os.getenv("FZF_DEFAULT_OPTS") ++ local file = os.getenv("FZF_DEFAULT_OPTS_FILE") ++ local content = file and require("fzf-lua.utils").read_file(file) or nil ++ local opts1 = default_opts and M.parse(default_opts) or {} ++ local opts2 = content and M.parse(content) or {} ++ parsed = vim.tbl_deep_extend("keep", opts1, opts2) ++ return parsed ++end ++ ++return M +diff --git a/tests/config_spec.lua b/tests/config_spec.lua +new file mode 100644 +index 00000000..2da83e21 +--- /dev/null ++++ b/tests/config_spec.lua +@@ -0,0 +1,97 @@ ++local helpers = require("fzf-lua.test.helpers") ++local assert = helpers.assert ++ ++local parse = require("fzf-lua.config.parse") ++local eq = assert.are.equal ++local same = assert.are.same ++ ++describe("Testing config parser", function() ++ it("parses empty and simple strings", function() ++ same(parse.shellparse(""), {}) ++ same(parse.shellparse("foo"), { "foo" }) ++ same(parse.shellparse("foo bar"), { "foo", "bar" }) ++ same(parse.shellparse("foo\tbar\n"), { "foo", "bar" }) ++ end) ++ ++ it("handles single and double quotes", function() ++ same(parse.shellparse("--foo='bar baz'"), { "--foo=bar baz" }) ++ same(parse.shellparse('--foo="bar baz"'), { "--foo=bar baz" }) ++ same(parse.shellparse([[--foo="bar\"baz"]]), { [[--foo=bar"baz]] }) ++ same(parse.shellparse([[--foo=\'bar\ baz\']]), { [[--foo='bar baz']] }) ++ end) ++ ++ it("handles spaces in quotes and variables", function() ++ same(parse.shellparse("a b `ls`"), { "a", "b", "`ls`" }) ++ same(parse.shellparse("a $(echo b)"), { "a", "$(echo b)" }) ++ same(parse.shellparse([[$(echo "ab c")]]), { [[$(echo "ab c")]] }) ++ end) ++ ++ it("handles comments correctly", function() ++ same(parse.shellparse("a #b"), { "a" }) ++ same(parse.shellparse("a#b"), { "a#b" }) ++ same(parse.shellparse("a #b\nc"), { "a", "c" }) ++ same(parse.shellparse("a b#c"), { "a", "b#c" }) ++ same(parse.shellparse('--foo="bar #baz"'), { "--foo=bar #baz" }) ++ same(parse.shellparse('--foo="bar" #baz'), { "--foo=bar" }) ++ end) ++ ++ it("stops at certain operators", function() ++ same(parse.shellparse("a ; b"), { "a" }) ++ same(parse.shellparse("a & b"), { "a" }) ++ same(parse.shellparse("a | b"), { "a" }) ++ same(parse.shellparse("a < b"), { "a" }) ++ same(parse.shellparse("a > b"), { "a" }) ++ same(parse.shellparse("> file"), {}) ++ same(parse.shellparse("abc 2>"), { "abc" }) ++ same(parse.shellparse("2>"), {}) ++ same(parse.shellparse("abc2>"), { "abc2" }) ++ end) ++ ++ it("returns error on unclosed quotes", function() ++ local res, err = parse.shellparse('"abc') ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("'abc") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("a `b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ ++ res, err = parse.shellparse("a $(b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ end) ++ ++ it("invalid unclosed bracket command", function() ++ local res, err = parse.shellparse("a (b") ++ eq(res, nil) ++ eq(err, "invalid command line string") ++ end) ++ ++ it("tests config parser wrapper", function() ++ local res = parse.parse("") ++ same(res, {}) ++ ++ res = parse.parse("foo bar") ++ same(res, { foo = nil, bar = nil }) ++ ++ res = parse.parse("--foo") ++ same(res, { ["--foo"] = true }) ++ ++ res = parse.parse("--foo=bar") ++ same(res, { ["--foo"] = "bar" }) ++ ++ res = parse.parse("--foo='bar baz'") ++ same(res, { ["--foo"] = "bar baz" }) ++ ++ res = parse.parse("--foo 'bar baz'") ++ same(res, { ["--foo"] = "bar baz" }) ++ ++ -- When tokenizing multiple '=' ++ res = parse.parse([[--bind='ctrl-a:execute(echo "==")']]) ++ same(res, { ["--bind"] = [[ctrl-a:execute(echo "==")]] }) ++ end) ++end) diff --git a/tasks/ibhagwan__fzf-lua-2712/tests/test.sh b/tasks/ibhagwan__fzf-lua-2712/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..34da431e66f294eb8d79f5966f4f841cb91b21d1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5b36002c54d647307339714cec47e89c2c2c50c1 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2712/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2712/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2712/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2716/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2716/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..30498b667e94f5e3a04ad6492f984167a6dddc63 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b62213f542dc7a123e1ee9b01e3833d2add59c17 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b62213f542dc7a123e1ee9b01e3833d2add59c17 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b62213f542dc7a123e1ee9b01e3833d2add59c17 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2716/instruction.md b/tasks/ibhagwan__fzf-lua-2716/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9bf9afcfdcf6ca88a6f89d880facc287c740d194 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(win): validate last winnr + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved window-context handling to avoid restoring or referencing an invalid previous window. When no suitable prior window exists, restoration is safely skipped, preventing errors and making window-related features more stable and reliable. + +* **Tests** + * Updated CI and test helpers to use Neovim stable version 0.12.2. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b62213f542dc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2716/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2716/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8687ee4fd464c013b2f593807a2189641a66ed82 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index a9f7abcb..fb01e64b 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -18,7 +18,7 @@ jobs: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] +- rev: [nightly, v0.12.1, puc-lua] ++ rev: [nightly, v0.12.2, puc-lua] + exclude: + - os: macos-latest + rev: puc-lua +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 6391af9a..42753349 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -11,7 +11,7 @@ local ctx + ---@field bufnr integer + ---@field bname string + ---@field winid integer +----@field last_winid integer ++---@field last_winid integer? + ---@field alt_bufnr integer + ---@field tabnr integer + ---@field tabh integer +@@ -52,7 +52,15 @@ M.refresh = function(opts) + bufnr = vim.api.nvim_get_current_buf(), + bname = vim.api.nvim_buf_get_name(0), + winid = vim.api.nvim_get_current_win(), +- last_winid = vim.fn.win_getid(vim.fn.winnr("#")), ++ last_winid = (function() ++ local last_winnr = vim.fn.winnr("#") ++ return last_winnr > 0 ++ -- we use this to restore the last window ++ -- ignore if both current and last are equal ++ and last_winnr ~= vim.fn.winnr() ++ and vim.fn.win_getid(last_winnr) ++ or nil ++ end)(), + alt_bufnr = vim.fn.bufnr("#"), + tabnr = vim.fn.tabpagenr(), + tabh = vim.api.nvim_win_get_tabpage(0), +diff --git a/lua/fzf-lua/test/helpers.lua b/lua/fzf-lua/test/helpers.lua +index b5918da9..2f06a3a5 100644 +--- a/lua/fzf-lua/test/helpers.lua ++++ b/lua/fzf-lua/test/helpers.lua +@@ -36,7 +36,7 @@ local os_detect = { + }, + MAC = { name = "MacOS", fn = function() return vim.fn.has("mac") == 1 end }, + LINUX = { name = "Linux", fn = function() return vim.fn.has("linux") == 1 end }, +- STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.1" end }, ++ STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.2" end }, + NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.13") == 1 end }, + } + diff --git a/tasks/ibhagwan__fzf-lua-2716/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2716/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2716/task.toml b/tasks/ibhagwan__fzf-lua-2716/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..17ab495c3dbb8721232805e5cc3953e32e801d7d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2716" +description = "fix(win): validate last winnr (closes #2714)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b62213f542dc7a123e1ee9b01e3833d2add59c17" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2716" +source_access = "auto" +built_at = "2026-11-16T16:09:55.994275+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6c795934092ef4702f905720c1dba9bb4541a3b04b3925ea89bb0d302baa521d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-02T17:20:29Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", + "lua/fzf-lua/ctx.lua", + "lua/fzf-lua/test/helpers.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[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:01.046230+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7f17edf7b6f85b4f7aedc8df58466bd9ba395d6efbc95b23673e4398476dae78" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2716/tests/capture.py b/tasks/ibhagwan__fzf-lua-2716/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2716/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2716/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9bf9afcfdcf6ca88a6f89d880facc287c740d194 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(win): validate last winnr + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved window-context handling to avoid restoring or referencing an invalid previous window. When no suitable prior window exists, restoration is safely skipped, preventing errors and making window-related features more stable and reliable. + +* **Tests** + * Updated CI and test helpers to use Neovim stable version 0.12.2. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b62213f542dc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2716/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2716/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8687ee4fd464c013b2f593807a2189641a66ed82 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index a9f7abcb..fb01e64b 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -18,7 +18,7 @@ jobs: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] +- rev: [nightly, v0.12.1, puc-lua] ++ rev: [nightly, v0.12.2, puc-lua] + exclude: + - os: macos-latest + rev: puc-lua +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 6391af9a..42753349 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -11,7 +11,7 @@ local ctx + ---@field bufnr integer + ---@field bname string + ---@field winid integer +----@field last_winid integer ++---@field last_winid integer? + ---@field alt_bufnr integer + ---@field tabnr integer + ---@field tabh integer +@@ -52,7 +52,15 @@ M.refresh = function(opts) + bufnr = vim.api.nvim_get_current_buf(), + bname = vim.api.nvim_buf_get_name(0), + winid = vim.api.nvim_get_current_win(), +- last_winid = vim.fn.win_getid(vim.fn.winnr("#")), ++ last_winid = (function() ++ local last_winnr = vim.fn.winnr("#") ++ return last_winnr > 0 ++ -- we use this to restore the last window ++ -- ignore if both current and last are equal ++ and last_winnr ~= vim.fn.winnr() ++ and vim.fn.win_getid(last_winnr) ++ or nil ++ end)(), + alt_bufnr = vim.fn.bufnr("#"), + tabnr = vim.fn.tabpagenr(), + tabh = vim.api.nvim_win_get_tabpage(0), +diff --git a/lua/fzf-lua/test/helpers.lua b/lua/fzf-lua/test/helpers.lua +index b5918da9..2f06a3a5 100644 +--- a/lua/fzf-lua/test/helpers.lua ++++ b/lua/fzf-lua/test/helpers.lua +@@ -36,7 +36,7 @@ local os_detect = { + }, + MAC = { name = "MacOS", fn = function() return vim.fn.has("mac") == 1 end }, + LINUX = { name = "Linux", fn = function() return vim.fn.has("linux") == 1 end }, +- STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.1" end }, ++ STABLE = { name = "Neovim stable", fn = function() return M.NVIM_VERSION() == "0.12.2" end }, + NIGHTLY = { name = "Neovim nightly", fn = function() return vim.fn.has("nvim-0.13") == 1 end }, + } + diff --git a/tasks/ibhagwan__fzf-lua-2716/tests/test.sh b/tasks/ibhagwan__fzf-lua-2716/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1e23af2ea5713accd3a830e7205045b723f7e851 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b62213f542dc7a123e1ee9b01e3833d2add59c17 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2716/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2716/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2716/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2718/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2718/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ba797fd013958d334cb7b3f21978043fc3b49df0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9b382a9afdb5ce91b66802d405991eb765e88d16 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9b382a9afdb5ce91b66802d405991eb765e88d16 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9b382a9afdb5ce91b66802d405991eb765e88d16 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2718/instruction.md b/tasks/ibhagwan__fzf-lua-2718/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2052da6e08831334a7746d108a6cf66ee458ed1f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** perf(ctx): skip hidden bufnr validation + +## Description + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed an issue where session state could become stale when resuming operations with the interface hidden. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b382a9afdb5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2718/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2718/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..101dee689b04947b3c013e1a9fd9439f4f7f6fab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 5f6c3ea2..32b286f7 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -43,9 +43,11 @@ M.refresh = function(opts) + -- never cleared. The below condition validates the source window when the + -- UI is not open (#907) + or (not winobj and ctx.bufnr ~= vim.api.nvim_get_current_buf()) +- -- we should never get here when fzf process is hidden unless the user requested +- -- not to resume or a different picker, i.e. hide files and open buffers +- or winobj and (winobj:hidden() or winobj:was_hidden()) ++ -- we don't get here when hidden fzf process is resumed, only when the user ++ -- starts a different picker, i.e. hide files and open buffers, in this case ++ -- we update ctx regardless of hidden buf validity as the underlying fzf ++ -- job/bufnr may have also been terminated (#2715) ++ or winobj and winobj._hidden_fzf_bufnr + then + ctx = { + mode = vim.api.nvim_get_mode().mode, diff --git a/tasks/ibhagwan__fzf-lua-2718/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2718/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2718/task.toml b/tasks/ibhagwan__fzf-lua-2718/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..24264dcae3007a6cf25ce727e7639985cafcc981 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2718" +description = "perf(ctx): skip hidden bufnr validation" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "9b382a9afdb5ce91b66802d405991eb765e88d16" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2718" +source_access = "auto" +built_at = "2026-11-16T16:09:55.992740+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:21d348a1d503e1c62fc51640f158f26908be32c3db2a6648816cd42a9e4eb2da" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-03T16:55:20Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/ctx.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[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:01.046699+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc527e069587f51043764144af864dd82a4adf22e45712d9c5e88f09f663fbf6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2718/tests/capture.py b/tasks/ibhagwan__fzf-lua-2718/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2718/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2718/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2052da6e08831334a7746d108a6cf66ee458ed1f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** perf(ctx): skip hidden bufnr validation + +## Description + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Fixed an issue where session state could become stale when resuming operations with the interface hidden. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b382a9afdb5`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2718/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2718/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..101dee689b04947b3c013e1a9fd9439f4f7f6fab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/lua/fzf-lua/ctx.lua b/lua/fzf-lua/ctx.lua +index 5f6c3ea2..32b286f7 100644 +--- a/lua/fzf-lua/ctx.lua ++++ b/lua/fzf-lua/ctx.lua +@@ -43,9 +43,11 @@ M.refresh = function(opts) + -- never cleared. The below condition validates the source window when the + -- UI is not open (#907) + or (not winobj and ctx.bufnr ~= vim.api.nvim_get_current_buf()) +- -- we should never get here when fzf process is hidden unless the user requested +- -- not to resume or a different picker, i.e. hide files and open buffers +- or winobj and (winobj:hidden() or winobj:was_hidden()) ++ -- we don't get here when hidden fzf process is resumed, only when the user ++ -- starts a different picker, i.e. hide files and open buffers, in this case ++ -- we update ctx regardless of hidden buf validity as the underlying fzf ++ -- job/bufnr may have also been terminated (#2715) ++ or winobj and winobj._hidden_fzf_bufnr + then + ctx = { + mode = vim.api.nvim_get_mode().mode, diff --git a/tasks/ibhagwan__fzf-lua-2718/tests/test.sh b/tasks/ibhagwan__fzf-lua-2718/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d91a9a0ed91ec592a2c5abef0a62ee5a2244f9b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9b382a9afdb5ce91b66802d405991eb765e88d16 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2718/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2718/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2718/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2722/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2722/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fd1cf929eb6613db5f3ad281f44e3a538770c0bb --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 33fe4b6f0c817c4d99a7baeea82c4d17e57efd64 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 33fe4b6f0c817c4d99a7baeea82c4d17e57efd64 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 33fe4b6f0c817c4d99a7baeea82c4d17e57efd64 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2722/instruction.md b/tasks/ibhagwan__fzf-lua-2722/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5635b0c8ca11600849a81280372a844015945c73 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(ui_select): align upstream opts.preview_items spec + +## Description + + +## Summary by CodeRabbit + +* **Refactor** + * Previewer now immediately displays available temporary scratch buffers, improving preview responsiveness and avoiding redundant buffer updates. + * Selection preview integration normalizes returned preview info and supplies sensible defaults for missing position data, improving cursor and position behavior. + +* **Chores** + * Public types updated to optionally track scratch-buffer references used by the previewer. + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2722) + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `33fe4b6f0c81`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2722/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2722/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2975cedde3325cb3417973086d9225dc19991630 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index e244dd7e..f5e38691 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -959,6 +959,11 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + -- kill previously running jobs + self:_stop_preview_job() + ++ if entry._scratch_buf then ++ self:set_preview_buf(entry._scratch_buf) ++ self:preview_buf_post(entry) ++ return ++ end + -- check if cached is update-to-date to be reuse + local cached, stale = self.bcache:check(entry) + entry.cached = cached +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 4374fb92..92b4352a 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -181,7 +181,17 @@ M.ui_select = function(items, ui_opts, on_choice) + _ctor = function() + local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() + ---@diagnostic disable-next-line: unused +- function previewer:parse_entry(entry_str, cb) return ui_opts.preview_item(entry_str, cb) end ++ function previewer:parse_entry(entry_str, cb) ++ local res = assert(ui_opts.preview_item(entry_str, cb)) ++ local pos_start, pos_end = res.pos, res.pos_end ++ return { ++ _scratch_buf = res.buf, ++ line = pos_start and pos_start[1] or 1, ++ col = pos_start and pos_start[2] or 1, ++ end_line = pos_end and pos_end[1] or 1, ++ end_col = pos_end and pos_end[2] or 1, ++ } ++ end + + return previewer + end +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 4393e394..2cafeddd 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -39,6 +39,7 @@ local FzfLua = require("fzf-lua") + ---@field end_col? integer 1-based + ---@field open_term? boolean open_term for content (cmd always open_term) + ---@field cache_key? any unique cache key for entry (to reuse preview buffer) ++---@field _scratch_buf? integer "unmanaged" buffer + + ---@class fzf-lua.keymap.Entry: fzf-lua.buffer_or_file.Entry + ---@field vmap string? diff --git a/tasks/ibhagwan__fzf-lua-2722/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2722/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2722/task.toml b/tasks/ibhagwan__fzf-lua-2722/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c5429b4395af88f7dd6aacd1bc633277f68ae237 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2722" +description = "fix(ui_select): align upstream opts.preview_items spec" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "33fe4b6f0c817c4d99a7baeea82c4d17e57efd64" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2722" +source_access = "auto" +built_at = "2026-11-16T16:09:55.986106+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d63c70653c68be5cf6c72fd9cd0f760942ea98e7e8169e8f41d8145f263ba858" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-09T13:27:36Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", + "lua/fzf-lua/providers/ui_select.lua", + "lua/fzf-lua/types.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[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:01.047201+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:50f908e09eeeb86783d29ffe2d995c20192568f998f5734e71b4d9e40e43a7fa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2722/tests/capture.py b/tasks/ibhagwan__fzf-lua-2722/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2722/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2722/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5635b0c8ca11600849a81280372a844015945c73 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(ui_select): align upstream opts.preview_items spec + +## Description + + +## Summary by CodeRabbit + +* **Refactor** + * Previewer now immediately displays available temporary scratch buffers, improving preview responsiveness and avoiding redundant buffer updates. + * Selection preview integration normalizes returned preview info and supplies sensible defaults for missing position data, improving cursor and position behavior. + +* **Chores** + * Public types updated to optionally track scratch-buffer references used by the previewer. + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2722) + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `33fe4b6f0c81`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2722/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2722/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2975cedde3325cb3417973086d9225dc19991630 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index e244dd7e..f5e38691 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -959,6 +959,11 @@ function Previewer.buffer_or_file:populate_preview_buf(entry_str) + -- kill previously running jobs + self:_stop_preview_job() + ++ if entry._scratch_buf then ++ self:set_preview_buf(entry._scratch_buf) ++ self:preview_buf_post(entry) ++ return ++ end + -- check if cached is update-to-date to be reuse + local cached, stale = self.bcache:check(entry) + entry.cached = cached +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 4374fb92..92b4352a 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -181,7 +181,17 @@ M.ui_select = function(items, ui_opts, on_choice) + _ctor = function() + local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() + ---@diagnostic disable-next-line: unused +- function previewer:parse_entry(entry_str, cb) return ui_opts.preview_item(entry_str, cb) end ++ function previewer:parse_entry(entry_str, cb) ++ local res = assert(ui_opts.preview_item(entry_str, cb)) ++ local pos_start, pos_end = res.pos, res.pos_end ++ return { ++ _scratch_buf = res.buf, ++ line = pos_start and pos_start[1] or 1, ++ col = pos_start and pos_start[2] or 1, ++ end_line = pos_end and pos_end[1] or 1, ++ end_col = pos_end and pos_end[2] or 1, ++ } ++ end + + return previewer + end +diff --git a/lua/fzf-lua/types.lua b/lua/fzf-lua/types.lua +index 4393e394..2cafeddd 100644 +--- a/lua/fzf-lua/types.lua ++++ b/lua/fzf-lua/types.lua +@@ -39,6 +39,7 @@ local FzfLua = require("fzf-lua") + ---@field end_col? integer 1-based + ---@field open_term? boolean open_term for content (cmd always open_term) + ---@field cache_key? any unique cache key for entry (to reuse preview buffer) ++---@field _scratch_buf? integer "unmanaged" buffer + + ---@class fzf-lua.keymap.Entry: fzf-lua.buffer_or_file.Entry + ---@field vmap string? diff --git a/tasks/ibhagwan__fzf-lua-2722/tests/test.sh b/tasks/ibhagwan__fzf-lua-2722/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..be1665429bc50e0e799540e41c594432e4480cde --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 33fe4b6f0c817c4d99a7baeea82c4d17e57efd64 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2722/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2722/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2722/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2727/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2727/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a7258a0cad6601f0f8c91f3a0f98ee4a483389c5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97376e364f51f1b5ae3efaa3eb2e929430ca8419 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97376e364f51f1b5ae3efaa3eb2e929430ca8419 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97376e364f51f1b5ae3efaa3eb2e929430ca8419 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2727/instruction.md b/tasks/ibhagwan__fzf-lua-2727/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a79712803dcdfe36134c7a37431f8047afdf58c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(health): skip --version for Windows built-ins and fix CRLF + +## Description + +1. On Japanese Windows, `find --version` invokes Windows' system `find.exe` which outputs an error in CP932 encoding, causing garbled text in `:checkhealth`. Also, `dir` has the same issue. + +2. Skip `--version` for these Windows built-ins and report them as available without a version string. Also switch to `utils.io_system()` to avoid CRLF-corrupted version strings on Windows. + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved tool detection to use more reliable version checking mechanism. + * Added Windows compatibility for built-in commands to prevent UTF-8 encoding errors. + * Enhanced version string retrieval for accurate tool identification. + + + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2727) + + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97376e364f51`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2727/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2727/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..777fccdf3dc931d7721da55dfba8e4277c93b29f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/_health.lua b/lua/fzf-lua/_health.lua +index dc70896f..afd3734b 100644 +--- a/lua/fzf-lua/_health.lua ++++ b/lua/fzf-lua/_health.lua +@@ -17,9 +17,14 @@ function M.check() + warn("'" .. tool .. "' not found") + end + else +- local version = vim.fn.system(tool .. " --version") or "" +- version = vim.trim(assert(vim.split(version, "\n")[1])) +- local is_ok = vim.v.shell_error == 0 ++ -- Windows built-in tools don't support --version and output non-UTF-8 error messages ++ if is_win and (tool == "find" or tool == "dir") then ++ ok("'" .. tool .. "' (Windows built-in)") ++ return true ++ end ++ local out, rc = utils.io_system({ tool, "--version" }) ++ local version = vim.trim(vim.split(out, "\n")[1] or "") ++ local is_ok = rc == 0 + (is_ok and ok or error)("'" .. tool .. "' `" .. version .. "`") + return true + end diff --git a/tasks/ibhagwan__fzf-lua-2727/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2727/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2727/task.toml b/tasks/ibhagwan__fzf-lua-2727/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b2023a48cb55b99dd903d1d7996b5166b8cdc74f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2727" +description = "fix(health): skip --version for Windows built-ins and fix CRLF" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "97376e364f51f1b5ae3efaa3eb2e929430ca8419" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2727" +source_access = "auto" +built_at = "2026-11-16T16:09:55.989215+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2240dee135ac624854f5a946d2153b10ddf4b95f3f5c54b654deb2431abb0488" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-14T11:16:17Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/_health.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[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:01.047670+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c0b45208e2084814714dd295cf6fbfafbbfe3124d7a8479c07df665a9fb2203f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2727/tests/capture.py b/tasks/ibhagwan__fzf-lua-2727/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2727/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2727/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a79712803dcdfe36134c7a37431f8047afdf58c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(health): skip --version for Windows built-ins and fix CRLF + +## Description + +1. On Japanese Windows, `find --version` invokes Windows' system `find.exe` which outputs an error in CP932 encoding, causing garbled text in `:checkhealth`. Also, `dir` has the same issue. + +2. Skip `--version` for these Windows built-ins and report them as available without a version string. Also switch to `utils.io_system()` to avoid CRLF-corrupted version strings on Windows. + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved tool detection to use more reliable version checking mechanism. + * Added Windows compatibility for built-in commands to prevent UTF-8 encoding errors. + * Enhanced version string retrieval for accurate tool identification. + + + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2727) + + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97376e364f51`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2727/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2727/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..777fccdf3dc931d7721da55dfba8e4277c93b29f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/lua/fzf-lua/_health.lua b/lua/fzf-lua/_health.lua +index dc70896f..afd3734b 100644 +--- a/lua/fzf-lua/_health.lua ++++ b/lua/fzf-lua/_health.lua +@@ -17,9 +17,14 @@ function M.check() + warn("'" .. tool .. "' not found") + end + else +- local version = vim.fn.system(tool .. " --version") or "" +- version = vim.trim(assert(vim.split(version, "\n")[1])) +- local is_ok = vim.v.shell_error == 0 ++ -- Windows built-in tools don't support --version and output non-UTF-8 error messages ++ if is_win and (tool == "find" or tool == "dir") then ++ ok("'" .. tool .. "' (Windows built-in)") ++ return true ++ end ++ local out, rc = utils.io_system({ tool, "--version" }) ++ local version = vim.trim(vim.split(out, "\n")[1] or "") ++ local is_ok = rc == 0 + (is_ok and ok or error)("'" .. tool .. "' `" .. version .. "`") + return true + end diff --git a/tasks/ibhagwan__fzf-lua-2727/tests/test.sh b/tasks/ibhagwan__fzf-lua-2727/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..414b604610e4286a29f3405c58260ccab8978baa --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 97376e364f51f1b5ae3efaa3eb2e929430ca8419 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2727/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2727/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2727/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2733/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2733/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..17ebbf891911fb1d9d3fc6f7908741c89770609f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3ff77862f6c62f7b850668435ae43aa026de8758 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3ff77862f6c62f7b850668435ae43aa026de8758 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3ff77862f6c62f7b850668435ae43aa026de8758 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2733/instruction.md b/tasks/ibhagwan__fzf-lua-2733/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34f5652412c114782b4842b2bd0a575746a40c39 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: correctly vim.schedule the exit + +## Description + +My word here is wrong: + +I didn't look the code carefully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3ff77862f6c6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2733/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2733/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..15a962071a5b0416f91753f1898a92733f2bce00 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/libuv.lua b/lua/fzf-lua/libuv.lua +index 3038f24f..f7d1dec6 100644 +--- a/lua/fzf-lua/libuv.lua ++++ b/lua/fzf-lua/libuv.lua +@@ -547,9 +547,9 @@ M.spawn_stdio = function(opts) + local on_finish = function(code) + pipe_close(stdout) + pipe_close(stderr) +- if vim.in_fast_event() and fn_postprocess then ++ if vim.in_fast_event() then + vim.schedule(function() +- fn_postprocess(opts) ++ if fn_postprocess then fn_postprocess(opts) end + exit(code) + end) + else diff --git a/tasks/ibhagwan__fzf-lua-2733/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2733/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2733/task.toml b/tasks/ibhagwan__fzf-lua-2733/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b2b499dec76efba0f05a6263d78bfa90afd0a95b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2733" +description = "fix: correctly vim.schedule the exit" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "3ff77862f6c62f7b850668435ae43aa026de8758" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2733" +source_access = "auto" +built_at = "2026-11-16T16:09:55.987563+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e3c0877327439063004a8a598e7f068e701d174f90475c3137349b3510444cf0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-21T03:01:30Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/libuv.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.048131+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38936b1de80f15ed520370bfc3fc3597c9b074af63f9480334b080238eb58a4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2733/tests/capture.py b/tasks/ibhagwan__fzf-lua-2733/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2733/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2733/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34f5652412c114782b4842b2bd0a575746a40c39 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: correctly vim.schedule the exit + +## Description + +My word here is wrong: + +I didn't look the code carefully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3ff77862f6c6`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2733/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2733/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..15a962071a5b0416f91753f1898a92733f2bce00 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/libuv.lua b/lua/fzf-lua/libuv.lua +index 3038f24f..f7d1dec6 100644 +--- a/lua/fzf-lua/libuv.lua ++++ b/lua/fzf-lua/libuv.lua +@@ -547,9 +547,9 @@ M.spawn_stdio = function(opts) + local on_finish = function(code) + pipe_close(stdout) + pipe_close(stderr) +- if vim.in_fast_event() and fn_postprocess then ++ if vim.in_fast_event() then + vim.schedule(function() +- fn_postprocess(opts) ++ if fn_postprocess then fn_postprocess(opts) end + exit(code) + end) + else diff --git a/tasks/ibhagwan__fzf-lua-2733/tests/test.sh b/tasks/ibhagwan__fzf-lua-2733/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8384275e3a90fd8bfd4cf2c9f8368356a8de95cd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3ff77862f6c62f7b850668435ae43aa026de8758 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2733/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2733/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2733/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2734/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2734/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a6ff8a822e0f8399ee0d6f20bdc624f8aa4119d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 71b45a044c4ef6ecb1910880ef642d5a0e1c02e9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 71b45a044c4ef6ecb1910880ef642d5a0e1c02e9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 71b45a044c4ef6ecb1910880ef642d5a0e1c02e9 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2734/instruction.md b/tasks/ibhagwan__fzf-lua-2734/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00ce827cf8413ea41a7ed44d254f0db5139f6b3f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** refactor(buffers): remove spurious nvim-treesitter dependency check + +## Description + +The `treesitter` picker previously checked for the presence of the external `nvim-treesitter` plugin before proceeding, but this check was unnecessary - since the [current implementation now uses Neovim's built-in `vim.treesitter` API](https://github.com/tienshuoc/fzf-lua/blob/9f5e0a22739697ebe73f27acd4c1897be123056b/lua/fzf-lua/providers/buffers.lua#L505), not `nvim-treesitter`. + +This creates an unnecessary dependency for users trying to use the treesitter function. + +### Changes +- Removed the `pcall(require, "nvim-treesitter")` check from + `M.treesitter()` in `lua/fzf-lua/providers/buffers.lua` +- The existing `has_ts_parser()` validation already uses built-in APIs and + provides appropriate error messaging + + + +## Summary by CodeRabbit + +* **Refactor** + * Simplified treesitter integration by removing an explicit dependency availability check from the buffer provider. + + + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2734?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) + + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `71b45a044c4e`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2734/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2734/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..167d8413aa97b1d0087f7d5e16088cfa0976306b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index 6ebac2aa..bf4ba31a 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -495,12 +495,6 @@ M.treesitter = function(opts) + opts = config.normalize_opts(opts, "treesitter") + if not opts then return end + +- local __has_ts, _ = pcall(require, "nvim-treesitter") +- if not __has_ts then +- utils.info("Treesitter requires 'nvim-treesitter'.") +- return +- end +- + -- Default to current buffer + local bufnr0 = utils.tointeger(opts.bufnr) or vim.api.nvim_get_current_buf() + local bufname0 = path.basename(vim.api.nvim_buf_get_name(bufnr0)) diff --git a/tasks/ibhagwan__fzf-lua-2734/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2734/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2734/task.toml b/tasks/ibhagwan__fzf-lua-2734/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cad956d1ef0d95411928de6198529f67dc4d18ae --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2734" +description = "refactor(buffers): remove spurious nvim-treesitter dependency check" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "71b45a044c4ef6ecb1910880ef642d5a0e1c02e9" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2734" +source_access = "auto" +built_at = "2026-11-16T16:09:55.984586+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:87367aa34271ca009e6629e53264758d4ffd5fa3a1f74a0c127cc064f4daa428" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-24T14:12:10Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/buffers.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.048610+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4d092410786bf7961a99ffb199ca877825cb131d7ccf5894b8c68c71fd2cc8bb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2734/tests/capture.py b/tasks/ibhagwan__fzf-lua-2734/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2734/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2734/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00ce827cf8413ea41a7ed44d254f0db5139f6b3f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** refactor(buffers): remove spurious nvim-treesitter dependency check + +## Description + +The `treesitter` picker previously checked for the presence of the external `nvim-treesitter` plugin before proceeding, but this check was unnecessary - since the [current implementation now uses Neovim's built-in `vim.treesitter` API](https://github.com/tienshuoc/fzf-lua/blob/9f5e0a22739697ebe73f27acd4c1897be123056b/lua/fzf-lua/providers/buffers.lua#L505), not `nvim-treesitter`. + +This creates an unnecessary dependency for users trying to use the treesitter function. + +### Changes +- Removed the `pcall(require, "nvim-treesitter")` check from + `M.treesitter()` in `lua/fzf-lua/providers/buffers.lua` +- The existing `has_ts_parser()` validation already uses built-in APIs and + provides appropriate error messaging + + + +## Summary by CodeRabbit + +* **Refactor** + * Simplified treesitter integration by removing an explicit dependency availability check from the buffer provider. + + + +[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/ibhagwan/fzf-lua/pull/2734?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) + + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `71b45a044c4e`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2734/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2734/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..167d8413aa97b1d0087f7d5e16088cfa0976306b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index 6ebac2aa..bf4ba31a 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -495,12 +495,6 @@ M.treesitter = function(opts) + opts = config.normalize_opts(opts, "treesitter") + if not opts then return end + +- local __has_ts, _ = pcall(require, "nvim-treesitter") +- if not __has_ts then +- utils.info("Treesitter requires 'nvim-treesitter'.") +- return +- end +- + -- Default to current buffer + local bufnr0 = utils.tointeger(opts.bufnr) or vim.api.nvim_get_current_buf() + local bufname0 = path.basename(vim.api.nvim_buf_get_name(bufnr0)) diff --git a/tasks/ibhagwan__fzf-lua-2734/tests/test.sh b/tasks/ibhagwan__fzf-lua-2734/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..55b84112aba0cd31deeacb4bcd56e8dbee9fc780 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 71b45a044c4ef6ecb1910880ef642d5a0e1c02e9 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2734/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2734/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2734/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2738/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2738/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..28e8ac230d791c4e4fb837a656f7f0681a68905b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2738/instruction.md b/tasks/ibhagwan__fzf-lua-2738/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90100e2c1497cd93817fc9c9e626d5963c8bdde2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(grep): grep_cword fails for words starting/ending with non-word chars + +## Description + +If `iskeyword` contains a character that `rg` does not consider a word character (e.g. `$`) then `grep_cword` will fail if the word starts or ends with such a character. + +For example if `$` is in `iskeyword` then for `demo$` the regex will be `\bdemo\$\b` - but `rg` does not consider `$` to be a word character so the `\b` will never match. + +The suggested fix here leaves away the `\b` in such cases. It's not as sharp as `\b` matching anymore but I'd say that's more correct than no results at all. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved word-boundary handling when searching for the word under the cursor: searches now use a safer escaping routine and apply word boundaries only when appropriate, preventing missed or incorrect matches. + * Ensures grep and tag searches produce more accurate results for edge-case words. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fea9eedc6894`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2738/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2738/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..069438a8bf919658ee14b00d8c6fd0d616ab8ee1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/lua/fzf-lua/providers/grep.lua b/lua/fzf-lua/providers/grep.lua +index 35483fe5..9a3bf2bb 100644 +--- a/lua/fzf-lua/providers/grep.lua ++++ b/lua/fzf-lua/providers/grep.lua +@@ -266,7 +266,7 @@ M.grep_cword = function(opts) + opts = opts or {} + opts.no_esc = true + -- match whole words only (#968) +- opts.search = [[\b]] .. utils.rg_escape(vim.fn.expand("")) .. [[\b]] ++ opts.search = utils.rg_escape_cword(vim.fn.expand("")) + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/providers/tags.lua b/lua/fzf-lua/providers/tags.lua +index a9b6146c..100ed90f 100644 +--- a/lua/fzf-lua/providers/tags.lua ++++ b/lua/fzf-lua/providers/tags.lua +@@ -251,7 +251,7 @@ end + M.grep_cword = function(opts) + if not opts then opts = {} end + opts.no_esc = true +- opts.search = [[\b]] .. utils.rg_escape(vim.fn.expand("")) .. [[\b]] ++ opts.search = utils.rg_escape_cword(vim.fn.expand("")) + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index cebb1b27..89a986f4 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -245,6 +245,17 @@ function M.rg_escape(str) + return ret + end + ++--- Escape a word and wrap it in `\b` word boundaries (#968), but only on edges ++--- that are word characters: a `\b` next to a non-word char (e.g. a cword ++--- ending in `$`) can never match and would yield no results. ++--- @param word string ++--- @return string ++function M.rg_escape_cword(word) ++ local bl = word:match("^[%w_]") and [[\b]] or "" ++ local br = word:match("[%w_]$") and [[\b]] or "" ++ return bl .. M.rg_escape(word) .. br ++end ++ + ---@param str string + ---@return string + function M.regex_to_magic(str) diff --git a/tasks/ibhagwan__fzf-lua-2738/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2738/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2738/task.toml b/tasks/ibhagwan__fzf-lua-2738/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ccee283e15de68df6b25124bf245fd0d9628aa43 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2738" +description = "fix(grep): grep_cword fails for words starting/ending with non-word chars" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "fea9eedc6894c44d44cbb772a5cd11c93b82d7a1" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2738" +source_access = "auto" +built_at = "2026-11-16T16:09:55.979770+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9f7f4ad043b25845aece892ec98d474d39dfb56c805fc36a3266fb719447fd46" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-01T23:19:26Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/grep.lua", + "lua/fzf-lua/providers/tags.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[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:01.049094+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:21e9a8811a6efbcb06fc92cf189bd1d1cfe7c7759bd37090d8607a59dfb7614e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2738/tests/capture.py b/tasks/ibhagwan__fzf-lua-2738/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2738/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2738/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90100e2c1497cd93817fc9c9e626d5963c8bdde2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(grep): grep_cword fails for words starting/ending with non-word chars + +## Description + +If `iskeyword` contains a character that `rg` does not consider a word character (e.g. `$`) then `grep_cword` will fail if the word starts or ends with such a character. + +For example if `$` is in `iskeyword` then for `demo$` the regex will be `\bdemo\$\b` - but `rg` does not consider `$` to be a word character so the `\b` will never match. + +The suggested fix here leaves away the `\b` in such cases. It's not as sharp as `\b` matching anymore but I'd say that's more correct than no results at all. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved word-boundary handling when searching for the word under the cursor: searches now use a safer escaping routine and apply word boundaries only when appropriate, preventing missed or incorrect matches. + * Ensures grep and tag searches produce more accurate results for edge-case words. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fea9eedc6894`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2738/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2738/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..069438a8bf919658ee14b00d8c6fd0d616ab8ee1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/lua/fzf-lua/providers/grep.lua b/lua/fzf-lua/providers/grep.lua +index 35483fe5..9a3bf2bb 100644 +--- a/lua/fzf-lua/providers/grep.lua ++++ b/lua/fzf-lua/providers/grep.lua +@@ -266,7 +266,7 @@ M.grep_cword = function(opts) + opts = opts or {} + opts.no_esc = true + -- match whole words only (#968) +- opts.search = [[\b]] .. utils.rg_escape(vim.fn.expand("")) .. [[\b]] ++ opts.search = utils.rg_escape_cword(vim.fn.expand("")) + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/providers/tags.lua b/lua/fzf-lua/providers/tags.lua +index a9b6146c..100ed90f 100644 +--- a/lua/fzf-lua/providers/tags.lua ++++ b/lua/fzf-lua/providers/tags.lua +@@ -251,7 +251,7 @@ end + M.grep_cword = function(opts) + if not opts then opts = {} end + opts.no_esc = true +- opts.search = [[\b]] .. utils.rg_escape(vim.fn.expand("")) .. [[\b]] ++ opts.search = utils.rg_escape_cword(vim.fn.expand("")) + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index cebb1b27..89a986f4 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -245,6 +245,17 @@ function M.rg_escape(str) + return ret + end + ++--- Escape a word and wrap it in `\b` word boundaries (#968), but only on edges ++--- that are word characters: a `\b` next to a non-word char (e.g. a cword ++--- ending in `$`) can never match and would yield no results. ++--- @param word string ++--- @return string ++function M.rg_escape_cword(word) ++ local bl = word:match("^[%w_]") and [[\b]] or "" ++ local br = word:match("[%w_]$") and [[\b]] or "" ++ return bl .. M.rg_escape(word) .. br ++end ++ + ---@param str string + ---@return string + function M.regex_to_magic(str) diff --git a/tasks/ibhagwan__fzf-lua-2738/tests/test.sh b/tasks/ibhagwan__fzf-lua-2738/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97429aa8fafa062e2372c728565a4a79af0c2fb2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2738/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2738/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2738/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2739/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2739/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..209e6eb761c7eab0ec600417d363abcf77ffdcce --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e3a71496027f2e3c4a60340170c04d66053d5c4c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e3a71496027f2e3c4a60340170c04d66053d5c4c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e3a71496027f2e3c4a60340170c04d66053d5c4c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2739/instruction.md b/tasks/ibhagwan__fzf-lua-2739/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1940624e5c917c2a4628bcf89fd2c694eab4f620 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** fix(win): "E749: Empty buffer" on closing fzf due to continuous "|" + +## Description + +Bug: If `cmd` contains empty string "", after concatenation the concatenated command will contains continuous separator "|", e.g. ":1resize 9|vert :1resize 103|||:1resize 9|vert :1resize 103|||", running this command through `vim.cmd()` will cause error: "E749: Empty buffer". + +image + + +Fix: Filter out empty commands in `cmd`. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable restoration of split windows and sizes when closing temporary windows; prevents running empty or invalid restore commands to avoid spurious behavior. + * Ensures only valid resize fragments are applied during restore, reducing edge-case failures. + +* **Refactor** + * Internal cleanup of window-restoration logic for clearer, safer execution and easier maintenance. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e3a71496027f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2739/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2739/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4eb4b34082466cdbe2389a850d86b09ac46e6e86 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/solution/patch.diff @@ -0,0 +1,24 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 5af35b9e..3b5873df 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1066,11 +1066,14 @@ function FzfWin:create() + -- if we're not doing this the result might be all over the place + local winnrs = vim.tbl_map(api.nvim_win_get_number, api.nvim_tabpage_list_wins(0)) + local parts = vim.split(winrestcmd, "|") +- local cmd = vim.tbl_map(function(cmd_part) +- local winnr = tonumber(cmd_part:match("(.)resize")) +- return utils.tbl_contains(winnrs, winnr) and cmd_part or "" +- end, parts) +- vim.cmd(table.concat(cmd, "|")) ++ local cmd = {} ++ for _, cmd_part in ipairs(parts) do ++ local winnr = tonumber(cmd_part:match("(%d+)resize")) ++ if utils.tbl_contains(winnrs, winnr) then ++ table.insert(cmd, cmd_part) ++ end ++ end ++ if #cmd > 0 then vim.cmd(table.concat(cmd, "|")) end + -- Also restore cmdheight, will be wrong if vim resized (#1462) + vim.o.cmdheight = cmdheight + end diff --git a/tasks/ibhagwan__fzf-lua-2739/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2739/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2739/task.toml b/tasks/ibhagwan__fzf-lua-2739/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c8a92d32ae7a7e2d7742707720cea3ea40229acf --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2739" +description = "fix(win): \"E749: Empty buffer\" on closing fzf due to continuous \"|\"" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "e3a71496027f2e3c4a60340170c04d66053d5c4c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2739" +source_access = "auto" +built_at = "2026-11-16T16:09:55.981238+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4e61b6a36db8367394167fb2d550517391aa631234f6a606a6b686727ca00cc5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-01T00:37:03Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[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:01.049566+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6415bd63d79e3c2a0bd545586ee1b8074a87822a9e1d1e977840f51ec726c86d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2739/tests/capture.py b/tasks/ibhagwan__fzf-lua-2739/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2739/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2739/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1940624e5c917c2a4628bcf89fd2c694eab4f620 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** fix(win): "E749: Empty buffer" on closing fzf due to continuous "|" + +## Description + +Bug: If `cmd` contains empty string "", after concatenation the concatenated command will contains continuous separator "|", e.g. ":1resize 9|vert :1resize 103|||:1resize 9|vert :1resize 103|||", running this command through `vim.cmd()` will cause error: "E749: Empty buffer". + +image + + +Fix: Filter out empty commands in `cmd`. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * More reliable restoration of split windows and sizes when closing temporary windows; prevents running empty or invalid restore commands to avoid spurious behavior. + * Ensures only valid resize fragments are applied during restore, reducing edge-case failures. + +* **Refactor** + * Internal cleanup of window-restoration logic for clearer, safer execution and easier maintenance. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e3a71496027f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2739/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2739/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4eb4b34082466cdbe2389a850d86b09ac46e6e86 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/tests/oracle.patch @@ -0,0 +1,24 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 5af35b9e..3b5873df 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1066,11 +1066,14 @@ function FzfWin:create() + -- if we're not doing this the result might be all over the place + local winnrs = vim.tbl_map(api.nvim_win_get_number, api.nvim_tabpage_list_wins(0)) + local parts = vim.split(winrestcmd, "|") +- local cmd = vim.tbl_map(function(cmd_part) +- local winnr = tonumber(cmd_part:match("(.)resize")) +- return utils.tbl_contains(winnrs, winnr) and cmd_part or "" +- end, parts) +- vim.cmd(table.concat(cmd, "|")) ++ local cmd = {} ++ for _, cmd_part in ipairs(parts) do ++ local winnr = tonumber(cmd_part:match("(%d+)resize")) ++ if utils.tbl_contains(winnrs, winnr) then ++ table.insert(cmd, cmd_part) ++ end ++ end ++ if #cmd > 0 then vim.cmd(table.concat(cmd, "|")) end + -- Also restore cmdheight, will be wrong if vim resized (#1462) + vim.o.cmdheight = cmdheight + end diff --git a/tasks/ibhagwan__fzf-lua-2739/tests/test.sh b/tasks/ibhagwan__fzf-lua-2739/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f03588059405b9b932f4b624bbde14d2af040e7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e3a71496027f2e3c4a60340170c04d66053d5c4c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2739/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2739/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2739/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2740/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2740/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..28e8ac230d791c4e4fb837a656f7f0681a68905b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2740/instruction.md b/tasks/ibhagwan__fzf-lua-2740/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..562c2f2dbf256c0625041ab2b0fbcea662f884e0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci: sync mini.test upstream change + +## Description + +Fix failure in https://github.com/ibhagwan/fzf-lua/actions/runs/26711878681/job/78723449441?pr=2739. + + +## Summary by CodeRabbit + +* **Tests** + * Improved screenshot comparison to correctly handle multi-width characters by aligning and padding display cells, improving visual regression accuracy for wide-character content. +* **Chores** + * Adjusted test startup: ensure the code is loaded in minimal test environments and remove redundant early loading from the CLI test runner. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fea9eedc6894`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2740/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2740/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ff7c5a56be1f2353d813be5953c79a46c53d7f7b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/solution/patch.diff @@ -0,0 +1,71 @@ +diff --git a/lua/fzf-lua/test/screenshot.lua b/lua/fzf-lua/test/screenshot.lua +index 3e3eedb4..8ebe6355 100644 +--- a/lua/fzf-lua/test/screenshot.lua ++++ b/lua/fzf-lua/test/screenshot.lua +@@ -47,11 +47,18 @@ end + + ---@param s string + ---@return string[] +-local function string_to_chars(s) ++local function string_to_screenchars(s) + -- Can't use `vim.split(s, '')` because of multibyte characters + local res = {} + for i = 1, vim.fn.strchars(s) do +- table.insert(res, vim.fn.strcharpart(s, i - 1, 1)) ++ local ch = vim.fn.strcharpart(s, i - 1, 1) ++ table.insert(res, ch) ++ -- Not single-width characters are read as a single char, but result into ++ -- `{ ch, '', ... }` when computing observed screenshot (as this is how ++ -- `vim.fn.screenstring()` works) ++ for _ = 1, vim.fn.strdisplaywidth(ch) - 1 do ++ table.insert(res, "") ++ end + end + return res + end +@@ -66,10 +73,7 @@ function M.from_lines(text_lines, opts) + if opts and opts.normalize_paths then + text_lines = vim.tbl_map(function(x) return (x:gsub([[\]], [[/]])) end, text_lines) + end +- local f = function(x) +- return string_to_chars(x) +- end +- return screenshot_new({ text = vim.tbl_map(f, text_lines) }, opts) ++ return screenshot_new({ text = vim.tbl_map(string_to_screenchars, text_lines) }, opts) + end + + ---@param child MiniTest.child +@@ -109,7 +113,7 @@ local screenshot_read = function(path) + local lines = vim.fn.readfile(path) + local text_lines = vim.list_slice(lines, 2, #lines) + +- local f = function(x) return H.string_to_chars(x:gsub("^%d+|", "")) end ++ local f = function(x) return string_to_screenchars(x:gsub("^%d+|", "")) end + return screenshot_new({ text = vim.tbl_map(f, text_lines) }, opts) + end + +diff --git a/scripts/make_cli.lua b/scripts/make_cli.lua +index 6e9e532d..9eaf7529 100644 +--- a/scripts/make_cli.lua ++++ b/scripts/make_cli.lua +@@ -33,9 +33,6 @@ if filter then + end + end + +--- make _G.FzfLua usable in test (e.g. headless_spec.lua) +-require("fzf-lua") +- + -- https://github.com/neovim/neovim/pull/36557 + local sig = assert(vim.uv.new_signal()) + sig:start(vim.uv.constants.SIGINT, function() MiniTest.stop() end) +diff --git a/scripts/minimal_init.lua b/scripts/minimal_init.lua +index b366221c..0a967ac0 100644 +--- a/scripts/minimal_init.lua ++++ b/scripts/minimal_init.lua +@@ -17,3 +17,6 @@ vim.env.FZF_DEFAULT_OPTS_FILE = nil + vim.env.FZF_DEFAULT_COMMAND = nil + vim.env.FZF_API_KEY = nil + vim.env.LC_ALL = "C" ++ ++-- make _G.FzfLua usable in test (e.g. headless_spec.lua) ++require("fzf-lua") diff --git a/tasks/ibhagwan__fzf-lua-2740/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2740/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2740/task.toml b/tasks/ibhagwan__fzf-lua-2740/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10e6e4f01bea290bd8e13fdb5826451cbe0f2690 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2740" +description = "ci: sync mini.test upstream change" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "fea9eedc6894c44d44cbb772a5cd11c93b82d7a1" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2740" +source_access = "auto" +built_at = "2026-11-16T16:09:55.982790+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bbe303215b88241383f8b122287136333982f448ff9e9232f928ffa80406116e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-05-31T12:52:49Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/test/screenshot.lua", + "scripts/make_cli.lua", + "scripts/minimal_init.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "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:01.050081+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:21e9a8811a6efbcb06fc92cf189bd1d1cfe7c7759bd37090d8607a59dfb7614e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2740/tests/capture.py b/tasks/ibhagwan__fzf-lua-2740/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2740/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2740/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..562c2f2dbf256c0625041ab2b0fbcea662f884e0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci: sync mini.test upstream change + +## Description + +Fix failure in https://github.com/ibhagwan/fzf-lua/actions/runs/26711878681/job/78723449441?pr=2739. + + +## Summary by CodeRabbit + +* **Tests** + * Improved screenshot comparison to correctly handle multi-width characters by aligning and padding display cells, improving visual regression accuracy for wide-character content. +* **Chores** + * Adjusted test startup: ensure the code is loaded in minimal test environments and remove redundant early loading from the CLI test runner. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fea9eedc6894`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2740/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2740/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ff7c5a56be1f2353d813be5953c79a46c53d7f7b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/tests/oracle.patch @@ -0,0 +1,71 @@ +diff --git a/lua/fzf-lua/test/screenshot.lua b/lua/fzf-lua/test/screenshot.lua +index 3e3eedb4..8ebe6355 100644 +--- a/lua/fzf-lua/test/screenshot.lua ++++ b/lua/fzf-lua/test/screenshot.lua +@@ -47,11 +47,18 @@ end + + ---@param s string + ---@return string[] +-local function string_to_chars(s) ++local function string_to_screenchars(s) + -- Can't use `vim.split(s, '')` because of multibyte characters + local res = {} + for i = 1, vim.fn.strchars(s) do +- table.insert(res, vim.fn.strcharpart(s, i - 1, 1)) ++ local ch = vim.fn.strcharpart(s, i - 1, 1) ++ table.insert(res, ch) ++ -- Not single-width characters are read as a single char, but result into ++ -- `{ ch, '', ... }` when computing observed screenshot (as this is how ++ -- `vim.fn.screenstring()` works) ++ for _ = 1, vim.fn.strdisplaywidth(ch) - 1 do ++ table.insert(res, "") ++ end + end + return res + end +@@ -66,10 +73,7 @@ function M.from_lines(text_lines, opts) + if opts and opts.normalize_paths then + text_lines = vim.tbl_map(function(x) return (x:gsub([[\]], [[/]])) end, text_lines) + end +- local f = function(x) +- return string_to_chars(x) +- end +- return screenshot_new({ text = vim.tbl_map(f, text_lines) }, opts) ++ return screenshot_new({ text = vim.tbl_map(string_to_screenchars, text_lines) }, opts) + end + + ---@param child MiniTest.child +@@ -109,7 +113,7 @@ local screenshot_read = function(path) + local lines = vim.fn.readfile(path) + local text_lines = vim.list_slice(lines, 2, #lines) + +- local f = function(x) return H.string_to_chars(x:gsub("^%d+|", "")) end ++ local f = function(x) return string_to_screenchars(x:gsub("^%d+|", "")) end + return screenshot_new({ text = vim.tbl_map(f, text_lines) }, opts) + end + +diff --git a/scripts/make_cli.lua b/scripts/make_cli.lua +index 6e9e532d..9eaf7529 100644 +--- a/scripts/make_cli.lua ++++ b/scripts/make_cli.lua +@@ -33,9 +33,6 @@ if filter then + end + end + +--- make _G.FzfLua usable in test (e.g. headless_spec.lua) +-require("fzf-lua") +- + -- https://github.com/neovim/neovim/pull/36557 + local sig = assert(vim.uv.new_signal()) + sig:start(vim.uv.constants.SIGINT, function() MiniTest.stop() end) +diff --git a/scripts/minimal_init.lua b/scripts/minimal_init.lua +index b366221c..0a967ac0 100644 +--- a/scripts/minimal_init.lua ++++ b/scripts/minimal_init.lua +@@ -17,3 +17,6 @@ vim.env.FZF_DEFAULT_OPTS_FILE = nil + vim.env.FZF_DEFAULT_COMMAND = nil + vim.env.FZF_API_KEY = nil + vim.env.LC_ALL = "C" ++ ++-- make _G.FzfLua usable in test (e.g. headless_spec.lua) ++require("fzf-lua") diff --git a/tasks/ibhagwan__fzf-lua-2740/tests/test.sh b/tasks/ibhagwan__fzf-lua-2740/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97429aa8fafa062e2372c728565a4a79af0c2fb2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace fea9eedc6894c44d44cbb772a5cd11c93b82d7a1 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2740/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2740/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2740/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2750/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2750/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c21d3609fdc16efca8d2412959ed3b42ab1c64f4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin dbe7895a07079b2320abfb3c555b90d3d40a8c9e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard dbe7895a07079b2320abfb3c555b90d3d40a8c9e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base dbe7895a07079b2320abfb3c555b90d3d40a8c9e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2750/instruction.md b/tasks/ibhagwan__fzf-lua-2750/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fc57c5b45b46abab2976568848b8f6b11bb4b4d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat(git follow): Add option to make git_bcommits follow renames + +## Description + +Core idea: + +* Use `git log --follow --name-only` to print the original filename in another line after each log message +* Combine lines with log messages + lines with filenames in a loop into a single entry +* Use `--with-nth` feature of fzf to hide the filename + + + +## Summary by CodeRabbit + +* **New Features** + * Added a `follow` option to the `bcommits` picker to follow a buffer’s history across renames (non-visual mode only). + * When enabled, entries use commit-aware file resolution and previews. +* **Documentation** + * Documented the new `follow` option for `bcommits`, explicitly noting its default (`false`). +* **Behavior Changes** + * Commit-specific file paths are resolved to reflect the filename as it existed at the selected commit, improving renamed-file accuracy. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dbe7895a0707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2750/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2750/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4f825207e3b1a470de10228681636c5ccf2a5d5b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/solution/patch.diff @@ -0,0 +1,98 @@ +diff --git a/README.md b/README.md +index fc9599ad..d6fbe80b 100644 +--- a/README.md ++++ b/README.md +@@ -936,6 +936,8 @@ previewers = { + }, + bcommits = { + prompt = 'BCommits❯ ', ++ -- follow the buffer's history across renames ++ follow = false, + -- default preview shows a git diff vs the previous commit + -- if you prefer to see the entire commit you can use: + -- git show --color {1} --rotate-to={file} +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 95540cdd..8cf38b93 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1116,7 +1116,10 @@ M.git_buf_edit = function(selected, opts) + local git_root = assert(path.git_root(opts, true), "not in git directory") + local win = vim.api.nvim_get_current_win() + local buffer_filetype = vim.bo.filetype +- local file = path.relative_to(path.normalize(vim.fn.expand("%:p")), git_root) ++ -- `fn_match_file` lets a provider (e.g. bcommits `follow`) resolve the path the ++ -- buffer had at the selected commit; otherwise fall back to the current name. ++ local file = type(opts.fn_match_file) == "function" and opts.fn_match_file(selected[1], opts) ++ or path.relative_to(path.normalize(vim.fn.expand("%:p")), git_root) + local commit_hash = match_commit_hash(selected[1], opts) + table.insert(cmd, commit_hash .. ":" .. file) + local git_file_contents = utils.io_systemlist(cmd) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index edfd4831..69d423e0 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -780,9 +780,13 @@ M.defaults.git = { + }, + ---Git commits (buffer). + ---@class fzf-lua.config.GitBcommits: fzf-lua.config.GitBase ++ ---Follow the buffer's history across renames. ++ ---@field follow? boolean + bcommits = { + cmd = [[git log --color --pretty=format:"%C(yellow)%h%Creset ]] + .. [[%Cgreen(%><(12)%cr%><|(12))%Creset %s %C(blue)<%an>%Creset" -- {file}]], ++ -- When true, follow the buffer's history across renames. ++ follow = false, + preview = "git show --color {1} -- {file}", + preview_pager = M._preview_pager_fn, + actions = { +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index f855a499..b372f2f0 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -216,6 +216,46 @@ M.bcommits = function(opts) + end + local git_root = path.git_root(opts) + if not git_root then return end ++ -- `follow`: list (and preview) the buffer's history across renames. We resolve ++ -- the filename the buffer had at each commit via `git log --follow --name-only` ++ -- (which prints the per-commit name with no rename-chain bookkeeping), embedding ++ -- it as a hidden fzf field so the preview/actions reference the correct path for ++ -- commits where the file was named differently. ++ if opts.follow and not utils.mode_is_visual() then ++ local display_fmt = opts.cmd:match('%-%-pretty=format:"(.-)"') or "%C(yellow)%h%Creset %s" ++ local relfile = path.relative_to(vim.fn.expand("%:p"), git_root) ++ -- \1 marks a header line; \31 separates the clean sha from the coloured display ++ local logcmd = path.git_cwd({ ++ "git", "-c", "core.quotepath=false", ++ "log", "--follow", "--name-only", "--color=always", ++ "--pretty=format:%x01%h%x1f" .. display_fmt, "--", relfile, ++ }, opts) ++ local entries, sha, disp = {}, nil, nil ++ for _, line in ipairs(utils.io_systemlist(logcmd)) do ++ local s, d = line:match("^\1([^\31]*)\31(.*)$") ++ if s then ++ sha, disp = s, d ++ elseif sha and #line > 0 then ++ local fname = line:gsub("\27%[[%d;]*m", "") -- defensive ANSI strip ++ entries[#entries + 1] = string.format("%s\t%s\t%s", sha, fname, disp) ++ sha = nil ++ end ++ end ++ opts.fzf_opts = opts.fzf_opts or {} ++ if opts.fzf_opts["--delimiter"] == nil then opts.fzf_opts["--delimiter"] = "\t" end ++ if opts.fzf_opts["--with-nth"] == nil then opts.fzf_opts["--with-nth"] = "3.." end ++ opts.preview = "git show --color {1} -- {2}" ++ opts.preview = git_preview(opts) ++ ---@class fzf-lua.config.GitBcommitsFollow: fzf-lua.config.GitBcommits ++ ---@field fn_match_commit_hash? fun(line: string, opts: table): string? ++ ---@field fn_match_file? fun(line: string, opts: table): string? ++ ---@cast opts fzf-lua.config.GitBcommitsFollow ++ opts.fn_match_commit_hash = opts.fn_match_commit_hash ++ or function(l) return l:match("^[^\t]+") end ++ opts.fn_match_file = opts.fn_match_file ++ or function(l) return (l:match("^[^\t]+\t([^\t]+)")) end ++ return core.fzf_exec(entries, opts) ++ end + local file = libuv.shellescape(path.relative_to(vim.fn.expand("%:p"), git_root)) + local range + if utils.mode_is_visual() then diff --git a/tasks/ibhagwan__fzf-lua-2750/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2750/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2750/task.toml b/tasks/ibhagwan__fzf-lua-2750/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e6fcff09d377c291160b4eebaa44a4db908e8ff1 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2750" +description = "feat(git follow): Add option to make git_bcommits follow renames" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "dbe7895a07079b2320abfb3c555b90d3d40a8c9e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2750" +source_access = "auto" +built_at = "2026-11-16T16:09:55.975566+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:625ac21c8fb9a5e9b6ad7cc8e57c12f00d125ce7a618954fce2c97c238048084" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-29T03:19:48Z" +diff_format = "unified" +context_files = [ + "README.md", + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/git.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 51 +difficulty = "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:01.050579+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0359b1d6aa59ad77b394bddbbc19a3e462003a427328a67fd5723a8afaef2fc0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2750/tests/capture.py b/tasks/ibhagwan__fzf-lua-2750/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2750/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2750/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fc57c5b45b46abab2976568848b8f6b11bb4b4d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** feat(git follow): Add option to make git_bcommits follow renames + +## Description + +Core idea: + +* Use `git log --follow --name-only` to print the original filename in another line after each log message +* Combine lines with log messages + lines with filenames in a loop into a single entry +* Use `--with-nth` feature of fzf to hide the filename + + + +## Summary by CodeRabbit + +* **New Features** + * Added a `follow` option to the `bcommits` picker to follow a buffer’s history across renames (non-visual mode only). + * When enabled, entries use commit-aware file resolution and previews. +* **Documentation** + * Documented the new `follow` option for `bcommits`, explicitly noting its default (`false`). +* **Behavior Changes** + * Commit-specific file paths are resolved to reflect the filename as it existed at the selected commit, improving renamed-file accuracy. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dbe7895a0707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2750/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2750/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4f825207e3b1a470de10228681636c5ccf2a5d5b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/tests/oracle.patch @@ -0,0 +1,98 @@ +diff --git a/README.md b/README.md +index fc9599ad..d6fbe80b 100644 +--- a/README.md ++++ b/README.md +@@ -936,6 +936,8 @@ previewers = { + }, + bcommits = { + prompt = 'BCommits❯ ', ++ -- follow the buffer's history across renames ++ follow = false, + -- default preview shows a git diff vs the previous commit + -- if you prefer to see the entire commit you can use: + -- git show --color {1} --rotate-to={file} +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 95540cdd..8cf38b93 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1116,7 +1116,10 @@ M.git_buf_edit = function(selected, opts) + local git_root = assert(path.git_root(opts, true), "not in git directory") + local win = vim.api.nvim_get_current_win() + local buffer_filetype = vim.bo.filetype +- local file = path.relative_to(path.normalize(vim.fn.expand("%:p")), git_root) ++ -- `fn_match_file` lets a provider (e.g. bcommits `follow`) resolve the path the ++ -- buffer had at the selected commit; otherwise fall back to the current name. ++ local file = type(opts.fn_match_file) == "function" and opts.fn_match_file(selected[1], opts) ++ or path.relative_to(path.normalize(vim.fn.expand("%:p")), git_root) + local commit_hash = match_commit_hash(selected[1], opts) + table.insert(cmd, commit_hash .. ":" .. file) + local git_file_contents = utils.io_systemlist(cmd) +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index edfd4831..69d423e0 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -780,9 +780,13 @@ M.defaults.git = { + }, + ---Git commits (buffer). + ---@class fzf-lua.config.GitBcommits: fzf-lua.config.GitBase ++ ---Follow the buffer's history across renames. ++ ---@field follow? boolean + bcommits = { + cmd = [[git log --color --pretty=format:"%C(yellow)%h%Creset ]] + .. [[%Cgreen(%><(12)%cr%><|(12))%Creset %s %C(blue)<%an>%Creset" -- {file}]], ++ -- When true, follow the buffer's history across renames. ++ follow = false, + preview = "git show --color {1} -- {file}", + preview_pager = M._preview_pager_fn, + actions = { +diff --git a/lua/fzf-lua/providers/git.lua b/lua/fzf-lua/providers/git.lua +index f855a499..b372f2f0 100644 +--- a/lua/fzf-lua/providers/git.lua ++++ b/lua/fzf-lua/providers/git.lua +@@ -216,6 +216,46 @@ M.bcommits = function(opts) + end + local git_root = path.git_root(opts) + if not git_root then return end ++ -- `follow`: list (and preview) the buffer's history across renames. We resolve ++ -- the filename the buffer had at each commit via `git log --follow --name-only` ++ -- (which prints the per-commit name with no rename-chain bookkeeping), embedding ++ -- it as a hidden fzf field so the preview/actions reference the correct path for ++ -- commits where the file was named differently. ++ if opts.follow and not utils.mode_is_visual() then ++ local display_fmt = opts.cmd:match('%-%-pretty=format:"(.-)"') or "%C(yellow)%h%Creset %s" ++ local relfile = path.relative_to(vim.fn.expand("%:p"), git_root) ++ -- \1 marks a header line; \31 separates the clean sha from the coloured display ++ local logcmd = path.git_cwd({ ++ "git", "-c", "core.quotepath=false", ++ "log", "--follow", "--name-only", "--color=always", ++ "--pretty=format:%x01%h%x1f" .. display_fmt, "--", relfile, ++ }, opts) ++ local entries, sha, disp = {}, nil, nil ++ for _, line in ipairs(utils.io_systemlist(logcmd)) do ++ local s, d = line:match("^\1([^\31]*)\31(.*)$") ++ if s then ++ sha, disp = s, d ++ elseif sha and #line > 0 then ++ local fname = line:gsub("\27%[[%d;]*m", "") -- defensive ANSI strip ++ entries[#entries + 1] = string.format("%s\t%s\t%s", sha, fname, disp) ++ sha = nil ++ end ++ end ++ opts.fzf_opts = opts.fzf_opts or {} ++ if opts.fzf_opts["--delimiter"] == nil then opts.fzf_opts["--delimiter"] = "\t" end ++ if opts.fzf_opts["--with-nth"] == nil then opts.fzf_opts["--with-nth"] = "3.." end ++ opts.preview = "git show --color {1} -- {2}" ++ opts.preview = git_preview(opts) ++ ---@class fzf-lua.config.GitBcommitsFollow: fzf-lua.config.GitBcommits ++ ---@field fn_match_commit_hash? fun(line: string, opts: table): string? ++ ---@field fn_match_file? fun(line: string, opts: table): string? ++ ---@cast opts fzf-lua.config.GitBcommitsFollow ++ opts.fn_match_commit_hash = opts.fn_match_commit_hash ++ or function(l) return l:match("^[^\t]+") end ++ opts.fn_match_file = opts.fn_match_file ++ or function(l) return (l:match("^[^\t]+\t([^\t]+)")) end ++ return core.fzf_exec(entries, opts) ++ end + local file = libuv.shellescape(path.relative_to(vim.fn.expand("%:p"), git_root)) + local range + if utils.mode_is_visual() then diff --git a/tasks/ibhagwan__fzf-lua-2750/tests/test.sh b/tasks/ibhagwan__fzf-lua-2750/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcabcb72e2b9b86a09ba32be5752ab0ad3b63f23 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace dbe7895a07079b2320abfb3c555b90d3d40a8c9e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2750/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2750/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2750/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2752/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2752/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9dd2133e64fca9361fb2ab0a72f1c57f07f69056 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 988416cc782dfe28bff3f0da9b8c943b236cd86a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 988416cc782dfe28bff3f0da9b8c943b236cd86a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 988416cc782dfe28bff3f0da9b8c943b236cd86a \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2752/instruction.md b/tasks/ibhagwan__fzf-lua-2752/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4bb3ad8ee4f0f456e9e75ae9655b926111263484 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix: add native color support to git diff preview + +## Description + +Added `--color=always` flag to git diff preview and cmd in order to support native git diff color in `git_commit` when navigating to individual commits making the diff easier to read without needing `delta`. + +Fixes issue from discussion https://github.com/ibhagwan/fzf-lua/discussions/2751 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved git diff visualization with color output for better readability. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `988416cc782d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2752/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2752/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1bce23f53ac8aa38a3b729b1bb264694cb8904fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index f0321dde..87a0188f 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -676,10 +676,10 @@ M.defaults.git = { + ---Git reference used as the base for the comparison. + ---@field ref1? string + diff = { +- cmd = "git --no-pager diff --name-only {ref1} {ref}", ++ cmd = "git --no-pager diff --color=always --name-only {ref1} {ref}", + ref = nil, + ref1 = nil, +- preview = "git diff {ref1} {ref} {file}", ++ preview = "git diff --color=always {ref1} {ref} {file}", + preview_pager = M._preview_pager_fn, + multiprocess = 1, ---@type integer|boolean + _type = "file", diff --git a/tasks/ibhagwan__fzf-lua-2752/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2752/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2752/task.toml b/tasks/ibhagwan__fzf-lua-2752/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..643dfb74b2b3f57dbf7d2feb7173ab4f2df8fb8e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2752" +description = "fix: add native color support to git diff preview" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "988416cc782dfe28bff3f0da9b8c943b236cd86a" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2752" +source_access = "auto" +built_at = "2026-11-16T16:09:55.978430+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:571b9ee3c056e6f630ee2da4b67281eaa1d429e5208601dec22ed2c7fc47ce3e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-18T02:08:08Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.051092+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:723c9c90bafe04c483691890d742459a937f965e3b957cf64336e0e19abe4ca6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2752/tests/capture.py b/tasks/ibhagwan__fzf-lua-2752/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2752/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2752/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4bb3ad8ee4f0f456e9e75ae9655b926111263484 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix: add native color support to git diff preview + +## Description + +Added `--color=always` flag to git diff preview and cmd in order to support native git diff color in `git_commit` when navigating to individual commits making the diff easier to read without needing `delta`. + +Fixes issue from discussion https://github.com/ibhagwan/fzf-lua/discussions/2751 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved git diff visualization with color output for better readability. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `988416cc782d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2752/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2752/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1bce23f53ac8aa38a3b729b1bb264694cb8904fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index f0321dde..87a0188f 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -676,10 +676,10 @@ M.defaults.git = { + ---Git reference used as the base for the comparison. + ---@field ref1? string + diff = { +- cmd = "git --no-pager diff --name-only {ref1} {ref}", ++ cmd = "git --no-pager diff --color=always --name-only {ref1} {ref}", + ref = nil, + ref1 = nil, +- preview = "git diff {ref1} {ref} {file}", ++ preview = "git diff --color=always {ref1} {ref} {file}", + preview_pager = M._preview_pager_fn, + multiprocess = 1, ---@type integer|boolean + _type = "file", diff --git a/tasks/ibhagwan__fzf-lua-2752/tests/test.sh b/tasks/ibhagwan__fzf-lua-2752/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8fa8e20abdaf15029bd9ebbc81068626a9a7aab --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 988416cc782dfe28bff3f0da9b8c943b236cd86a > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2752/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2752/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2752/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2753/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2753/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e770f7f78329a343917f497c3fd41b212208b04 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 09880d502bc76f1e025fdbdcaeff44650f7ea78a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 09880d502bc76f1e025fdbdcaeff44650f7ea78a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 09880d502bc76f1e025fdbdcaeff44650f7ea78a \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2753/instruction.md b/tasks/ibhagwan__fzf-lua-2753/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..587dd8a537fc9793ec1f9efede528338a02c8d25 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(ui_select): add native preview for fzf-native/fzf-tmux + +## Description + +Close + + +## Summary by CodeRabbit + +* **New Features** + * Added a default `ui_select` configuration for single-select with native preview behavior. + * Ensured the native and tmux profiles use native preview for `ui_select`. +* **Bug Fixes** + * Improved `ui_select` preview resolution and rendering for both native and buffer modes, including safer handling when preview data is missing. + * Improved temporary preview cleanup when the picker closes. +* **Tests** + * Expanded `ui_select` coverage for native/tmux preview, async preview startup, empty preview regression, and abort via escape. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `09880d502bc7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2753/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2753/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..de3b420beb0656bdebfd45d2fd3269bc2852494d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/solution/patch.diff @@ -0,0 +1,360 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 69d423e0..714be727 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -2208,6 +2208,22 @@ M.defaults.complete_line = vim.tbl_deep_extend("force", M.defaults.blines, { + complete = true, + }) + ++ ++---@class fzf-lua.config.UISelect: fzf-lua.config.Base ++M.defaults.ui_select = { ++ fzf_opts = { ["--no-multi"] = true }, ++ ui_select = { preview_type = "native" }, ++ actions = { ++ ["enter"] = { ++ fn = function(...) ++ return require("fzf-lua.providers.ui_select").accept_item(...) ++ end, ++ desc = "accept-item" ++ } ++ } ++} ++ ++ + M.defaults.file_icon_padding = "" + + -- No need to sset this, already defaults to `nvim_open_win` +diff --git a/lua/fzf-lua/profiles/fzf-native.lua b/lua/fzf-lua/profiles/fzf-native.lua +index 568aa530..8dcb187e 100644 +--- a/lua/fzf-lua/profiles/fzf-native.lua ++++ b/lua/fzf-lua/profiles/fzf-native.lua +@@ -21,4 +21,5 @@ return { + lsp = { code_actions = { previewer = "codeaction_native" } }, + tags = { previewer = "bat" }, + btags = { previewer = "bat" }, ++ ui_select = { preview_type = "native" }, + } +diff --git a/lua/fzf-lua/profiles/fzf-tmux.lua b/lua/fzf-lua/profiles/fzf-tmux.lua +index 9854382e..a5de0fc6 100644 +--- a/lua/fzf-lua/profiles/fzf-tmux.lua ++++ b/lua/fzf-lua/profiles/fzf-tmux.lua +@@ -33,4 +33,5 @@ return { + btags = { previewer = "bat" }, + lines = { _treesitter = false }, + blines = { _treesitter = false }, ++ ui_select = { preview_type = "native" }, + } +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 080ce37d..3312c246 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -53,6 +53,19 @@ M.accept_item = function(selected, o) + o._on_choice_called = true + end + ++local resolve_preview_type = function(ui_opts, opts) ++ local preview_type = ui_opts.preview_type or opts.preview_type ++ if preview_type == nil then ++ local profile = opts.profile or opts[1] ++ local is_tmux_profile = profile == "fzf-tmux" ++ or (type(profile) == "table" and vim.tbl_contains(profile, "fzf-tmux")) ++ preview_type = (is_tmux_profile ++ or (opts.fzf_opts and opts.fzf_opts["--tmux"])) ++ and "native" or "buffer" ++ end ++ return preview_type ++end ++ + M.ui_select = function(items, ui_opts, on_choice) + --[[ + -- Code Actions +@@ -89,21 +102,14 @@ M.ui_select = function(items, ui_opts, on_choice) + + local opts = _OPTS or {} + +- -- enables customization per kind (#755) +- if type(opts) == "function" then +- opts = opts(ui_opts, items) +- end ++ opts = config.normalize_opts(opts, "ui_select") ++ if not opts then return end + + -- deepcopy register opts so we don't poullute the original tbl ref (#2241) + if type(opts) == "table" then + opts = utils.tbl_deep_clone(opts) + end + +- opts.fzf_opts = vim.tbl_extend("keep", opts.fzf_opts or {}, { +- ["--no-multi"] = true, +- ["--preview-window"] = "hidden:right:0", +- }) +- + -- Force override prompt or it stays cached (#786) + local prompt = ui_opts.prompt or "Select one of:" + opts.prompt = opts.prompt or prompt:gsub(":%s?$", "> ") +@@ -113,10 +119,6 @@ M.ui_select = function(items, ui_opts, on_choice) + opts._on_choice = on_choice + opts._ui_select = ui_opts + +- opts.actions = vim.tbl_deep_extend("keep", opts.actions or {}, { +- ["enter"] = { fn = M.accept_item, desc = "accept-item" } +- }) +- + -- schedule to avoid our coroutine break external async logic #2719 + opts.fn_selected = vim.schedule_wrap(function(selected, o) + local function exec_choice() +@@ -180,26 +182,78 @@ M.ui_select = function(items, ui_opts, on_choice) + end + + if ui_opts.preview_item then +- opts.previewer = { +- _ctor = function() +- local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() +- ---@diagnostic disable-next-line: unused +- function previewer:parse_entry(entry_str, cb) +- local str = utils.strip_ansi_coloring(entry_str) +- local res = assert(ui_opts.preview_item(items[reverse_lookup[str]], cb)) +- local pos_start, pos_end = res.pos, res.pos_end +- return { +- _scratch_buf = res.buf, +- line = pos_start and pos_start[1] or 1, +- col = pos_start and pos_start[2] or 1, +- end_line = pos_end and pos_end[1] or 1, +- end_col = pos_end and pos_end[2] or 1, +- } ++ local preview_type = resolve_preview_type(ui_opts, opts) ++ if preview_type == "native" then ++ local tmpfile = vim.fn.tempname() ++ opts.preview = { ++ fn = function(s) ++ if not s or not s[1] then return utils.shell_nop() end ++ local idx = reverse_lookup[utils.strip_ansi_coloring(s[1])] ++ if not idx or not items[idx] then return utils.shell_nop() end ++ local res = ui_opts.preview_item(items[idx]) ++ if type(res) ~= "table" or not res.buf or not vim.api.nvim_buf_is_valid(res.buf) then ++ return utils.shell_nop() ++ end ++ local fd, _ = io.open(tmpfile, "w") ++ if fd then ++ fd:write(table.concat(vim.api.nvim_buf_get_lines(res.buf, 0, -1, false), "\n")) ++ fd:close() ++ end ++ local ft = vim.bo[res.buf].filetype or vim.filetype.match({ buf = res.buf }) ++ local cat = utils.__IS_WINDOWS and "type" or "cat" ++ local nul = utils.__IS_WINDOWS and "NUL" or "/dev/null" ++ local tmp_esc = require("fzf-lua.libuv").shellescape(tmpfile) ++ if ft and ft ~= "" then ++ return ("bat --style=numbers,changes --color=always --language=%s %s 2>%s || %s %s") ++ :format(ft, tmp_esc, nul, cat, tmp_esc) ++ end ++ return ("bat --style=numbers,changes --color=always %s 2>%s || %s %s"):format( ++ tmp_esc, nul, cat, tmp_esc) ++ end, ++ type = "cmd", ++ } ++ ++ -- `preview_offset` is a static fzf flag, so we seed it once from ++ -- the first item's `pos`. The user can scroll within fzf for ++ -- per-entry offsets; the common case is one shared buffer. ++ if items[1] then ++ local first = ui_opts.preview_item(items[1]) ++ if first and first.pos and first.pos[1] then ++ opts.preview_offset = ("+%d"):format(first.pos[1]) + end ++ end + +- return previewer ++ opts.winopts = opts.winopts or {} ++ local prev_on_close = opts.winopts.on_close ++ opts.winopts.on_close = function(...) ++ if prev_on_close then prev_on_close(...) end ++ pcall(os.remove, tmpfile) + end +- } ++ else ++ opts.previewer = { ++ _ctor = function() ++ local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() ++ ---@diagnostic disable-next-line: unused ++ function previewer:parse_entry(entry_str, cb) ++ local str = utils.strip_ansi_coloring(entry_str) ++ local res = ui_opts.preview_item(items[reverse_lookup[str]], cb) ++ if type(res) ~= "table" or (not res.buf and not res.pos) then ++ return { content = { { { "No preview available", "Error" } } }, } ++ end ++ local pos_start, pos_end = res.pos, res.pos_end ++ return { ++ _scratch_buf = res.buf, ++ line = pos_start and pos_start[1] or 1, ++ col = pos_start and pos_start[2] or 1, ++ end_line = pos_end and pos_end[1] or 1, ++ end_col = pos_end and pos_end[2] or 1, ++ } ++ end ++ ++ return previewer ++ end, ++ } ++ end + elseif _OPTS_ONCE then + -- merge and clear the once opts sent from lsp_code_actions. + -- We also override actions to guarantee a single default +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +new file mode 100644 +index 00000000..e454f09c +--- /dev/null ++++ b/tests/ui_select_spec.lua +@@ -0,0 +1,152 @@ ++---@diagnostic disable: unused-local, unused-function, unused ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local child = helpers.new_child_neovim() ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++local exec_lua = child.lua ++ ++--stylua: ignore start ++---@format disable-next ++local reload = function(config) child.unload(); child.setup(config) end ++local type_keys = function(...) return child.type_keys(...) end ++local sleep = function(ms) helpers.sleep(ms, child) end ++--stylua: ignore end ++ ++local T = helpers.new_set_with_child(child, { ++ hooks = { ++ pre_case = function() ++ child.o.shell = "/bin/sh" ++ child.o.termguicolors = true ++ child.o.background = "dark" ++ child.o.statusline = "fzf://" ++ end, ++ }, ++}) ++ ++T["ui_select"] = new_set() ++ ++local register = function(opts) ++ local literal = vim.inspect(opts or {}):gsub("\n", " ") ++ exec_lua(([[FzfLua.register_ui_select(%s)]]):format(literal)) ++end ++ ++-- Wipe any stale /tmp/fzf-lua-ui-select-*.tmp files left by previous ++-- (possibly crashed) test runs. The tmpfile name uses `os.time()` ++-- which has 1-second resolution, so concurrent runs in the same ++-- second would otherwise race on the same path. ++local function cleanup_stale_tmpfiles() ++ for _, f in ipairs(vim.fn.glob("/tmp/fzf-lua-ui-select-*.tmp", true, true)) do ++ pcall(os.remove, f) ++ end ++ exec_lua(([[ ++ for _, f in ipairs(vim.fn.glob("/tmp/fzf-lua-ui-select-*.tmp", true, true)) do ++ pcall(os.remove, f) ++ end ++ ]])) ++end ++ ++-- Open the picker via `vim.ui.select` and wait for it to appear. ++-- The buffer is created in the child nvim (buffers don't cross the rpc ++-- boundary). `pcall` traps any synchronous crash from the native ++-- preview fn (#2743). ++local function open_picker(items, preview_lines, ui_opts) ++ exec_lua(function(items, preview_lines, ui_opts) ++ _G._ui_select_choice = nil ++ _G._ui_select_errors = nil ++ local buf = vim.api.nvim_create_buf(false, true) ++ vim.api.nvim_buf_set_lines(buf, 0, -1, false, preview_lines) ++ local opts = vim.tbl_extend("keep", ui_opts, { ++ format_item = function(item) return tostring(item) end, ++ preview_item = function() return { buf = buf } end, ++ }) ++ local ok, err = pcall(vim.ui.select, items, opts, function(item, idx) ++ _G._ui_select_choice = { item = item, idx = idx } ++ end) ++ if not ok then ++ _G._ui_select_errors = tostring(err); error(err) ++ end ++ end, { items, preview_lines, ui_opts or {} }) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ or child.lua_get([[_G._ui_select_errors]]) ~= nil ++ end, 5000) ++ local errs = child.lua_get([[_G._ui_select_errors]]) ++ eq(errs, vim.NIL, { fail_reason = "vim.ui.select errored: " .. tostring(errs) }) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), true) ++end ++ ++local function close_picker(key) ++ type_keys(key or "") ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == vim.NIL ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), vim.NIL) ++end ++ ++-- Wait until the picker's previewer reports having rendered the ++-- first entry. `last_entry` is the full fzf line (with the `. ` ++-- prefix produced by ui_select). ++local function wait_preview_rendered(expected_entry) ++ child.wait_until(function() ++ local last = child.lua_get([[ ++ (FzfLua.utils.fzf_winobj() or {})._previewer ++ and FzfLua.utils.fzf_winobj()._previewer.last_entry or nil ++ ]]) ++ return last == expected_entry ++ end, 5000) ++end ++ ++T["ui_select"]["buffer preview (default)"] = function() ++ reload({ "default" }) ++ register() ++ open_picker({ "alpha", "beta" }, { "preview-line-1", "preview-line-2" }, ++ { prompt = "Pick (buffer):" }) ++ wait_preview_rendered("1. alpha") ++ local screen = tostring(child.get_screenshot({ redraw = true })) ++ eq(screen:find("alpha", 1, true) ~= nil, true, ++ { fail_reason = "alpha not in screen:\n" .. screen }) ++ eq(screen:find("preview-line-1", 1, true) ~= nil, true, ++ { fail_reason = "preview line 1 not in screen:\n" .. screen }) ++ close_picker() ++end ++ ++T["ui_select"]["native via fzf-tmux profile #2743"] = function() ++ -- The fzf-tmux profile declares `ui_select = { preview_type = "native" }` ++ -- so the picker should use the native backend even without an ++ -- explicit opt (in real tmux the picker runs in a tmux popup; here ++ -- without tmux it degrades to a regular fzf run with the same opts). ++ cleanup_stale_tmpfiles() ++ reload({ "fzf-tmux" }) ++ register() ++ open_picker({ "alpha", "beta" }, { "tmux-line" }) ++ sleep(300) ++ close_picker() ++end ++ ++T["ui_select"]["async preview_item opens without crash"] = function() ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Pick (async):", ++ preview_item = function(_) return {} end, ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), true) ++ close_picker("") ++end ++ ++T["ui_select"]["abort via esc"] = function() ++ reload({ "default" }) ++ register() ++ open_picker({ "alpha" }, { "esc-preview" }) ++ close_picker("") ++ eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2753/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2753/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2753/task.toml b/tasks/ibhagwan__fzf-lua-2753/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ebe2ebe0a39f2b037eb08979f21597087ae53c2b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2753" +description = "fix(ui_select): add native preview for fzf-native/fzf-tmux" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "09880d502bc76f1e025fdbdcaeff44650f7ea78a" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2753" +source_access = "auto" +built_at = "2026-11-16T16:09:55.969458+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4ceb4c9af63780b48f66abc2a9f8a81efdbc218f77ae32a968ede1b03fcf33a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-03T15:02:44Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/profiles/fzf-native.lua", + "lua/fzf-lua/profiles/fzf-tmux.lua", + "lua/fzf-lua/providers/ui_select.lua", + "tests/ui_select_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 284 +difficulty = "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:01.051579+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33723396a27b2a28cda4556dad0806e83095d6cfdf542d0bfb9476ebdb0ce72d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2753/tests/capture.py b/tasks/ibhagwan__fzf-lua-2753/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2753/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2753/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..587dd8a537fc9793ec1f9efede528338a02c8d25 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(ui_select): add native preview for fzf-native/fzf-tmux + +## Description + +Close + + +## Summary by CodeRabbit + +* **New Features** + * Added a default `ui_select` configuration for single-select with native preview behavior. + * Ensured the native and tmux profiles use native preview for `ui_select`. +* **Bug Fixes** + * Improved `ui_select` preview resolution and rendering for both native and buffer modes, including safer handling when preview data is missing. + * Improved temporary preview cleanup when the picker closes. +* **Tests** + * Expanded `ui_select` coverage for native/tmux preview, async preview startup, empty preview regression, and abort via escape. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `09880d502bc7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2753/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2753/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..de3b420beb0656bdebfd45d2fd3269bc2852494d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/tests/oracle.patch @@ -0,0 +1,360 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 69d423e0..714be727 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -2208,6 +2208,22 @@ M.defaults.complete_line = vim.tbl_deep_extend("force", M.defaults.blines, { + complete = true, + }) + ++ ++---@class fzf-lua.config.UISelect: fzf-lua.config.Base ++M.defaults.ui_select = { ++ fzf_opts = { ["--no-multi"] = true }, ++ ui_select = { preview_type = "native" }, ++ actions = { ++ ["enter"] = { ++ fn = function(...) ++ return require("fzf-lua.providers.ui_select").accept_item(...) ++ end, ++ desc = "accept-item" ++ } ++ } ++} ++ ++ + M.defaults.file_icon_padding = "" + + -- No need to sset this, already defaults to `nvim_open_win` +diff --git a/lua/fzf-lua/profiles/fzf-native.lua b/lua/fzf-lua/profiles/fzf-native.lua +index 568aa530..8dcb187e 100644 +--- a/lua/fzf-lua/profiles/fzf-native.lua ++++ b/lua/fzf-lua/profiles/fzf-native.lua +@@ -21,4 +21,5 @@ return { + lsp = { code_actions = { previewer = "codeaction_native" } }, + tags = { previewer = "bat" }, + btags = { previewer = "bat" }, ++ ui_select = { preview_type = "native" }, + } +diff --git a/lua/fzf-lua/profiles/fzf-tmux.lua b/lua/fzf-lua/profiles/fzf-tmux.lua +index 9854382e..a5de0fc6 100644 +--- a/lua/fzf-lua/profiles/fzf-tmux.lua ++++ b/lua/fzf-lua/profiles/fzf-tmux.lua +@@ -33,4 +33,5 @@ return { + btags = { previewer = "bat" }, + lines = { _treesitter = false }, + blines = { _treesitter = false }, ++ ui_select = { preview_type = "native" }, + } +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 080ce37d..3312c246 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -53,6 +53,19 @@ M.accept_item = function(selected, o) + o._on_choice_called = true + end + ++local resolve_preview_type = function(ui_opts, opts) ++ local preview_type = ui_opts.preview_type or opts.preview_type ++ if preview_type == nil then ++ local profile = opts.profile or opts[1] ++ local is_tmux_profile = profile == "fzf-tmux" ++ or (type(profile) == "table" and vim.tbl_contains(profile, "fzf-tmux")) ++ preview_type = (is_tmux_profile ++ or (opts.fzf_opts and opts.fzf_opts["--tmux"])) ++ and "native" or "buffer" ++ end ++ return preview_type ++end ++ + M.ui_select = function(items, ui_opts, on_choice) + --[[ + -- Code Actions +@@ -89,21 +102,14 @@ M.ui_select = function(items, ui_opts, on_choice) + + local opts = _OPTS or {} + +- -- enables customization per kind (#755) +- if type(opts) == "function" then +- opts = opts(ui_opts, items) +- end ++ opts = config.normalize_opts(opts, "ui_select") ++ if not opts then return end + + -- deepcopy register opts so we don't poullute the original tbl ref (#2241) + if type(opts) == "table" then + opts = utils.tbl_deep_clone(opts) + end + +- opts.fzf_opts = vim.tbl_extend("keep", opts.fzf_opts or {}, { +- ["--no-multi"] = true, +- ["--preview-window"] = "hidden:right:0", +- }) +- + -- Force override prompt or it stays cached (#786) + local prompt = ui_opts.prompt or "Select one of:" + opts.prompt = opts.prompt or prompt:gsub(":%s?$", "> ") +@@ -113,10 +119,6 @@ M.ui_select = function(items, ui_opts, on_choice) + opts._on_choice = on_choice + opts._ui_select = ui_opts + +- opts.actions = vim.tbl_deep_extend("keep", opts.actions or {}, { +- ["enter"] = { fn = M.accept_item, desc = "accept-item" } +- }) +- + -- schedule to avoid our coroutine break external async logic #2719 + opts.fn_selected = vim.schedule_wrap(function(selected, o) + local function exec_choice() +@@ -180,26 +182,78 @@ M.ui_select = function(items, ui_opts, on_choice) + end + + if ui_opts.preview_item then +- opts.previewer = { +- _ctor = function() +- local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() +- ---@diagnostic disable-next-line: unused +- function previewer:parse_entry(entry_str, cb) +- local str = utils.strip_ansi_coloring(entry_str) +- local res = assert(ui_opts.preview_item(items[reverse_lookup[str]], cb)) +- local pos_start, pos_end = res.pos, res.pos_end +- return { +- _scratch_buf = res.buf, +- line = pos_start and pos_start[1] or 1, +- col = pos_start and pos_start[2] or 1, +- end_line = pos_end and pos_end[1] or 1, +- end_col = pos_end and pos_end[2] or 1, +- } ++ local preview_type = resolve_preview_type(ui_opts, opts) ++ if preview_type == "native" then ++ local tmpfile = vim.fn.tempname() ++ opts.preview = { ++ fn = function(s) ++ if not s or not s[1] then return utils.shell_nop() end ++ local idx = reverse_lookup[utils.strip_ansi_coloring(s[1])] ++ if not idx or not items[idx] then return utils.shell_nop() end ++ local res = ui_opts.preview_item(items[idx]) ++ if type(res) ~= "table" or not res.buf or not vim.api.nvim_buf_is_valid(res.buf) then ++ return utils.shell_nop() ++ end ++ local fd, _ = io.open(tmpfile, "w") ++ if fd then ++ fd:write(table.concat(vim.api.nvim_buf_get_lines(res.buf, 0, -1, false), "\n")) ++ fd:close() ++ end ++ local ft = vim.bo[res.buf].filetype or vim.filetype.match({ buf = res.buf }) ++ local cat = utils.__IS_WINDOWS and "type" or "cat" ++ local nul = utils.__IS_WINDOWS and "NUL" or "/dev/null" ++ local tmp_esc = require("fzf-lua.libuv").shellescape(tmpfile) ++ if ft and ft ~= "" then ++ return ("bat --style=numbers,changes --color=always --language=%s %s 2>%s || %s %s") ++ :format(ft, tmp_esc, nul, cat, tmp_esc) ++ end ++ return ("bat --style=numbers,changes --color=always %s 2>%s || %s %s"):format( ++ tmp_esc, nul, cat, tmp_esc) ++ end, ++ type = "cmd", ++ } ++ ++ -- `preview_offset` is a static fzf flag, so we seed it once from ++ -- the first item's `pos`. The user can scroll within fzf for ++ -- per-entry offsets; the common case is one shared buffer. ++ if items[1] then ++ local first = ui_opts.preview_item(items[1]) ++ if first and first.pos and first.pos[1] then ++ opts.preview_offset = ("+%d"):format(first.pos[1]) + end ++ end + +- return previewer ++ opts.winopts = opts.winopts or {} ++ local prev_on_close = opts.winopts.on_close ++ opts.winopts.on_close = function(...) ++ if prev_on_close then prev_on_close(...) end ++ pcall(os.remove, tmpfile) + end +- } ++ else ++ opts.previewer = { ++ _ctor = function() ++ local previewer = require("fzf-lua.previewer.builtin").buffer_or_file:extend() ++ ---@diagnostic disable-next-line: unused ++ function previewer:parse_entry(entry_str, cb) ++ local str = utils.strip_ansi_coloring(entry_str) ++ local res = ui_opts.preview_item(items[reverse_lookup[str]], cb) ++ if type(res) ~= "table" or (not res.buf and not res.pos) then ++ return { content = { { { "No preview available", "Error" } } }, } ++ end ++ local pos_start, pos_end = res.pos, res.pos_end ++ return { ++ _scratch_buf = res.buf, ++ line = pos_start and pos_start[1] or 1, ++ col = pos_start and pos_start[2] or 1, ++ end_line = pos_end and pos_end[1] or 1, ++ end_col = pos_end and pos_end[2] or 1, ++ } ++ end ++ ++ return previewer ++ end, ++ } ++ end + elseif _OPTS_ONCE then + -- merge and clear the once opts sent from lsp_code_actions. + -- We also override actions to guarantee a single default +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +new file mode 100644 +index 00000000..e454f09c +--- /dev/null ++++ b/tests/ui_select_spec.lua +@@ -0,0 +1,152 @@ ++---@diagnostic disable: unused-local, unused-function, unused ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local child = helpers.new_child_neovim() ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++local exec_lua = child.lua ++ ++--stylua: ignore start ++---@format disable-next ++local reload = function(config) child.unload(); child.setup(config) end ++local type_keys = function(...) return child.type_keys(...) end ++local sleep = function(ms) helpers.sleep(ms, child) end ++--stylua: ignore end ++ ++local T = helpers.new_set_with_child(child, { ++ hooks = { ++ pre_case = function() ++ child.o.shell = "/bin/sh" ++ child.o.termguicolors = true ++ child.o.background = "dark" ++ child.o.statusline = "fzf://" ++ end, ++ }, ++}) ++ ++T["ui_select"] = new_set() ++ ++local register = function(opts) ++ local literal = vim.inspect(opts or {}):gsub("\n", " ") ++ exec_lua(([[FzfLua.register_ui_select(%s)]]):format(literal)) ++end ++ ++-- Wipe any stale /tmp/fzf-lua-ui-select-*.tmp files left by previous ++-- (possibly crashed) test runs. The tmpfile name uses `os.time()` ++-- which has 1-second resolution, so concurrent runs in the same ++-- second would otherwise race on the same path. ++local function cleanup_stale_tmpfiles() ++ for _, f in ipairs(vim.fn.glob("/tmp/fzf-lua-ui-select-*.tmp", true, true)) do ++ pcall(os.remove, f) ++ end ++ exec_lua(([[ ++ for _, f in ipairs(vim.fn.glob("/tmp/fzf-lua-ui-select-*.tmp", true, true)) do ++ pcall(os.remove, f) ++ end ++ ]])) ++end ++ ++-- Open the picker via `vim.ui.select` and wait for it to appear. ++-- The buffer is created in the child nvim (buffers don't cross the rpc ++-- boundary). `pcall` traps any synchronous crash from the native ++-- preview fn (#2743). ++local function open_picker(items, preview_lines, ui_opts) ++ exec_lua(function(items, preview_lines, ui_opts) ++ _G._ui_select_choice = nil ++ _G._ui_select_errors = nil ++ local buf = vim.api.nvim_create_buf(false, true) ++ vim.api.nvim_buf_set_lines(buf, 0, -1, false, preview_lines) ++ local opts = vim.tbl_extend("keep", ui_opts, { ++ format_item = function(item) return tostring(item) end, ++ preview_item = function() return { buf = buf } end, ++ }) ++ local ok, err = pcall(vim.ui.select, items, opts, function(item, idx) ++ _G._ui_select_choice = { item = item, idx = idx } ++ end) ++ if not ok then ++ _G._ui_select_errors = tostring(err); error(err) ++ end ++ end, { items, preview_lines, ui_opts or {} }) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ or child.lua_get([[_G._ui_select_errors]]) ~= nil ++ end, 5000) ++ local errs = child.lua_get([[_G._ui_select_errors]]) ++ eq(errs, vim.NIL, { fail_reason = "vim.ui.select errored: " .. tostring(errs) }) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), true) ++end ++ ++local function close_picker(key) ++ type_keys(key or "") ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == vim.NIL ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), vim.NIL) ++end ++ ++-- Wait until the picker's previewer reports having rendered the ++-- first entry. `last_entry` is the full fzf line (with the `. ` ++-- prefix produced by ui_select). ++local function wait_preview_rendered(expected_entry) ++ child.wait_until(function() ++ local last = child.lua_get([[ ++ (FzfLua.utils.fzf_winobj() or {})._previewer ++ and FzfLua.utils.fzf_winobj()._previewer.last_entry or nil ++ ]]) ++ return last == expected_entry ++ end, 5000) ++end ++ ++T["ui_select"]["buffer preview (default)"] = function() ++ reload({ "default" }) ++ register() ++ open_picker({ "alpha", "beta" }, { "preview-line-1", "preview-line-2" }, ++ { prompt = "Pick (buffer):" }) ++ wait_preview_rendered("1. alpha") ++ local screen = tostring(child.get_screenshot({ redraw = true })) ++ eq(screen:find("alpha", 1, true) ~= nil, true, ++ { fail_reason = "alpha not in screen:\n" .. screen }) ++ eq(screen:find("preview-line-1", 1, true) ~= nil, true, ++ { fail_reason = "preview line 1 not in screen:\n" .. screen }) ++ close_picker() ++end ++ ++T["ui_select"]["native via fzf-tmux profile #2743"] = function() ++ -- The fzf-tmux profile declares `ui_select = { preview_type = "native" }` ++ -- so the picker should use the native backend even without an ++ -- explicit opt (in real tmux the picker runs in a tmux popup; here ++ -- without tmux it degrades to a regular fzf run with the same opts). ++ cleanup_stale_tmpfiles() ++ reload({ "fzf-tmux" }) ++ register() ++ open_picker({ "alpha", "beta" }, { "tmux-line" }) ++ sleep(300) ++ close_picker() ++end ++ ++T["ui_select"]["async preview_item opens without crash"] = function() ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Pick (async):", ++ preview_item = function(_) return {} end, ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_lua_on_create]]), true) ++ close_picker("") ++end ++ ++T["ui_select"]["abort via esc"] = function() ++ reload({ "default" }) ++ register() ++ open_picker({ "alpha" }, { "esc-preview" }) ++ close_picker("") ++ eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2753/tests/test.sh b/tasks/ibhagwan__fzf-lua-2753/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bf66244c44b6cd07f17876853c0d0303fbc3f4a8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 09880d502bc76f1e025fdbdcaeff44650f7ea78a > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2753/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2753/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2753/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2754/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2754/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a1d87a99edae235947ab6761f17d488563db781 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c67fadd9a24230417267e4f9068227e093c0be2b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c67fadd9a24230417267e4f9068227e093c0be2b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c67fadd9a24230417267e4f9068227e093c0be2b \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2754/instruction.md b/tasks/ibhagwan__fzf-lua-2754/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee4a51394e592fb3729fe28d2c01a6996e7fb485 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(buffers): assertion failed when buflist is nil + +## Description + +Problem: `contents` callback calls `utils.CTX()` without `includeBuflist`, +so if the context was recreated between `core.lua:346` (which passes +`includeBuflist=true`) and the async `contents` invocation, `buflist` is +nil and the assertion crashes. The same file already handles this at +`line 282` with `utils.CTX().buflist or {}`. + +Solution: pass `{ includeBuflist = true }` explicitly, ensuring the ctx +always has `buflist` populated when accessed inside the callback. + + +## Summary by CodeRabbit + +## Release Notes + +- **Bug Fixes** + - Fixed an issue where delayed buffer-picker reloads could trigger assertion failures after the picker was closed. + - Buffer lists now remain available for asynchronous reload operations when picker context changes. + - Improved reliability when buffer updates complete after the picker has been closed or recreated. + +- **Tests** + - Added coverage for asynchronous buffer reloads during picker lifecycle changes. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c67fadd9a242`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2754/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2754/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9fa0be8715ab65f5f6b2914d8ffd1e5f2f637054 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/solution/patch.diff @@ -0,0 +1,81 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index ffa49bdb..cccb1720 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -216,7 +216,12 @@ M.buffers = function(opts) + if not opts then return end + + local contents = function(cb) +- local buflist = assert(utils.CTX().buflist) ++ -- `contents` can run asynchronously via fzf's `reload` action (#2736), ++ -- possibly after the picker was closed or its context was re-created ++ -- without `buflist` (e.g. another picker started). Request the buffer ++ -- list explicitly instead of relying on the context created when the ++ -- picker was opened. ++ local buflist = assert(utils.CTX({ includeBuflist = true }).buflist) + local filtered, _, max_bufnr = filter_buffers(opts, buflist) + + if next(filtered) then +diff --git a/tests/buffers_spec.lua b/tests/buffers_spec.lua +new file mode 100644 +index 00000000..0affdee4 +--- /dev/null ++++ b/tests/buffers_spec.lua +@@ -0,0 +1,57 @@ ++---@diagnostic disable: unused-local, unused-function, unused ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local child = helpers.new_child_neovim() ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++local exec_lua = child.lua ++ ++local T = helpers.new_set_with_child(child) ++ ++T["buffers"] = new_set({ n_retry = not helpers.IS_LINUX() and 5 or nil }) ++ ++-- Regression for #2736: `actions.buf_del` uses `reload=true`, which runs the ++-- contents callback asynchronously via a separate RPC process. If the picker ++-- is closed (or its context is otherwise re-created without `buflist`) before ++-- that reload is processed, the old code asserted on `ctx.buflist`. ++T["buffers"]["reload after picker close"] = function() ++ exec_lua([[ ++ for i = 1, 3 do ++ vim.cmd.edit(vim.fn.tempname()) ++ vim.api.nvim_buf_set_lines(0, 0, -1, false, { "buffer " .. i }) ++ end ++ vim.cmd.edit(vim.fn.tempname()) ++ ]]) ++ ++ child.FzfLua.buffers({ previewer = false }) ++ child.wait_until(function() return child.lua_get([[_G._fzf_lua_on_create]]) == true end) ++ child.wait_until(function() return child.lua_get([[_G._fzf_load_called]]) == true end) ++ local reload_cmd = exec_lua([[return FzfLua.config.__resume_data.contents]]) ++ eq(type(reload_cmd), "string") ++ ++ -- closing the picker clears the global context ++ child.type_keys("") ++ child.wait_until(function() return child.lua_get([[_G._fzf_lua_on_create]]) == vim.NIL end) ++ child.wait_until(function() return exec_lua([[return FzfLua.utils.__CTX() == nil]]) end) ++ ++ -- deliver the pending reload, as if it was still in flight when the picker ++ -- was closed ++ local job = exec_lua([[ ++ local cmd = ... ++ _G._fzf_lua_reload_exit = nil ++ return vim.fn.jobstart(cmd, { ++ env = { FZF_LUA_SERVER = vim.v.servername }, ++ on_exit = function(_, code) _G._fzf_lua_reload_exit = code end, ++ }) ++ ]], { reload_cmd }) ++ eq(job > 0, true, { fail_reason = "jobstart failed: " .. tostring(job) }) ++ child.wait_until(function() ++ return exec_lua([[return _G._fzf_lua_reload_exit ~= nil]]) == true ++ end) ++ eq(exec_lua([[return _G._fzf_lua_reload_exit]]), 0) ++ ++ local msgs = child.cmd_capture("messages") ++ eq(msgs:match("assertion failed") == nil, true, msgs) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2754/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2754/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2754/task.toml b/tasks/ibhagwan__fzf-lua-2754/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32eaa77683e5ba83dfc5068254182da7ea00fb67 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2754" +description = "fix(buffers): assertion failed when buflist is nil" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "c67fadd9a24230417267e4f9068227e093c0be2b" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2754" +source_access = "auto" +built_at = "2026-11-16T16:09:55.924406+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7e5a17299fd55ca18b4310f11b9b866775cee108d3dd1558c4c123bfd1b72ad6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-20T03:30:08Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/buffers.lua", + "tests/buffers_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 64 +difficulty = "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:01.052099+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:941d23e53464eb3856e8327a0b5502c05d43ea79d54c62e4a965a292d736931b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2754/tests/capture.py b/tasks/ibhagwan__fzf-lua-2754/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2754/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2754/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee4a51394e592fb3729fe28d2c01a6996e7fb485 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(buffers): assertion failed when buflist is nil + +## Description + +Problem: `contents` callback calls `utils.CTX()` without `includeBuflist`, +so if the context was recreated between `core.lua:346` (which passes +`includeBuflist=true`) and the async `contents` invocation, `buflist` is +nil and the assertion crashes. The same file already handles this at +`line 282` with `utils.CTX().buflist or {}`. + +Solution: pass `{ includeBuflist = true }` explicitly, ensuring the ctx +always has `buflist` populated when accessed inside the callback. + + +## Summary by CodeRabbit + +## Release Notes + +- **Bug Fixes** + - Fixed an issue where delayed buffer-picker reloads could trigger assertion failures after the picker was closed. + - Buffer lists now remain available for asynchronous reload operations when picker context changes. + - Improved reliability when buffer updates complete after the picker has been closed or recreated. + +- **Tests** + - Added coverage for asynchronous buffer reloads during picker lifecycle changes. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c67fadd9a242`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2754/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2754/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9fa0be8715ab65f5f6b2914d8ffd1e5f2f637054 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/tests/oracle.patch @@ -0,0 +1,81 @@ +diff --git a/lua/fzf-lua/providers/buffers.lua b/lua/fzf-lua/providers/buffers.lua +index ffa49bdb..cccb1720 100644 +--- a/lua/fzf-lua/providers/buffers.lua ++++ b/lua/fzf-lua/providers/buffers.lua +@@ -216,7 +216,12 @@ M.buffers = function(opts) + if not opts then return end + + local contents = function(cb) +- local buflist = assert(utils.CTX().buflist) ++ -- `contents` can run asynchronously via fzf's `reload` action (#2736), ++ -- possibly after the picker was closed or its context was re-created ++ -- without `buflist` (e.g. another picker started). Request the buffer ++ -- list explicitly instead of relying on the context created when the ++ -- picker was opened. ++ local buflist = assert(utils.CTX({ includeBuflist = true }).buflist) + local filtered, _, max_bufnr = filter_buffers(opts, buflist) + + if next(filtered) then +diff --git a/tests/buffers_spec.lua b/tests/buffers_spec.lua +new file mode 100644 +index 00000000..0affdee4 +--- /dev/null ++++ b/tests/buffers_spec.lua +@@ -0,0 +1,57 @@ ++---@diagnostic disable: unused-local, unused-function, unused ++local MiniTest = require("mini.test") ++local helpers = require("fzf-lua.test.helpers") ++local child = helpers.new_child_neovim() ++local eq = helpers.expect.equality ++local new_set = MiniTest.new_set ++local exec_lua = child.lua ++ ++local T = helpers.new_set_with_child(child) ++ ++T["buffers"] = new_set({ n_retry = not helpers.IS_LINUX() and 5 or nil }) ++ ++-- Regression for #2736: `actions.buf_del` uses `reload=true`, which runs the ++-- contents callback asynchronously via a separate RPC process. If the picker ++-- is closed (or its context is otherwise re-created without `buflist`) before ++-- that reload is processed, the old code asserted on `ctx.buflist`. ++T["buffers"]["reload after picker close"] = function() ++ exec_lua([[ ++ for i = 1, 3 do ++ vim.cmd.edit(vim.fn.tempname()) ++ vim.api.nvim_buf_set_lines(0, 0, -1, false, { "buffer " .. i }) ++ end ++ vim.cmd.edit(vim.fn.tempname()) ++ ]]) ++ ++ child.FzfLua.buffers({ previewer = false }) ++ child.wait_until(function() return child.lua_get([[_G._fzf_lua_on_create]]) == true end) ++ child.wait_until(function() return child.lua_get([[_G._fzf_load_called]]) == true end) ++ local reload_cmd = exec_lua([[return FzfLua.config.__resume_data.contents]]) ++ eq(type(reload_cmd), "string") ++ ++ -- closing the picker clears the global context ++ child.type_keys("") ++ child.wait_until(function() return child.lua_get([[_G._fzf_lua_on_create]]) == vim.NIL end) ++ child.wait_until(function() return exec_lua([[return FzfLua.utils.__CTX() == nil]]) end) ++ ++ -- deliver the pending reload, as if it was still in flight when the picker ++ -- was closed ++ local job = exec_lua([[ ++ local cmd = ... ++ _G._fzf_lua_reload_exit = nil ++ return vim.fn.jobstart(cmd, { ++ env = { FZF_LUA_SERVER = vim.v.servername }, ++ on_exit = function(_, code) _G._fzf_lua_reload_exit = code end, ++ }) ++ ]], { reload_cmd }) ++ eq(job > 0, true, { fail_reason = "jobstart failed: " .. tostring(job) }) ++ child.wait_until(function() ++ return exec_lua([[return _G._fzf_lua_reload_exit ~= nil]]) == true ++ end) ++ eq(exec_lua([[return _G._fzf_lua_reload_exit]]), 0) ++ ++ local msgs = child.cmd_capture("messages") ++ eq(msgs:match("assertion failed") == nil, true, msgs) ++end ++ ++return T diff --git a/tasks/ibhagwan__fzf-lua-2754/tests/test.sh b/tasks/ibhagwan__fzf-lua-2754/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..248002966220014cd2ee26798bdec7ca395eee7d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c67fadd9a24230417267e4f9068227e093c0be2b > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2754/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2754/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2754/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2755/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2755/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c21d3609fdc16efca8d2412959ed3b42ab1c64f4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin dbe7895a07079b2320abfb3c555b90d3d40a8c9e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard dbe7895a07079b2320abfb3c555b90d3d40a8c9e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base dbe7895a07079b2320abfb3c555b90d3d40a8c9e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2755/instruction.md b/tasks/ibhagwan__fzf-lua-2755/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3231031c7fa03c7f3a5753759bda71f77354ffed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(serverlist): display memory usage on each server + +## Description + +image + + + +## Summary by CodeRabbit + +* **New Features** + * Server list entries now show each server’s memory usage alongside its working directory, with cleaner aligned formatting. + * Server addresses are now extracted more reliably from the selected entry text. + +* **Bug Fixes** + * Improved handling of colored server list entries so connect/kill actions work with the updated display format. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dbe7895a0707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2755/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2755/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4a6e47e370cd84058cfa8001e52f1ae9bf3578ae --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/solution/patch.diff @@ -0,0 +1,82 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 95540cdd..200f01b7 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1327,7 +1327,9 @@ M.undo = function(selected, _opts) + utils.info("Undo jump to %s.", seq == "0" and "origin" or "change #" .. tostring(seq)) + end + +-local parse_entry = function(e) return e and e:match("%((.-)%)") or nil end ++local parse_entry = function(e) ++ return e and utils.strip_ansi_coloring(e):match(utils.nbsp .. "(.-)$") or nil ++end + + M.serverlist_kill = function(sel) + vim.iter(sel):map(parse_entry):each(function(addr) +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index cca1cf93..ab42c514 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -543,7 +543,9 @@ local function make_screenshot(screenshot, addr, lines, columns) + end + + function Previewer.nvim_server:cmdline(_) +- local function parse_entry(e) return e and e:match("%((.-)%)") or nil end ++ local parse_entry = function(e) ++ return e and utils.strip_ansi_coloring(e):match(utils.nbsp .. "(.-)$") or nil ++ end + local act = function(items, lines, columns) + FzfLua.get_info().query = items[2] or "" + local addr = parse_entry(items[1]) +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index 55d5f77e..3223989d 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -794,15 +794,43 @@ M.serverlist = function(opts) + return vim.iter(socket_paths):filter(filter) + end + ++ -- libuv normalizes `ru_maxrss` to kilobytes on all platforms ++ local function fmt_mem(rusage) ++ if not rusage or not rusage.maxrss then return "?" end ++ local kb = rusage.maxrss ++ if kb < 1024 then return string.format("%dK", kb) end ++ if kb < 1024 * 1024 then return string.format("%.1fM", kb / 1024) end ++ return string.format("%.2fG", kb / (1024 * 1024)) ++ end ++ + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") + + local f = function(cb) +- serverlist():each(function(p) ---@type boolean, string? +- local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) +- if not ok or not cwd then return end ++ local entries = {} ++ serverlist():each(function(p) ++ local ok, ret = utils.rpcexec(p, "nvim_exec_lua", ++ "return { vim.uv.cwd(), vim.uv.getrusage() }", {}) ++ if not ok or type(ret) ~= "table" then return end ++ local cwd, rusage = ret[1], ret[2] ++ if not cwd then return end + cwd = FzfLua.path.normalize(cwd) +- cb(("%s (%s)"):format(cwd, p)) ++ entries[#entries + 1] = { ++ cwd = cwd, ++ rusage = rusage, ++ socket = p, ++ } + end) ++ local max_cwd = 0 ++ for _, e in ipairs(entries) do ++ if #e.cwd > max_cwd then max_cwd = #e.cwd end ++ end ++ for _, e in ipairs(entries) do ++ cb(("%-" .. max_cwd .. "s %s%s%s"):format( ++ e.cwd, ++ utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), ++ utils.nbsp, ++ utils.ansi_codes.grey(e.socket))) ++ end + cb(nil) + end + if utils.has(opts, "sk", "3.0.0") then diff --git a/tasks/ibhagwan__fzf-lua-2755/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2755/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2755/task.toml b/tasks/ibhagwan__fzf-lua-2755/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..807265634d1cbc053f1c9930578ddacfa97be981 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2755" +description = "feat(serverlist): display memory usage on each server" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "dbe7895a07079b2320abfb3c555b90d3d40a8c9e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2755" +source_access = "auto" +built_at = "2026-11-16T16:09:55.974134+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f42899e31774cf61ed3cb5d327506d7312d88a4d63077a21a5683dd0de8f18a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-29T05:16:37Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/previewer/fzf.lua", + "lua/fzf-lua/providers/nvim.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 44 +difficulty = "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:01.052582+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0359b1d6aa59ad77b394bddbbc19a3e462003a427328a67fd5723a8afaef2fc0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2755/tests/capture.py b/tasks/ibhagwan__fzf-lua-2755/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2755/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2755/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3231031c7fa03c7f3a5753759bda71f77354ffed --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(serverlist): display memory usage on each server + +## Description + +image + + + +## Summary by CodeRabbit + +* **New Features** + * Server list entries now show each server’s memory usage alongside its working directory, with cleaner aligned formatting. + * Server addresses are now extracted more reliably from the selected entry text. + +* **Bug Fixes** + * Improved handling of colored server list entries so connect/kill actions work with the updated display format. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dbe7895a0707`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2755/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2755/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4a6e47e370cd84058cfa8001e52f1ae9bf3578ae --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/tests/oracle.patch @@ -0,0 +1,82 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 95540cdd..200f01b7 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1327,7 +1327,9 @@ M.undo = function(selected, _opts) + utils.info("Undo jump to %s.", seq == "0" and "origin" or "change #" .. tostring(seq)) + end + +-local parse_entry = function(e) return e and e:match("%((.-)%)") or nil end ++local parse_entry = function(e) ++ return e and utils.strip_ansi_coloring(e):match(utils.nbsp .. "(.-)$") or nil ++end + + M.serverlist_kill = function(sel) + vim.iter(sel):map(parse_entry):each(function(addr) +diff --git a/lua/fzf-lua/previewer/fzf.lua b/lua/fzf-lua/previewer/fzf.lua +index cca1cf93..ab42c514 100644 +--- a/lua/fzf-lua/previewer/fzf.lua ++++ b/lua/fzf-lua/previewer/fzf.lua +@@ -543,7 +543,9 @@ local function make_screenshot(screenshot, addr, lines, columns) + end + + function Previewer.nvim_server:cmdline(_) +- local function parse_entry(e) return e and e:match("%((.-)%)") or nil end ++ local parse_entry = function(e) ++ return e and utils.strip_ansi_coloring(e):match(utils.nbsp .. "(.-)$") or nil ++ end + local act = function(items, lines, columns) + FzfLua.get_info().query = items[2] or "" + local addr = parse_entry(items[1]) +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index 55d5f77e..3223989d 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -794,15 +794,43 @@ M.serverlist = function(opts) + return vim.iter(socket_paths):filter(filter) + end + ++ -- libuv normalizes `ru_maxrss` to kilobytes on all platforms ++ local function fmt_mem(rusage) ++ if not rusage or not rusage.maxrss then return "?" end ++ local kb = rusage.maxrss ++ if kb < 1024 then return string.format("%dK", kb) end ++ if kb < 1024 * 1024 then return string.format("%.1fM", kb / 1024) end ++ return string.format("%.2fG", kb / (1024 * 1024)) ++ end ++ + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") + + local f = function(cb) +- serverlist():each(function(p) ---@type boolean, string? +- local ok, cwd = utils.rpcexec(p, "nvim_exec_lua", "return vim.uv.cwd()", {}) +- if not ok or not cwd then return end ++ local entries = {} ++ serverlist():each(function(p) ++ local ok, ret = utils.rpcexec(p, "nvim_exec_lua", ++ "return { vim.uv.cwd(), vim.uv.getrusage() }", {}) ++ if not ok or type(ret) ~= "table" then return end ++ local cwd, rusage = ret[1], ret[2] ++ if not cwd then return end + cwd = FzfLua.path.normalize(cwd) +- cb(("%s (%s)"):format(cwd, p)) ++ entries[#entries + 1] = { ++ cwd = cwd, ++ rusage = rusage, ++ socket = p, ++ } + end) ++ local max_cwd = 0 ++ for _, e in ipairs(entries) do ++ if #e.cwd > max_cwd then max_cwd = #e.cwd end ++ end ++ for _, e in ipairs(entries) do ++ cb(("%-" .. max_cwd .. "s %s%s%s"):format( ++ e.cwd, ++ utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), ++ utils.nbsp, ++ utils.ansi_codes.grey(e.socket))) ++ end + cb(nil) + end + if utils.has(opts, "sk", "3.0.0") then diff --git a/tasks/ibhagwan__fzf-lua-2755/tests/test.sh b/tasks/ibhagwan__fzf-lua-2755/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcabcb72e2b9b86a09ba32be5752ab0ad3b63f23 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace dbe7895a07079b2320abfb3c555b90d3d40a8c9e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2755/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2755/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2755/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2758/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2758/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3a2c29ae5f4bc195450a667346574a0d3d7a256 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 267f5db2aa2202b9f6cc7a50783f0ccd2121766c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 267f5db2aa2202b9f6cc7a50783f0ccd2121766c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 267f5db2aa2202b9f6cc7a50783f0ccd2121766c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2758/instruction.md b/tasks/ibhagwan__fzf-lua-2758/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..009413c06047c9ea5a5d2e56120305081dd3dde9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(lsp): use current buffer path for outgoing call hierarchy items + +## Description + +callHierarchy/outgoingCalls returns fromRanges that refer to the *caller* file (the current buffer), while to describes the *callee*. The handler was incorrectly using to.uri for both the uri and filename fields, causing fzf-lua to display and jump to the wrong file path. + +Neovim's built-in handler handles this correctly by using ctx.bufnr for outgoing calls instead of the call hierarchy item's URI. + +Fix by detecting outgoing calls (call_hierarchy_call.to ~= nil) and using the current buffer's URI and filename for fromRanges. + + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved call hierarchy navigation so incoming and outgoing results now point to the correct file and location. + * Fixed cases where call hierarchy entries could open the wrong buffer when browsing relationships between symbols. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `267f5db2aa22`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2758/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2758/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6e3031aeedec332460b9def27170b9663c046661 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index 10054db8..e87a0012 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -166,11 +166,13 @@ local function call_hierarchy_handler(opts, cb, _, result, ctx, _) + for _, call_hierarchy_call in pairs(result) do + --- "from" for incoming calls and "to" for outgoing calls + local call_hierarchy_item = call_hierarchy_call.from or call_hierarchy_call.to ++ local is_outgoing = call_hierarchy_call.to ~= nil + for _, range in pairs(call_hierarchy_call.fromRanges) do + local location = { +- uri = call_hierarchy_item.uri, ++ uri = is_outgoing and vim.uri_from_bufnr(utils.CTX().bufnr) or call_hierarchy_item.uri, + range = range, +- filename = vim.uri_to_fname(call_hierarchy_item.uri), ++ filename = is_outgoing and vim.api.nvim_buf_get_name(utils.CTX().bufnr) ++ or vim.uri_to_fname(call_hierarchy_item.uri), + text = call_hierarchy_item.name, + lnum = range.start.line + 1, + col = range.start.character + 1, diff --git a/tasks/ibhagwan__fzf-lua-2758/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2758/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2758/task.toml b/tasks/ibhagwan__fzf-lua-2758/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a7394a5f5274f42b4a42b3e7b5a6e6eb64df394 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2758" +description = "fix(lsp): use current buffer path for outgoing call hierarchy items" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "267f5db2aa2202b9f6cc7a50783f0ccd2121766c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2758" +source_access = "auto" +built_at = "2026-11-16T16:09:55.941977+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c1553ce7702145c0aa387db21531ea69d2bca310c8b7a161ca68832a5519719e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T11:05:30Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/lsp.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.053074+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4bb01644c95f02dfaba610c8d85706188a89fa8206a19672dc8961e6d8f99020" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2758/tests/capture.py b/tasks/ibhagwan__fzf-lua-2758/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2758/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2758/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..009413c06047c9ea5a5d2e56120305081dd3dde9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(lsp): use current buffer path for outgoing call hierarchy items + +## Description + +callHierarchy/outgoingCalls returns fromRanges that refer to the *caller* file (the current buffer), while to describes the *callee*. The handler was incorrectly using to.uri for both the uri and filename fields, causing fzf-lua to display and jump to the wrong file path. + +Neovim's built-in handler handles this correctly by using ctx.bufnr for outgoing calls instead of the call hierarchy item's URI. + +Fix by detecting outgoing calls (call_hierarchy_call.to ~= nil) and using the current buffer's URI and filename for fromRanges. + + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved call hierarchy navigation so incoming and outgoing results now point to the correct file and location. + * Fixed cases where call hierarchy entries could open the wrong buffer when browsing relationships between symbols. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `267f5db2aa22`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2758/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2758/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6e3031aeedec332460b9def27170b9663c046661 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index 10054db8..e87a0012 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -166,11 +166,13 @@ local function call_hierarchy_handler(opts, cb, _, result, ctx, _) + for _, call_hierarchy_call in pairs(result) do + --- "from" for incoming calls and "to" for outgoing calls + local call_hierarchy_item = call_hierarchy_call.from or call_hierarchy_call.to ++ local is_outgoing = call_hierarchy_call.to ~= nil + for _, range in pairs(call_hierarchy_call.fromRanges) do + local location = { +- uri = call_hierarchy_item.uri, ++ uri = is_outgoing and vim.uri_from_bufnr(utils.CTX().bufnr) or call_hierarchy_item.uri, + range = range, +- filename = vim.uri_to_fname(call_hierarchy_item.uri), ++ filename = is_outgoing and vim.api.nvim_buf_get_name(utils.CTX().bufnr) ++ or vim.uri_to_fname(call_hierarchy_item.uri), + text = call_hierarchy_item.name, + lnum = range.start.line + 1, + col = range.start.character + 1, diff --git a/tasks/ibhagwan__fzf-lua-2758/tests/test.sh b/tasks/ibhagwan__fzf-lua-2758/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d2e0e4386b9c06bce69809f560dcbf81a22a280 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 267f5db2aa2202b9f6cc7a50783f0ccd2121766c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2758/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2758/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2758/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2759/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2759/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0059ed8a9e4df112bd140a83cb66877fa6feb48a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin eb32ac8d14b28dba922c038b15637aaacf2e045c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eb32ac8d14b28dba922c038b15637aaacf2e045c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eb32ac8d14b28dba922c038b15637aaacf2e045c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2759/instruction.md b/tasks/ibhagwan__fzf-lua-2759/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa8637c27d8e4d4dca58f583782676b0e5424a6f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(path): convert MSYS2 Unix paths to Windows paths in git_root + +## Description + +On Windows with MSYS2, the native msys2/git package outputs Unix-style paths (e.g. /home/user/repo) from `rev-parse --show-toplevel`. Neovim's `jobstart` expects a valid Windows directory for the `cwd` option, so passing a Unix path causes +`E475: Invalid argument: expected valid directory`. + +Use `cygpath -w` to convert the path when: +- We are on Windows (__IS_WINDOWS) +- The path is not already a Windows absolute path (avoids unnecessary overhead for git-for-windows users who already get C:\... paths) +- `cygpath` executable is available (vim.fn.executable == 1) + +Also handle the cygpath exit code gracefully: if cygpath fails, fall back to the original path instead of returning an error string. + + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved Git root detection on Windows so paths returned from Git are handled more reliably. + * Non-Windows path formats are now automatically converted to Windows-compatible paths when possible, reducing path-related issues in mixed environments. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eb32ac8d14b2`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2759/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2759/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ffa12fe8c19770dc8ceedac3d7cf597b074e2088 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 5d6c9e4e..19b19af6 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -648,6 +648,18 @@ function M.git_root(opts, noerr) + if not noerr then utils.info(table.concat(output, "\n")) end + return nil + end ++ -- On Windows, MSYS2's native git package outputs Unix-style paths ++ -- (e.g. /home/user/repo) rather than Windows-style paths. Use cygpath ++ -- to convert when available. Only run cygpath when the path is not ++ -- already a Windows absolute path to avoid unnecessary overhead ++ -- for users of git-for-windows (which already returns C:\... paths). ++ -- Ref: https://github.com/ibhagwan/fzf-lua/issues/2745 ++ if utils.__IS_WINDOWS and not M.is_absolute(output[1]) and vim.fn.executable("cygpath") == 1 then ++ local cyg_out, rc = utils.io_systemlist({ "cygpath", "-w", output[1] }) ++ if rc == 0 and cyg_out[1] then ++ return cyg_out[1] ++ end ++ end + return output[1] + end + diff --git a/tasks/ibhagwan__fzf-lua-2759/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2759/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2759/task.toml b/tasks/ibhagwan__fzf-lua-2759/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..96853802a949adc3d9ec03bf2cac38c24645e089 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2759" +description = "fix(path): convert MSYS2 Unix paths to Windows paths in git_root" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "eb32ac8d14b28dba922c038b15637aaacf2e045c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2759" +source_access = "auto" +built_at = "2026-11-16T16:09:55.948089+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0ee024f97be3b0d8903acde8080096db731079122ce7f3db27e869ab972fbb59" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-25T13:07:35Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/path.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[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:01.053560+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3fce0696c72c0e7dd814f3834cede05b8880fba389f3e62609a9b57ba677c893" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2759/tests/capture.py b/tasks/ibhagwan__fzf-lua-2759/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2759/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2759/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa8637c27d8e4d4dca58f583782676b0e5424a6f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(path): convert MSYS2 Unix paths to Windows paths in git_root + +## Description + +On Windows with MSYS2, the native msys2/git package outputs Unix-style paths (e.g. /home/user/repo) from `rev-parse --show-toplevel`. Neovim's `jobstart` expects a valid Windows directory for the `cwd` option, so passing a Unix path causes +`E475: Invalid argument: expected valid directory`. + +Use `cygpath -w` to convert the path when: +- We are on Windows (__IS_WINDOWS) +- The path is not already a Windows absolute path (avoids unnecessary overhead for git-for-windows users who already get C:\... paths) +- `cygpath` executable is available (vim.fn.executable == 1) + +Also handle the cygpath exit code gracefully: if cygpath fails, fall back to the original path instead of returning an error string. + + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved Git root detection on Windows so paths returned from Git are handled more reliably. + * Non-Windows path formats are now automatically converted to Windows-compatible paths when possible, reducing path-related issues in mixed environments. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eb32ac8d14b2`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2759/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2759/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ffa12fe8c19770dc8ceedac3d7cf597b074e2088 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/lua/fzf-lua/path.lua b/lua/fzf-lua/path.lua +index 5d6c9e4e..19b19af6 100644 +--- a/lua/fzf-lua/path.lua ++++ b/lua/fzf-lua/path.lua +@@ -648,6 +648,18 @@ function M.git_root(opts, noerr) + if not noerr then utils.info(table.concat(output, "\n")) end + return nil + end ++ -- On Windows, MSYS2's native git package outputs Unix-style paths ++ -- (e.g. /home/user/repo) rather than Windows-style paths. Use cygpath ++ -- to convert when available. Only run cygpath when the path is not ++ -- already a Windows absolute path to avoid unnecessary overhead ++ -- for users of git-for-windows (which already returns C:\... paths). ++ -- Ref: https://github.com/ibhagwan/fzf-lua/issues/2745 ++ if utils.__IS_WINDOWS and not M.is_absolute(output[1]) and vim.fn.executable("cygpath") == 1 then ++ local cyg_out, rc = utils.io_systemlist({ "cygpath", "-w", output[1] }) ++ if rc == 0 and cyg_out[1] then ++ return cyg_out[1] ++ end ++ end + return output[1] + end + diff --git a/tasks/ibhagwan__fzf-lua-2759/tests/test.sh b/tasks/ibhagwan__fzf-lua-2759/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6310c5be044a6cc33d78bdd57be03948ef6b5ccd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace eb32ac8d14b28dba922c038b15637aaacf2e045c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2759/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2759/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2759/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2762/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2762/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76b81ceeda1adcbba72b8337bb028470a8fa1394 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b6f0392fe1645973c795b5bbbd8d6db466a5a25a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b6f0392fe1645973c795b5bbbd8d6db466a5a25a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b6f0392fe1645973c795b5bbbd8d6db466a5a25a \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2762/instruction.md b/tasks/ibhagwan__fzf-lua-2762/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e422a33f1b1abe06e0c90c5d2d53a14e0fe80e6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** fix(rpc): schedule os.exit + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved reliability of RPC session termination to prevent premature or delayed shutdown behavior. + * Updated long-running RPC “keep alive” behavior to better maintain responsiveness during extended activity. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b6f0392fe164`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2762/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2762/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..61b7572073515efd93508ed2bc1ab4089b9cea92 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index b93ada4a..1f18a59a 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -43,7 +43,7 @@ local function server_listen(server_socket, server_socket_path) + -- on linux: zero event can freeze + -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 + -- uv.stop() +- os.exit(0) ++ vim.schedule_wrap(vim.cmd.cquit)(0) + end + + -- if _is_linux then +@@ -56,7 +56,7 @@ local function server_listen(server_socket, server_socket_path) + + receive_socket:read_start(function(err, data) + assert(not err) +- if not data then finish() end ++ if not data then return finish() end + io.write(data) + end) + end) +@@ -108,8 +108,9 @@ local rpc_nvim_exec_lua = function(opts) + os.exit(1) + end + +- uv.run("once") +- uv.run() -- noreturn, quit by os.exit ++ while true do ++ vim.wait(100) ++ end + end + + local args = vim.deepcopy(_G.arg) diff --git a/tasks/ibhagwan__fzf-lua-2762/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2762/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2762/task.toml b/tasks/ibhagwan__fzf-lua-2762/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4599f376faaef55f85607fb75f943c3cadc47ed6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2762" +description = "fix(rpc): schedule os.exit" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "b6f0392fe1645973c795b5bbbd8d6db466a5a25a" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2762" +source_access = "auto" +built_at = "2026-11-16T16:09:55.972667+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9f3dec2734e1c56803296cfbc8aa8ce6e40088ed678ee104a3c9865a0e43eca6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-28T02:33:34Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/rpc.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[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:01.054029+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7ada21714b1603ad6ff48933c86a063931b22183641f29711bdbada72ca13ef4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2762/tests/capture.py b/tasks/ibhagwan__fzf-lua-2762/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2762/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2762/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e422a33f1b1abe06e0c90c5d2d53a14e0fe80e6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** fix(rpc): schedule os.exit + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved reliability of RPC session termination to prevent premature or delayed shutdown behavior. + * Updated long-running RPC “keep alive” behavior to better maintain responsiveness during extended activity. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b6f0392fe164`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2762/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2762/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..61b7572073515efd93508ed2bc1ab4089b9cea92 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/lua/fzf-lua/rpc.lua b/lua/fzf-lua/rpc.lua +index b93ada4a..1f18a59a 100644 +--- a/lua/fzf-lua/rpc.lua ++++ b/lua/fzf-lua/rpc.lua +@@ -43,7 +43,7 @@ local function server_listen(server_socket, server_socket_path) + -- on linux: zero event can freeze + -- https://github.com/ibhagwan/fzf-lua/pull/1955#issuecomment-2785474217 + -- uv.stop() +- os.exit(0) ++ vim.schedule_wrap(vim.cmd.cquit)(0) + end + + -- if _is_linux then +@@ -56,7 +56,7 @@ local function server_listen(server_socket, server_socket_path) + + receive_socket:read_start(function(err, data) + assert(not err) +- if not data then finish() end ++ if not data then return finish() end + io.write(data) + end) + end) +@@ -108,8 +108,9 @@ local rpc_nvim_exec_lua = function(opts) + os.exit(1) + end + +- uv.run("once") +- uv.run() -- noreturn, quit by os.exit ++ while true do ++ vim.wait(100) ++ end + end + + local args = vim.deepcopy(_G.arg) diff --git a/tasks/ibhagwan__fzf-lua-2762/tests/test.sh b/tasks/ibhagwan__fzf-lua-2762/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d8cd80f0b9f55ffce66408a3c87051a147563a3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b6f0392fe1645973c795b5bbbd8d6db466a5a25a > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2762/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2762/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2762/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2764/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2764/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1f5fe063238d5e1831aeb389fe1df6b1f1a087d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 029a162a6671fdd453001fc1bca047ee3ecd5481 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 029a162a6671fdd453001fc1bca047ee3ecd5481 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 029a162a6671fdd453001fc1bca047ee3ecd5481 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2764/instruction.md b/tasks/ibhagwan__fzf-lua-2764/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8de280ce780d020718d352e05145b2a335391547 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci(lint): pin fixed upstream emmylua_check + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Improved the lint workflow setup to use a consistent Rust toolchain and install the Lua analysis tool from source. + * Updated the lint environment so checks run with the correct data directory configuration. + * Removed the previous prebuilt download approach for one lint dependency. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `029a162a6671`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2764/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2764/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e404da20d17236e1bfab1955be10d5e17e864a09 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index ff526391..e975a32e 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -37,19 +37,22 @@ jobs: + export PATH="${PWD}/lua-language-server/bin:${PATH}" + lua-language-server --version + ++ - name: Install rust toolchain ++ uses: dtolnay/rust-toolchain@master ++ with: ++ toolchain: stable ++ + - name: Install emmylua_check +- env: +- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +- run: | +- cd +- gh release download -R EmmyLuaLs/emmylua-analyzer-rust -p emmylua_check-linux-x64.tar.gz -D emmylua_check +- tar xzf emmylua_check/* -C emmylua_check +- echo "${PWD}/emmylua_check/" >> $GITHUB_PATH +- export PATH="${PWD}/emmylua_check/:${PATH}" +- emmylua_check --version ++ uses: baptiste0928/cargo-install@v3 ++ with: ++ crate: emmylua_check ++ git: https://github.com/EmmyLuaLs/emmylua-analyzer-rust ++ commit: 7c96abd684c3d840719c0d9d24ada5e5b1b81288 ++ cache-key: emmylua-check-v1 + + - name: Lint + run: | ++ export XDG_DATA_HOME="$HOME/.local/share" + make deps + make lint + make emmylua-check diff --git a/tasks/ibhagwan__fzf-lua-2764/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2764/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2764/task.toml b/tasks/ibhagwan__fzf-lua-2764/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..12d5e1ca2bd69d2ab178c09bd379d82733b635a9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2764" +description = "ci(lint): pin fixed upstream emmylua_check" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "029a162a6671fdd453001fc1bca047ee3ecd5481" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2764" +source_access = "auto" +built_at = "2026-11-16T16:09:55.976951+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4324a5eb810040ba43adc3013a50bce5e3c56144a114537413204a1fa216bee8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-06-29T01:37:15Z" +diff_format = "unified" +context_files = [ + ".github/workflows/lint.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 21 +difficulty = "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:01.054538+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7d1283c6bef6df78f91206e31b767687af43806e5664014a8c3f0c825ff8c7cd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2764/tests/capture.py b/tasks/ibhagwan__fzf-lua-2764/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2764/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2764/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8de280ce780d020718d352e05145b2a335391547 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ci(lint): pin fixed upstream emmylua_check + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Improved the lint workflow setup to use a consistent Rust toolchain and install the Lua analysis tool from source. + * Updated the lint environment so checks run with the correct data directory configuration. + * Removed the previous prebuilt download approach for one lint dependency. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `029a162a6671`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2764/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2764/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e404da20d17236e1bfab1955be10d5e17e864a09 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index ff526391..e975a32e 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -37,19 +37,22 @@ jobs: + export PATH="${PWD}/lua-language-server/bin:${PATH}" + lua-language-server --version + ++ - name: Install rust toolchain ++ uses: dtolnay/rust-toolchain@master ++ with: ++ toolchain: stable ++ + - name: Install emmylua_check +- env: +- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +- run: | +- cd +- gh release download -R EmmyLuaLs/emmylua-analyzer-rust -p emmylua_check-linux-x64.tar.gz -D emmylua_check +- tar xzf emmylua_check/* -C emmylua_check +- echo "${PWD}/emmylua_check/" >> $GITHUB_PATH +- export PATH="${PWD}/emmylua_check/:${PATH}" +- emmylua_check --version ++ uses: baptiste0928/cargo-install@v3 ++ with: ++ crate: emmylua_check ++ git: https://github.com/EmmyLuaLs/emmylua-analyzer-rust ++ commit: 7c96abd684c3d840719c0d9d24ada5e5b1b81288 ++ cache-key: emmylua-check-v1 + + - name: Lint + run: | ++ export XDG_DATA_HOME="$HOME/.local/share" + make deps + make lint + make emmylua-check diff --git a/tasks/ibhagwan__fzf-lua-2764/tests/test.sh b/tasks/ibhagwan__fzf-lua-2764/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b45759552c621797d0c1f47d4194959632fb556 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 029a162a6671fdd453001fc1bca047ee3ecd5481 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2764/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2764/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2764/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2765/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2765/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a2847be4be526d3d97869db60ea1f0af74a37d6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 39da6060d53659acf3ec118200bc48721b29b8fd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 39da6060d53659acf3ec118200bc48721b29b8fd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 39da6060d53659acf3ec118200bc48721b29b8fd \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2765/instruction.md b/tasks/ibhagwan__fzf-lua-2765/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cacc07fe234909fba5432568f7213bd2b4cf3b38 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** feat(serverlist): cpu usage and every(2) + +## Description + +fzf 0.73 add timer support +https://github.com/junegunn/fzf/blob/f2e451596c5d23de0069cdc51ea3fec73b7fe835/CHANGELOG.md#L23-L34 + + +## Summary by CodeRabbit + +* **New Features** + * Added per-server CPU usage to the server list, shown in a new CPU column alongside existing memory and socket details. + * Enabled periodic server list refreshing (on supported fzf versions) so CPU readings stay up to date. +* **Bug Fixes** + * Improved RPC request reliability by introducing an explicit timeout/cleanup path, returning a clear “Timeout” result instead of potentially waiting indefinitely. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39da6060d536`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2765/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2765/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..58d212159df6610f45010698448422d70de50c5d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/solution/patch.diff @@ -0,0 +1,124 @@ +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index 3223989d..7053da58 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -803,42 +803,75 @@ M.serverlist = function(opts) + return string.format("%.2fG", kb / (1024 * 1024)) + end + ++ local function cpu_time_us(rusage) ++ if not rusage or not rusage.utime or not rusage.stime then return nil end ++ return (rusage.utime.sec * 1e6 + rusage.utime.usec) ++ + (rusage.stime.sec * 1e6 + rusage.stime.usec) ++ end ++ ++ local function fmt_cpu(pct) ++ if not pct then return " ?" end ++ if pct < 10 then return string.format("%.1f%%", pct) end ++ if pct < 100 then return string.format("%3.0f%%", pct) end ++ return string.format("%4.0f%%", pct) ++ end ++ + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") + ++ local SAMPLE_INTERVAL_MS = 50 ++ + local f = function(cb) + local entries = {} + serverlist():each(function(p) + local ok, ret = utils.rpcexec(p, "nvim_exec_lua", +- "return { vim.uv.cwd(), vim.uv.getrusage() }", {}) ++ "return { vim.uv.cwd(), vim.uv.getrusage(), vim.uv.hrtime() }", {}) + if not ok or type(ret) ~= "table" then return end +- local cwd, rusage = ret[1], ret[2] ++ local cwd, rusage, wall_start = ret[1], ret[2], ret[3] + if not cwd then return end +- cwd = FzfLua.path.normalize(cwd) + entries[#entries + 1] = { +- cwd = cwd, ++ cwd = FzfLua.path.normalize(cwd), + rusage = rusage, ++ wall_start = wall_start, + socket = p, + } + end) +- local max_cwd = 0 +- for _, e in ipairs(entries) do +- if #e.cwd > max_cwd then max_cwd = #e.cwd end +- end +- for _, e in ipairs(entries) do +- cb(("%-" .. max_cwd .. "s %s%s%s"):format( +- e.cwd, +- utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), +- utils.nbsp, +- utils.ansi_codes.grey(e.socket))) +- end +- cb(nil) ++ vim.defer_fn(function() ++ for _, e in ipairs(entries) do ++ local ok, ret = utils.rpcexec(e.socket, "nvim_exec_lua", ++ "return { vim.uv.getrusage(), vim.uv.hrtime() }", {}) ++ if ok and type(ret) == "table" then ++ local rusage2, wall_end = ret[1], ret[2] ++ if rusage2 and wall_end and e.wall_start then ++ local cpu1, cpu2 = cpu_time_us(e.rusage), cpu_time_us(rusage2) ++ if cpu1 and cpu2 and wall_end > e.wall_start then ++ e.cpu_pct = (cpu2 - cpu1) / ((wall_end - e.wall_start) / 1000) * 100 ++ end ++ end ++ end ++ end ++ local max_cwd = 0 ++ for _, e in ipairs(entries) do ++ if #e.cwd > max_cwd then max_cwd = #e.cwd end ++ end ++ for _, e in ipairs(entries) do ++ cb(("%-" .. max_cwd .. "s %s %s%s%s"):format( ++ e.cwd, ++ utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), ++ utils.ansi_codes.yellow(string.format("%5s", fmt_cpu(e.cpu_pct))), ++ utils.nbsp, ++ utils.ansi_codes.grey(e.socket))) ++ end ++ cb(nil) ++ end, SAMPLE_INTERVAL_MS) + end + if utils.has(opts, "sk", "3.0.0") then + opts = vim.tbl_deep_extend("force", opts, { winopts = { preview = { pty = true } } }) + end +- core.fzf_exec(function(cb) +- vim.defer_fn(function() f(cb) end, 50) -- wait for spawn/remote_exec? +- end, opts) ++ if utils.has(opts, "fzf", "0.73.0") then ++ opts.actions = opts.actions or {} ++ opts.actions["every(2)"] = { fn = function() end, reload = true } ++ end ++ core.fzf_exec(f, opts) + end + + return M +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 89a986f4..644a3d13 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1607,8 +1607,20 @@ function M.rpcexec(addr, method, ...) + ---@type boolean, any + local ok, chan = pcall(vim.fn.sockconnect, "pipe", addr, { rpc = true }) + if not ok or chan == 0 then return false, "Invalid channel" end ++ local timer = assert(vim.uv.new_timer()) ++ local fired = false ++ pcall(function() ++ require("ffi").cdef [[bool channel_close(unsigned long long id, int part, const char **error);]] ++ end) ++ timer:start(200, 0, M.nil_wrap(function() ++ if not timer:is_closing() then timer:close() end ++ fired = true ++ require("ffi").C.channel_close(chan, 3, nil) ++ end)) + ---@cast chan integer + local ret = { pcall(vim.rpcrequest, chan, method, ...) } ++ if not timer:is_closing() then timer:close() end ++ if fired then return false, "Timeout" end + vim.fn.chanclose(chan) + local tonil = function(v) if v == vim.NIL then return nil else return v end end + return unpack(vim.tbl_map(tonil, ret)) diff --git a/tasks/ibhagwan__fzf-lua-2765/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2765/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2765/task.toml b/tasks/ibhagwan__fzf-lua-2765/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffdf1a9df6724455c78966f31883f84b817299e8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2765" +description = "feat(serverlist): cpu usage and every(2)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "39da6060d53659acf3ec118200bc48721b29b8fd" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2765" +source_access = "auto" +built_at = "2026-11-16T16:09:55.971055+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6163ada103c91149b26a7a4740267b6e278cc868258a9754f4e9ba02b10f332c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-03T10:23:08Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/nvim.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 83 +difficulty = "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:01.055029+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c03952a86e7eb280ff93f81f300c2d99384690d5f26f954ab3d4ea80c3c22c97" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2765/tests/capture.py b/tasks/ibhagwan__fzf-lua-2765/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2765/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2765/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cacc07fe234909fba5432568f7213bd2b4cf3b38 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** feat(serverlist): cpu usage and every(2) + +## Description + +fzf 0.73 add timer support +https://github.com/junegunn/fzf/blob/f2e451596c5d23de0069cdc51ea3fec73b7fe835/CHANGELOG.md#L23-L34 + + +## Summary by CodeRabbit + +* **New Features** + * Added per-server CPU usage to the server list, shown in a new CPU column alongside existing memory and socket details. + * Enabled periodic server list refreshing (on supported fzf versions) so CPU readings stay up to date. +* **Bug Fixes** + * Improved RPC request reliability by introducing an explicit timeout/cleanup path, returning a clear “Timeout” result instead of potentially waiting indefinitely. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39da6060d536`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2765/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2765/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..58d212159df6610f45010698448422d70de50c5d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/tests/oracle.patch @@ -0,0 +1,124 @@ +diff --git a/lua/fzf-lua/providers/nvim.lua b/lua/fzf-lua/providers/nvim.lua +index 3223989d..7053da58 100644 +--- a/lua/fzf-lua/providers/nvim.lua ++++ b/lua/fzf-lua/providers/nvim.lua +@@ -803,42 +803,75 @@ M.serverlist = function(opts) + return string.format("%.2fG", kb / (1024 * 1024)) + end + ++ local function cpu_time_us(rusage) ++ if not rusage or not rusage.utime or not rusage.stime then return nil end ++ return (rusage.utime.sec * 1e6 + rusage.utime.usec) ++ + (rusage.stime.sec * 1e6 + rusage.stime.usec) ++ end ++ ++ local function fmt_cpu(pct) ++ if not pct then return " ?" end ++ if pct < 10 then return string.format("%.1f%%", pct) end ++ if pct < 100 then return string.format("%3.0f%%", pct) end ++ return string.format("%4.0f%%", pct) ++ end ++ + opts = require("fzf-lua.config").normalize_opts(opts or {}, "serverlist") + ++ local SAMPLE_INTERVAL_MS = 50 ++ + local f = function(cb) + local entries = {} + serverlist():each(function(p) + local ok, ret = utils.rpcexec(p, "nvim_exec_lua", +- "return { vim.uv.cwd(), vim.uv.getrusage() }", {}) ++ "return { vim.uv.cwd(), vim.uv.getrusage(), vim.uv.hrtime() }", {}) + if not ok or type(ret) ~= "table" then return end +- local cwd, rusage = ret[1], ret[2] ++ local cwd, rusage, wall_start = ret[1], ret[2], ret[3] + if not cwd then return end +- cwd = FzfLua.path.normalize(cwd) + entries[#entries + 1] = { +- cwd = cwd, ++ cwd = FzfLua.path.normalize(cwd), + rusage = rusage, ++ wall_start = wall_start, + socket = p, + } + end) +- local max_cwd = 0 +- for _, e in ipairs(entries) do +- if #e.cwd > max_cwd then max_cwd = #e.cwd end +- end +- for _, e in ipairs(entries) do +- cb(("%-" .. max_cwd .. "s %s%s%s"):format( +- e.cwd, +- utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), +- utils.nbsp, +- utils.ansi_codes.grey(e.socket))) +- end +- cb(nil) ++ vim.defer_fn(function() ++ for _, e in ipairs(entries) do ++ local ok, ret = utils.rpcexec(e.socket, "nvim_exec_lua", ++ "return { vim.uv.getrusage(), vim.uv.hrtime() }", {}) ++ if ok and type(ret) == "table" then ++ local rusage2, wall_end = ret[1], ret[2] ++ if rusage2 and wall_end and e.wall_start then ++ local cpu1, cpu2 = cpu_time_us(e.rusage), cpu_time_us(rusage2) ++ if cpu1 and cpu2 and wall_end > e.wall_start then ++ e.cpu_pct = (cpu2 - cpu1) / ((wall_end - e.wall_start) / 1000) * 100 ++ end ++ end ++ end ++ end ++ local max_cwd = 0 ++ for _, e in ipairs(entries) do ++ if #e.cwd > max_cwd then max_cwd = #e.cwd end ++ end ++ for _, e in ipairs(entries) do ++ cb(("%-" .. max_cwd .. "s %s %s%s%s"):format( ++ e.cwd, ++ utils.ansi_codes.cyan(string.format("%7s", fmt_mem(e.rusage))), ++ utils.ansi_codes.yellow(string.format("%5s", fmt_cpu(e.cpu_pct))), ++ utils.nbsp, ++ utils.ansi_codes.grey(e.socket))) ++ end ++ cb(nil) ++ end, SAMPLE_INTERVAL_MS) + end + if utils.has(opts, "sk", "3.0.0") then + opts = vim.tbl_deep_extend("force", opts, { winopts = { preview = { pty = true } } }) + end +- core.fzf_exec(function(cb) +- vim.defer_fn(function() f(cb) end, 50) -- wait for spawn/remote_exec? +- end, opts) ++ if utils.has(opts, "fzf", "0.73.0") then ++ opts.actions = opts.actions or {} ++ opts.actions["every(2)"] = { fn = function() end, reload = true } ++ end ++ core.fzf_exec(f, opts) + end + + return M +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 89a986f4..644a3d13 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1607,8 +1607,20 @@ function M.rpcexec(addr, method, ...) + ---@type boolean, any + local ok, chan = pcall(vim.fn.sockconnect, "pipe", addr, { rpc = true }) + if not ok or chan == 0 then return false, "Invalid channel" end ++ local timer = assert(vim.uv.new_timer()) ++ local fired = false ++ pcall(function() ++ require("ffi").cdef [[bool channel_close(unsigned long long id, int part, const char **error);]] ++ end) ++ timer:start(200, 0, M.nil_wrap(function() ++ if not timer:is_closing() then timer:close() end ++ fired = true ++ require("ffi").C.channel_close(chan, 3, nil) ++ end)) + ---@cast chan integer + local ret = { pcall(vim.rpcrequest, chan, method, ...) } ++ if not timer:is_closing() then timer:close() end ++ if fired then return false, "Timeout" end + vim.fn.chanclose(chan) + local tonil = function(v) if v == vim.NIL then return nil else return v end end + return unpack(vim.tbl_map(tonil, ret)) diff --git a/tasks/ibhagwan__fzf-lua-2765/tests/test.sh b/tasks/ibhagwan__fzf-lua-2765/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7fa18d52edab80e1217b68188be4a78a415902f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 39da6060d53659acf3ec118200bc48721b29b8fd > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2765/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2765/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2765/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2767/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2767/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a2847be4be526d3d97869db60ea1f0af74a37d6 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 39da6060d53659acf3ec118200bc48721b29b8fd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 39da6060d53659acf3ec118200bc48721b29b8fd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 39da6060d53659acf3ec118200bc48721b29b8fd \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2767/instruction.md b/tasks/ibhagwan__fzf-lua-2767/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f919c929c72d9576d40366a2474343cf012526e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** refactor(swiper): better line logic + +## Description + +to accomodate for winbar/status line + +fix #2766 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved match highlighting in preview panes so visible results are scanned more accurately. + * Fixed issues where highlighted matches could be missed or misaligned when the preview window size or layout changed. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39da6060d536`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2767/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2767/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3627164faf17eb7bc6e8e280d2333abd70e20be8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/lua/fzf-lua/previewer/swiper.lua b/lua/fzf-lua/previewer/swiper.lua +index da0a5c0e..0b128761 100644 +--- a/lua/fzf-lua/previewer/swiper.lua ++++ b/lua/fzf-lua/previewer/swiper.lua +@@ -145,16 +145,14 @@ function M.base:highlight_matches() + if not vim.api.nvim_win_is_valid(fzf_win) or not vim.api.nvim_buf_is_valid(fzf_buf) then + return + end +- local height = vim.api.nvim_win_get_height(fzf_win) +- local off = vim.o.cmdheight + (vim.o.laststatus and 1 or 0) +- local lines = vim.o.lines +- local l_s = lines - height - off + 1 +- local l_e = lines - off - 1 ++ local top = vim.fn.line("w0", fzf_win) ++ local bot = vim.fn.line("w$", fzf_win) ++ local top_row = vim.fn.screenpos(fzf_win, top, 1).row + local max_columns = vim.o.columns + local buf_lines = vim.api.nvim_buf_get_lines(fzf_buf, 0, -1, false) +- for r = l_s, l_e do ++ for buf_lnum = top, bot do + (function() +- local buf_lnum = r - l_s + 2 ++ local r = top_row + (buf_lnum - top) + local lnum, _, col_valid_idx, col_off = self:parse_lnum_col(assert(buf_lines[buf_lnum])) + if not lnum or lnum < 1 then return end + local state = { bytelen = 0 } diff --git a/tasks/ibhagwan__fzf-lua-2767/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2767/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2767/task.toml b/tasks/ibhagwan__fzf-lua-2767/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e6fd94b696546de47c53888637696f083438c2c3 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2767" +description = "refactor(swiper): better line logic" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "39da6060d53659acf3ec118200bc48721b29b8fd" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2767" +source_access = "auto" +built_at = "2026-11-16T16:09:55.943281+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d0d383ee4e86e76100cdcb890c911d39803a27ca634e838f46bd6c7148a4350f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-03T15:21:23Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/swiper.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[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:01.055499+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c03952a86e7eb280ff93f81f300c2d99384690d5f26f954ab3d4ea80c3c22c97" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2767/tests/capture.py b/tasks/ibhagwan__fzf-lua-2767/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2767/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2767/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f919c929c72d9576d40366a2474343cf012526e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** refactor(swiper): better line logic + +## Description + +to accomodate for winbar/status line + +fix #2766 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved match highlighting in preview panes so visible results are scanned more accurately. + * Fixed issues where highlighted matches could be missed or misaligned when the preview window size or layout changed. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39da6060d536`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2767/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2767/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3627164faf17eb7bc6e8e280d2333abd70e20be8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/lua/fzf-lua/previewer/swiper.lua b/lua/fzf-lua/previewer/swiper.lua +index da0a5c0e..0b128761 100644 +--- a/lua/fzf-lua/previewer/swiper.lua ++++ b/lua/fzf-lua/previewer/swiper.lua +@@ -145,16 +145,14 @@ function M.base:highlight_matches() + if not vim.api.nvim_win_is_valid(fzf_win) or not vim.api.nvim_buf_is_valid(fzf_buf) then + return + end +- local height = vim.api.nvim_win_get_height(fzf_win) +- local off = vim.o.cmdheight + (vim.o.laststatus and 1 or 0) +- local lines = vim.o.lines +- local l_s = lines - height - off + 1 +- local l_e = lines - off - 1 ++ local top = vim.fn.line("w0", fzf_win) ++ local bot = vim.fn.line("w$", fzf_win) ++ local top_row = vim.fn.screenpos(fzf_win, top, 1).row + local max_columns = vim.o.columns + local buf_lines = vim.api.nvim_buf_get_lines(fzf_buf, 0, -1, false) +- for r = l_s, l_e do ++ for buf_lnum = top, bot do + (function() +- local buf_lnum = r - l_s + 2 ++ local r = top_row + (buf_lnum - top) + local lnum, _, col_valid_idx, col_off = self:parse_lnum_col(assert(buf_lines[buf_lnum])) + if not lnum or lnum < 1 then return end + local state = { bytelen = 0 } diff --git a/tasks/ibhagwan__fzf-lua-2767/tests/test.sh b/tasks/ibhagwan__fzf-lua-2767/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7fa18d52edab80e1217b68188be4a78a415902f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 39da6060d53659acf3ec118200bc48721b29b8fd > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2767/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2767/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2767/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2769/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2769/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7164a0b87058d1e35d9639b8d1bcde5274e63e52 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d2084cf776049b4bce6764eb58cda567dec781c4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d2084cf776049b4bce6764eb58cda567dec781c4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d2084cf776049b4bce6764eb58cda567dec781c4 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2769/instruction.md b/tasks/ibhagwan__fzf-lua-2769/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d46ca9e6adbe509194e4d21c3685d8d8f50f562 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: soft deprecated ui_select=true + +## Description + +Fix + + +## Summary by CodeRabbit + +- **Bug Fixes** + - Improved backward compatibility for the `ui_select` configuration. + - `ui_select = true` is now treated as an enabled empty configuration, while `ui_select = false` cleanly disables the option. + - Added a deprecation warning encouraging the newer `ui_select = {}` format. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2084cf77604`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2769/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2769/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4062ad0cff32773c72c20f8fc46bc31db52eb764 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index 9598c8dc..d9f3ea52 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -220,6 +220,10 @@ function M.setup(opts, do_not_reset_defaults) + M.setup_highlights() + -- opt-in register ui.select via setup + if opts.ui_select then ++ if type(opts.ui_select) == "boolean" then -- back compat #2768 ++ opts.ui_select = opts.ui_select and {} or nil ++ vim.deprecate("ui_select = true", "ui_select = {}", "Jan 2027", "FzfLua") ++ end + M.register_ui_select((type(opts.ui_select) == "table" or type(opts.ui_select) == "function") + and opts.ui_select or nil, + true) -- silent diff --git a/tasks/ibhagwan__fzf-lua-2769/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2769/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2769/task.toml b/tasks/ibhagwan__fzf-lua-2769/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..719729fa027b24c8cad4aaa6f052677e9bc9c6fc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2769" +description = "fix: soft deprecated ui_select=true" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "d2084cf776049b4bce6764eb58cda567dec781c4" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2769" +source_access = "auto" +built_at = "2026-11-16T16:09:55.967993+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e1abe4dd70314c0685ae3503a6a30193048c8b4318a200e92643e30af24f67cc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-04T02:02:30Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/init.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.055962+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:55f044aa79d44d3ccf660596ddd69566a282483bc9c458138992b16b49fd29be" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2769/tests/capture.py b/tasks/ibhagwan__fzf-lua-2769/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2769/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2769/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d46ca9e6adbe509194e4d21c3685d8d8f50f562 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: soft deprecated ui_select=true + +## Description + +Fix + + +## Summary by CodeRabbit + +- **Bug Fixes** + - Improved backward compatibility for the `ui_select` configuration. + - `ui_select = true` is now treated as an enabled empty configuration, while `ui_select = false` cleanly disables the option. + - Added a deprecation warning encouraging the newer `ui_select = {}` format. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2084cf77604`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2769/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2769/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4062ad0cff32773c72c20f8fc46bc31db52eb764 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index 9598c8dc..d9f3ea52 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -220,6 +220,10 @@ function M.setup(opts, do_not_reset_defaults) + M.setup_highlights() + -- opt-in register ui.select via setup + if opts.ui_select then ++ if type(opts.ui_select) == "boolean" then -- back compat #2768 ++ opts.ui_select = opts.ui_select and {} or nil ++ vim.deprecate("ui_select = true", "ui_select = {}", "Jan 2027", "FzfLua") ++ end + M.register_ui_select((type(opts.ui_select) == "table" or type(opts.ui_select) == "function") + and opts.ui_select or nil, + true) -- silent diff --git a/tasks/ibhagwan__fzf-lua-2769/tests/test.sh b/tasks/ibhagwan__fzf-lua-2769/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c9de6da12a102a41445903c4ea97ce26ae01ec2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d2084cf776049b4bce6764eb58cda567dec781c4 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2769/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2769/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2769/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2771/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2771/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..710cbfe4bb7ca92ec66d60d4038485a5adab5303 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 237b7e7f2bd07becc83144933b6058cc15bef2dc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 237b7e7f2bd07becc83144933b6058cc15bef2dc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 237b7e7f2bd07becc83144933b6058cc15bef2dc \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2771/instruction.md b/tasks/ibhagwan__fzf-lua-2771/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a96ca186826d6fcdf2677cd8ee16156972ef99 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(ui_select): restore callable opts (fix #2770) + +## Description + +@dpetka, can you test and lmk if this solves your issue? + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Updated `ui_select` to correctly handle function-based option values by resolving them with `(ui_opts, items)` before applying the options. + * Ensured registered function-based options still receive the expected arguments, preserving custom `prompt` and `kind`. + +* **Tests** + * Added a test covering function-based `ui_select` options to confirm the callback receives `(ui_opts, items)` and that item counts and fields are passed through correctly. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `237b7e7f2bd0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2771/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2771/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..186f53cc54b7fd827864bad4bbda80123b822166 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 3312c246..23fbf069 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -102,6 +102,15 @@ M.ui_select = function(items, ui_opts, on_choice) + + local opts = _OPTS or {} + ++ -- enables customization per kind (#755): the registered opts can be a ++ -- function that returns an opts table based on the `ui_opts` (kind, ++ -- prompt, etc.) and the `items` being selected. `config.normalize_opts` ++ -- calls function opts with no args, so resolve the function here first ++ -- to preserve the historical `opts(ui_opts, items)` signature (#2770). ++ if vim.is_callable(opts) then ++ opts = opts(ui_opts, items) ++ end ++ + opts = config.normalize_opts(opts, "ui_select") + if not opts then return end + +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +index e454f09c..96089cf0 100644 +--- a/tests/ui_select_spec.lua ++++ b/tests/ui_select_spec.lua +@@ -149,4 +149,26 @@ T["ui_select"]["abort via esc"] = function() + eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) + end + ++T["ui_select"]["registered function opts receive (ui_opts, items) #2770"] = function() ++ reload({ "default" }) ++ -- `config.normalize_opts` calls function opts with no args; the wrapper ++ -- in `M.ui_select` must resolve the function with `(ui_opts, items)` ++ -- before normalizing, preserving the documented interface (#755). ++ exec_lua([[ ++ FzfLua.register_ui_select(function(fzf_opts, items) ++ _G._ui_select_args = { ++ kind = fzf_opts.kind, ++ prompt = fzf_opts.prompt, ++ nitems = #items, ++ } ++ return {} ++ end) ++ ]]) ++ open_picker({ "alpha", "beta" }, { "preview-line-1", "preview-line-2" }, ++ { prompt = "Pick (fn):", kind = "codeaction" }) ++ close_picker("") ++ eq(child.lua_get([[_G._ui_select_args]]), ++ { kind = "codeaction", prompt = "Pick (fn):", nitems = 2 }) ++end ++ + return T diff --git a/tasks/ibhagwan__fzf-lua-2771/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2771/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2771/task.toml b/tasks/ibhagwan__fzf-lua-2771/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..77ca9c0d6c3945e9fe9f0dbf8804150ca59c4442 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2771" +description = "fix(ui_select): restore callable opts (fix #2770)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "237b7e7f2bd07becc83144933b6058cc15bef2dc" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2771" +source_access = "auto" +built_at = "2026-11-16T16:09:55.944574+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0a0f4c8dcf740f629a6ea52542635fe1fb6e526df5129200dfd67304d6c789fc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-05T01:13:04Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/ui_select.lua", + "tests/ui_select_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 31 +difficulty = "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:01.056453+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5803f7568b9aabf1dcb490a67034f5a3dd1a437473154f66fe010360f79f1ca5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2771/tests/capture.py b/tasks/ibhagwan__fzf-lua-2771/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2771/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2771/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a96ca186826d6fcdf2677cd8ee16156972ef99 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** fix(ui_select): restore callable opts (fix #2770) + +## Description + +@dpetka, can you test and lmk if this solves your issue? + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Updated `ui_select` to correctly handle function-based option values by resolving them with `(ui_opts, items)` before applying the options. + * Ensured registered function-based options still receive the expected arguments, preserving custom `prompt` and `kind`. + +* **Tests** + * Added a test covering function-based `ui_select` options to confirm the callback receives `(ui_opts, items)` and that item counts and fields are passed through correctly. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `237b7e7f2bd0`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2771/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2771/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..186f53cc54b7fd827864bad4bbda80123b822166 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index 3312c246..23fbf069 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -102,6 +102,15 @@ M.ui_select = function(items, ui_opts, on_choice) + + local opts = _OPTS or {} + ++ -- enables customization per kind (#755): the registered opts can be a ++ -- function that returns an opts table based on the `ui_opts` (kind, ++ -- prompt, etc.) and the `items` being selected. `config.normalize_opts` ++ -- calls function opts with no args, so resolve the function here first ++ -- to preserve the historical `opts(ui_opts, items)` signature (#2770). ++ if vim.is_callable(opts) then ++ opts = opts(ui_opts, items) ++ end ++ + opts = config.normalize_opts(opts, "ui_select") + if not opts then return end + +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +index e454f09c..96089cf0 100644 +--- a/tests/ui_select_spec.lua ++++ b/tests/ui_select_spec.lua +@@ -149,4 +149,26 @@ T["ui_select"]["abort via esc"] = function() + eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) + end + ++T["ui_select"]["registered function opts receive (ui_opts, items) #2770"] = function() ++ reload({ "default" }) ++ -- `config.normalize_opts` calls function opts with no args; the wrapper ++ -- in `M.ui_select` must resolve the function with `(ui_opts, items)` ++ -- before normalizing, preserving the documented interface (#755). ++ exec_lua([[ ++ FzfLua.register_ui_select(function(fzf_opts, items) ++ _G._ui_select_args = { ++ kind = fzf_opts.kind, ++ prompt = fzf_opts.prompt, ++ nitems = #items, ++ } ++ return {} ++ end) ++ ]]) ++ open_picker({ "alpha", "beta" }, { "preview-line-1", "preview-line-2" }, ++ { prompt = "Pick (fn):", kind = "codeaction" }) ++ close_picker("") ++ eq(child.lua_get([[_G._ui_select_args]]), ++ { kind = "codeaction", prompt = "Pick (fn):", nitems = 2 }) ++end ++ + return T diff --git a/tasks/ibhagwan__fzf-lua-2771/tests/test.sh b/tasks/ibhagwan__fzf-lua-2771/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..da270c5c031ea4d29c41fc5b053b34570e29e96d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 237b7e7f2bd07becc83144933b6058cc15bef2dc > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2771/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2771/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2771/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2772/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2772/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f97567474dfb9f9400903fd4477488b55cb96a05 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1c91f217f394b8c5c628f9e900fc52e923c850fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1c91f217f394b8c5c628f9e900fc52e923c850fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1c91f217f394b8c5c628f9e900fc52e923c850fa \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2772/instruction.md b/tasks/ibhagwan__fzf-lua-2772/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c1abc5a25e3018ac0f6780e875370ffd001acfe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: ui_select function compact + +## Description + +fix #2770 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved setup handling for UI selection behavior, ensuring configuration is applied consistently and no longer lingers after initialization. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c91f217f394`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2772/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2772/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b1ca15b909116c9d080f8627e6cb90031f272ecd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index d9f3ea52..885e35e5 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -219,14 +219,15 @@ function M.setup(opts, do_not_reset_defaults) + -- setup highlights + M.setup_highlights() + -- opt-in register ui.select via setup +- if opts.ui_select then +- if type(opts.ui_select) == "boolean" then -- back compat #2768 +- opts.ui_select = opts.ui_select and {} or nil ++ local ui_opts = opts.ui_select ++ opts.ui_select = nil -- function back compat #2770 ++ if ui_opts then ++ if type(ui_opts) == "boolean" then -- boolean back compat #2768 ++ ui_opts = ui_opts and {} or nil + vim.deprecate("ui_select = true", "ui_select = {}", "Jan 2027", "FzfLua") + end +- M.register_ui_select((type(opts.ui_select) == "table" or type(opts.ui_select) == "function") +- and opts.ui_select or nil, +- true) -- silent ++ M.register_ui_select((type(ui_opts) == "table" or type(ui_opts) == "function") ++ and ui_opts or nil, true) -- silent + end + end + diff --git a/tasks/ibhagwan__fzf-lua-2772/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2772/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2772/task.toml b/tasks/ibhagwan__fzf-lua-2772/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5ff7b6e60e65afdb07b03e06511e8d0e24fe4cb --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2772" +description = "fix: ui_select function compact" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "1c91f217f394b8c5c628f9e900fc52e923c850fa" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2772" +source_access = "auto" +built_at = "2026-11-16T16:09:55.966720+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a610edae91211a8844ce124752e9e468f91367dca31cc5a56e26861b78895db7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-05T17:00:01Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/init.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[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:01.056960+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33e82aad6b40fe28285e527369a9f06743e42b1f6d2d9f462b2d66d3b93df72d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2772/tests/capture.py b/tasks/ibhagwan__fzf-lua-2772/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2772/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2772/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c1abc5a25e3018ac0f6780e875370ffd001acfe --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: ui_select function compact + +## Description + +fix #2770 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved setup handling for UI selection behavior, ensuring configuration is applied consistently and no longer lingers after initialization. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c91f217f394`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2772/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2772/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b1ca15b909116c9d080f8627e6cb90031f272ecd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/lua/fzf-lua/init.lua b/lua/fzf-lua/init.lua +index d9f3ea52..885e35e5 100644 +--- a/lua/fzf-lua/init.lua ++++ b/lua/fzf-lua/init.lua +@@ -219,14 +219,15 @@ function M.setup(opts, do_not_reset_defaults) + -- setup highlights + M.setup_highlights() + -- opt-in register ui.select via setup +- if opts.ui_select then +- if type(opts.ui_select) == "boolean" then -- back compat #2768 +- opts.ui_select = opts.ui_select and {} or nil ++ local ui_opts = opts.ui_select ++ opts.ui_select = nil -- function back compat #2770 ++ if ui_opts then ++ if type(ui_opts) == "boolean" then -- boolean back compat #2768 ++ ui_opts = ui_opts and {} or nil + vim.deprecate("ui_select = true", "ui_select = {}", "Jan 2027", "FzfLua") + end +- M.register_ui_select((type(opts.ui_select) == "table" or type(opts.ui_select) == "function") +- and opts.ui_select or nil, +- true) -- silent ++ M.register_ui_select((type(ui_opts) == "table" or type(ui_opts) == "function") ++ and ui_opts or nil, true) -- silent + end + end + diff --git a/tasks/ibhagwan__fzf-lua-2772/tests/test.sh b/tasks/ibhagwan__fzf-lua-2772/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1015ff385eb058b80367a305ea7e5640cde044c8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1c91f217f394b8c5c628f9e900fc52e923c850fa > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2772/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2772/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2772/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2775/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2775/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a57112667e0487e4113fc03943da9822d4af271 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 774150bc05f774af1df614f55d156b3318c6decd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 774150bc05f774af1df614f55d156b3318c6decd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 774150bc05f774af1df614f55d156b3318c6decd \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2775/instruction.md b/tasks/ibhagwan__fzf-lua-2775/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebbbbf9f15f127cd6b2bc28e9c78fd5db26e169e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(lsp_code_actions): regerssion from 4a602e1 + +## Description + + + +## Summary by CodeRabbit + +* **New Features** + * Code actions now open with a dedicated preview and single-selection behavior for a smoother selection flow. + * Choosing an item in the code action picker now immediately applies the selected action. + +* **Bug Fixes** + * Removed conflicting picker settings so code action selection behaves more consistently. + * Streamlined inherited settings to reduce unexpected overrides. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `774150bc05f7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2775/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2775/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..40bef6863df5af375397aa045857647038d3185e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 714be727..324efea7 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1741,14 +1741,17 @@ M.defaults.lsp.finder = { + ---@field _ui_select? { kind: string } + ---@field _items any[] + M.defaults.lsp.code_actions = { +- async_or_timeout = 5000, +- previewer = "codeaction", + -- previewer = "codeaction_native", +- fzf_opts = { ["--no-multi"] = true }, +- -- NOTE: we don't need an action as code actions are executed by the ui.select +- -- callback but we setup an empty table to indicate to `globals.__index` that +- -- we need to inherit from the global defaults (#1232) +- actions = {}, ++ previewer = "codeaction", ++ fzf_opts = { ["--no-multi"] = true }, ++ actions = { ++ ["enter"] = { ++ fn = function(...) ++ return require("fzf-lua.providers.ui_select").accept_item(...) ++ end, ++ desc = "accept-item" ++ } ++ } + } + + ---Workspace/document diagnostics. +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index e87a0012..8b81c4f0 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -963,8 +963,6 @@ M.code_actions = function(opts) + " to hide this message or register globally using ':FzfLua register_ui_select'.") + end + +- opts.actions = opts.actions or {} +- opts.actions.enter = nil + -- only dereg if we aren't registered + if not registered then + opts.post_action_cb = function() diff --git a/tasks/ibhagwan__fzf-lua-2775/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2775/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2775/task.toml b/tasks/ibhagwan__fzf-lua-2775/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eea66325029655090529a829bbb0952b1211bb68 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2775" +description = "fix(lsp_code_actions): regerssion from 4a602e1" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "774150bc05f774af1df614f55d156b3318c6decd" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2775" +source_access = "auto" +built_at = "2026-11-16T16:09:55.949771+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1fff73a533b6c02763bcd14903d9e01f48a03461cedc982efdd8136a0abe04da" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-07T17:03:37Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/lsp.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[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:01.057464+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:567c073a4d823e9771a31f4ea9c168edaef2e4ffd47277a861038349c0bc5419" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2775/tests/capture.py b/tasks/ibhagwan__fzf-lua-2775/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2775/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2775/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebbbbf9f15f127cd6b2bc28e9c78fd5db26e169e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(lsp_code_actions): regerssion from 4a602e1 + +## Description + + + +## Summary by CodeRabbit + +* **New Features** + * Code actions now open with a dedicated preview and single-selection behavior for a smoother selection flow. + * Choosing an item in the code action picker now immediately applies the selected action. + +* **Bug Fixes** + * Removed conflicting picker settings so code action selection behaves more consistently. + * Streamlined inherited settings to reduce unexpected overrides. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `774150bc05f7`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2775/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2775/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..40bef6863df5af375397aa045857647038d3185e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 714be727..324efea7 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1741,14 +1741,17 @@ M.defaults.lsp.finder = { + ---@field _ui_select? { kind: string } + ---@field _items any[] + M.defaults.lsp.code_actions = { +- async_or_timeout = 5000, +- previewer = "codeaction", + -- previewer = "codeaction_native", +- fzf_opts = { ["--no-multi"] = true }, +- -- NOTE: we don't need an action as code actions are executed by the ui.select +- -- callback but we setup an empty table to indicate to `globals.__index` that +- -- we need to inherit from the global defaults (#1232) +- actions = {}, ++ previewer = "codeaction", ++ fzf_opts = { ["--no-multi"] = true }, ++ actions = { ++ ["enter"] = { ++ fn = function(...) ++ return require("fzf-lua.providers.ui_select").accept_item(...) ++ end, ++ desc = "accept-item" ++ } ++ } + } + + ---Workspace/document diagnostics. +diff --git a/lua/fzf-lua/providers/lsp.lua b/lua/fzf-lua/providers/lsp.lua +index e87a0012..8b81c4f0 100644 +--- a/lua/fzf-lua/providers/lsp.lua ++++ b/lua/fzf-lua/providers/lsp.lua +@@ -963,8 +963,6 @@ M.code_actions = function(opts) + " to hide this message or register globally using ':FzfLua register_ui_select'.") + end + +- opts.actions = opts.actions or {} +- opts.actions.enter = nil + -- only dereg if we aren't registered + if not registered then + opts.post_action_cb = function() diff --git a/tasks/ibhagwan__fzf-lua-2775/tests/test.sh b/tasks/ibhagwan__fzf-lua-2775/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..28ce608584440f722126fb34aad3c0b356f9759a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 774150bc05f774af1df614f55d156b3318c6decd > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2775/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2775/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2775/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2777/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2777/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..391607c038a3a15a80395f32945e575a9c686d3b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7e4fc9fe68e2656659e009001884cfb14425a88b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7e4fc9fe68e2656659e009001884cfb14425a88b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7e4fc9fe68e2656659e009001884cfb14425a88b \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2777/instruction.md b/tasks/ibhagwan__fzf-lua-2777/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f575e1c1c80040329572b69a4e94b01b51fd42 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** ci: always use latest fzf version on Linux + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * Updated the CI workflow’s Ubuntu unit-test dependency setup to download and unpack the required tooling using GitHub releases. + * Improved the automation flow by switching from a direct archive fetch to GitHub CLI–based retrieval, with the necessary token configured to support the download. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e4fc9fe68e2`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2777/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2777/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3e62b9438907b7cdf5e262daccb1df1bdf145cef --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 94d670d4..20193cb5 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -36,7 +36,8 @@ jobs: + - os: ubuntu-latest + install-deps: | + sudo apt-get update && sudo apt-get install -y ripgrep fd-find +- wget -O - https://github.com/junegunn/fzf/releases/download/v0.74.0/fzf-0.74.0-linux_amd64.tar.gz | tar zxfv - ++ gh release download -R junegunn/fzf --pattern '*-linux_amd64.tar.gz' ++ tar xvfz *.tar.gz + sudo mv ./fzf /bin + + steps: +@@ -67,6 +68,8 @@ jobs: + + - name: Install Dependencies + shell: bash ++ env: ++ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ${{ matrix.install-deps }} + fzf --version diff --git a/tasks/ibhagwan__fzf-lua-2777/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2777/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2777/task.toml b/tasks/ibhagwan__fzf-lua-2777/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c13efb50999974a8a880d4bc2ecb1719ebfe37cd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2777" +description = "ci: always use latest fzf version on Linux" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "7e4fc9fe68e2656659e009001884cfb14425a88b" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2777" +source_access = "auto" +built_at = "2026-11-16T16:09:55.951062+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2e3bb2ac258d8b885f53cd9194f431201f9d17dbd1e8f0d05bae870e10aabcf6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-08T19:38:27Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.057936+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:268b693b398dbc92a94f1103467702e1df937362ec0cc6bd29852335ae8495b2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2777/tests/capture.py b/tasks/ibhagwan__fzf-lua-2777/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2777/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2777/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4f575e1c1c80040329572b69a4e94b01b51fd42 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** ci: always use latest fzf version on Linux + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * Updated the CI workflow’s Ubuntu unit-test dependency setup to download and unpack the required tooling using GitHub releases. + * Improved the automation flow by switching from a direct archive fetch to GitHub CLI–based retrieval, with the necessary token configured to support the download. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7e4fc9fe68e2`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2777/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2777/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3e62b9438907b7cdf5e262daccb1df1bdf145cef --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 94d670d4..20193cb5 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -36,7 +36,8 @@ jobs: + - os: ubuntu-latest + install-deps: | + sudo apt-get update && sudo apt-get install -y ripgrep fd-find +- wget -O - https://github.com/junegunn/fzf/releases/download/v0.74.0/fzf-0.74.0-linux_amd64.tar.gz | tar zxfv - ++ gh release download -R junegunn/fzf --pattern '*-linux_amd64.tar.gz' ++ tar xvfz *.tar.gz + sudo mv ./fzf /bin + + steps: +@@ -67,6 +68,8 @@ jobs: + + - name: Install Dependencies + shell: bash ++ env: ++ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ${{ matrix.install-deps }} + fzf --version diff --git a/tasks/ibhagwan__fzf-lua-2777/tests/test.sh b/tasks/ibhagwan__fzf-lua-2777/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c9697277d8f2b386306004bf666c694723d3bc00 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7e4fc9fe68e2656659e009001884cfb14425a88b > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2777/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2777/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2777/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2783/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2783/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..97028a978c7eb7cc9fa8d4cab8c2842987b72de0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 233999ebe458284c79959222222f9e2dd29e509b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 233999ebe458284c79959222222f9e2dd29e509b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 233999ebe458284c79959222222f9e2dd29e509b \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2783/instruction.md b/tasks/ibhagwan__fzf-lua-2783/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5923d1103d2e83ff4d22e0f50759c355a65fc50f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** fix(btags): limit "excmd=combine" to universal ctags + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved tag searching compatibility by detecting Universal Ctags and adjusting the command options accordingly. + * Preserved correct handling of `` searches with special characters by keeping the existing escaping behavior. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `233999ebe458`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2783/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2783/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9bd4b2d06583e79ab5c55d99e7bece76d444d017 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/lua/fzf-lua/providers/tags.lua b/lua/fzf-lua/providers/tags.lua +index cccbaa34..268cba60 100644 +--- a/lua/fzf-lua/providers/tags.lua ++++ b/lua/fzf-lua/providers/tags.lua +@@ -207,7 +207,8 @@ M.btags = function(opts) + -- Used as fallback to pipe the tags into fzf from stdout + opts._btags_cmd = string.format("%s %s %s", + opts.ctags_bin or "ctags", +- opts.ctags_args or string.format("-f - %s", utils.is_darwin() and "" or "--excmd=combine"), ++ opts.ctags_args or ++ string.format("-f - %s", utils.ctags_is_universal(opts.ctags_bin) and "--excmd=combine" or ""), + libuv.shellescape(opts.filename)) + if opts.ctags_autogen then + opts.cmd = opts.cmd or opts._btags_cmd +@@ -265,7 +266,8 @@ M.grep_cWORD = function(opts) + if not opts then opts = {} end + opts.no_esc = true + -- since we're searching a tags file also search for surrounding literals ^ $ +- opts.search = [[(^|\^|\s)]] .. utils.rg_escape(vim.fn.expand("") --[[@as string]]) .. [[($|\$|\s)]] ++ opts.search = [[(^|\^|\s)]] .. ++ utils.rg_escape(vim.fn.expand("") --[[@as string]]) .. [[($|\$|\s)]] + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 54f51f67..41e866ad 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1570,6 +1570,15 @@ function M.git_version() + return tonumber(out:match("(%d+.%d+).")) + end + ++ ---@param binary string? ++ ---@return boolean? is universal ctags ++ ---@return number? version ++function M.ctags_is_universal(binary) ++ local out, rc = M.io_system({ binary or "ctags", "--version" }) ++ if rc ~= 0 then return end ++ return out:match("Universal") ~= nil, tonumber(out:match("(%d+.%d+).")) ++end ++ + function M.create_user_command_callback(provider, arg, altmap) + ---@param o vim.api.keyset.create_user_command.command_args + ---@return table diff --git a/tasks/ibhagwan__fzf-lua-2783/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2783/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2783/task.toml b/tasks/ibhagwan__fzf-lua-2783/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9685de9e9728dbefa52a8668b7574a9d02800d8c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2783" +description = "fix(btags): limit \"excmd=combine\" to universal ctags" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "233999ebe458284c79959222222f9e2dd29e509b" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2783" +source_access = "auto" +built_at = "2026-11-16T16:09:55.963933+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:660a8a2ad6bc2820bf606e6d3ac5aa948df19088ec3cde9ea99876dc38a0af95" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-22T14:46:05Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/tags.lua", + "lua/fzf-lua/utils.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[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:01.058400+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9adfb1a5ef7483f01685c1148140505e736fb72a768189ad322cc130e4d5f5fe" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2783/tests/capture.py b/tasks/ibhagwan__fzf-lua-2783/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2783/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2783/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5923d1103d2e83ff4d22e0f50759c355a65fc50f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** fix(btags): limit "excmd=combine" to universal ctags + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved tag searching compatibility by detecting Universal Ctags and adjusting the command options accordingly. + * Preserved correct handling of `` searches with special characters by keeping the existing escaping behavior. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `233999ebe458`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2783/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2783/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9bd4b2d06583e79ab5c55d99e7bece76d444d017 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/lua/fzf-lua/providers/tags.lua b/lua/fzf-lua/providers/tags.lua +index cccbaa34..268cba60 100644 +--- a/lua/fzf-lua/providers/tags.lua ++++ b/lua/fzf-lua/providers/tags.lua +@@ -207,7 +207,8 @@ M.btags = function(opts) + -- Used as fallback to pipe the tags into fzf from stdout + opts._btags_cmd = string.format("%s %s %s", + opts.ctags_bin or "ctags", +- opts.ctags_args or string.format("-f - %s", utils.is_darwin() and "" or "--excmd=combine"), ++ opts.ctags_args or ++ string.format("-f - %s", utils.ctags_is_universal(opts.ctags_bin) and "--excmd=combine" or ""), + libuv.shellescape(opts.filename)) + if opts.ctags_autogen then + opts.cmd = opts.cmd or opts._btags_cmd +@@ -265,7 +266,8 @@ M.grep_cWORD = function(opts) + if not opts then opts = {} end + opts.no_esc = true + -- since we're searching a tags file also search for surrounding literals ^ $ +- opts.search = [[(^|\^|\s)]] .. utils.rg_escape(vim.fn.expand("") --[[@as string]]) .. [[($|\$|\s)]] ++ opts.search = [[(^|\^|\s)]] .. ++ utils.rg_escape(vim.fn.expand("") --[[@as string]]) .. [[($|\$|\s)]] + return M.grep(opts) + end + +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 54f51f67..41e866ad 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -1570,6 +1570,15 @@ function M.git_version() + return tonumber(out:match("(%d+.%d+).")) + end + ++ ---@param binary string? ++ ---@return boolean? is universal ctags ++ ---@return number? version ++function M.ctags_is_universal(binary) ++ local out, rc = M.io_system({ binary or "ctags", "--version" }) ++ if rc ~= 0 then return end ++ return out:match("Universal") ~= nil, tonumber(out:match("(%d+.%d+).")) ++end ++ + function M.create_user_command_callback(provider, arg, altmap) + ---@param o vim.api.keyset.create_user_command.command_args + ---@return table diff --git a/tasks/ibhagwan__fzf-lua-2783/tests/test.sh b/tasks/ibhagwan__fzf-lua-2783/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2be88f112ad624ae7f227d517bea0b08d1f29b69 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 233999ebe458284c79959222222f9e2dd29e509b > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2783/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2783/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2783/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2784/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2784/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..07ad0f7ff5617414243a37778c948523c64df76e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a16807c8b76308ee509d1274bb796ca4fa279b49 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a16807c8b76308ee509d1274bb796ca4fa279b49 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a16807c8b76308ee509d1274bb796ca4fa279b49 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2784/instruction.md b/tasks/ibhagwan__fzf-lua-2784/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..210199a6bd7ade5041e3d436d17db76cd528ec24 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ci: fix macos-latest brew lock + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Improved the macOS automated test setup by separating package manager update and installation steps. + * No changes to product functionality or user-facing behavior. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a16807c8b763`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2784/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2784/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6c31e72e8821a698340597da20730263ae8fc67 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 20193cb5..bbfca5a6 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -27,7 +27,8 @@ jobs: + include: + - os: macos-latest + install-deps: | +- brew update && brew install fzf ripgrep fd gnu-getopt ++ brew update ++ brew install fzf ripgrep fd gnu-getopt + brew link --force gnu-getopt + - os: windows-latest + install-deps: | diff --git a/tasks/ibhagwan__fzf-lua-2784/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2784/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2784/task.toml b/tasks/ibhagwan__fzf-lua-2784/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd2f6e7dee72efb4053c914eeab704f0fbf6a66d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2784" +description = "ci: fix macos-latest brew lock" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "a16807c8b76308ee509d1274bb796ca4fa279b49" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2784" +source_access = "auto" +built_at = "2026-11-16T16:09:55.965362+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:342f2d8f0c987bbe9f9de6f504354ef64aeb7095ff6a6e2d3d9000dba4635b9e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-22T14:55:55Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.058898+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c2b385c8f1184ab38df11b14ef35065100cd833525c63438a288ffa84d15b0d8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2784/tests/capture.py b/tasks/ibhagwan__fzf-lua-2784/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2784/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2784/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..210199a6bd7ade5041e3d436d17db76cd528ec24 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ci: fix macos-latest brew lock + +## Description + + + +## Summary by CodeRabbit + +* **Chores** + * Improved the macOS automated test setup by separating package manager update and installation steps. + * No changes to product functionality or user-facing behavior. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a16807c8b763`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2784/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2784/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e6c31e72e8821a698340597da20730263ae8fc67 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 20193cb5..bbfca5a6 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -27,7 +27,8 @@ jobs: + include: + - os: macos-latest + install-deps: | +- brew update && brew install fzf ripgrep fd gnu-getopt ++ brew update ++ brew install fzf ripgrep fd gnu-getopt + brew link --force gnu-getopt + - os: windows-latest + install-deps: | diff --git a/tasks/ibhagwan__fzf-lua-2784/tests/test.sh b/tasks/ibhagwan__fzf-lua-2784/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d312a255ef828209e82561867d29d3ef98f3274e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a16807c8b76308ee509d1274bb796ca4fa279b49 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2784/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2784/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2784/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2785/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2785/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..81f76ce10b3b36cd91f36fdac1f45496d46c4e7a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 00fdbbe62420222554fce495316f2ce51c721236 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 00fdbbe62420222554fce495316f2ce51c721236 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 00fdbbe62420222554fce495316f2ce51c721236 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2785/instruction.md b/tasks/ibhagwan__fzf-lua-2785/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e878cbf6958fed6ef53ab1cd82bcc9b817220c9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** ci: fix macos-latest brew lock take 2 + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved macOS continuous integration reliability by preventing conflicts with concurrent Homebrew activity. + * CI now waits for any ongoing Homebrew process to finish before running dependency updates/installs, reducing transient pipeline failures. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `00fdbbe62420`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2785/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2785/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1e02698876ad4f69853de915f18b2a833631b554 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index bbfca5a6..83932e20 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -27,8 +27,12 @@ jobs: + include: + - os: macos-latest + install-deps: | +- brew update +- brew install fzf ripgrep fd gnu-getopt ++ # setup-vim action uses brew to install stable which may lock brew ++ while pgrep -f "[b]rew" >/dev/null; do ++ echo "Waiting for another brew process to finish..." ++ sleep 2 ++ done ++ brew update && brew install fzf ripgrep fd gnu-getopt + brew link --force gnu-getopt + - os: windows-latest + install-deps: | diff --git a/tasks/ibhagwan__fzf-lua-2785/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2785/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2785/task.toml b/tasks/ibhagwan__fzf-lua-2785/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23b5229402c30eb6db629e4174f1294f61b94c15 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2785" +description = "ci: fix macos-latest brew lock take 2" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "00fdbbe62420222554fce495316f2ce51c721236" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2785" +source_access = "auto" +built_at = "2026-11-16T16:09:55.962580+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:143dc39207b741401552b1491bd0a62263702fa35d6d37f7ada18de7ab058423" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-22T15:41:13Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[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:01.059359+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e5212d6fb37d1bcdaee06d05aae9c2671fda74ccd73471e0fec28fcf6af3275a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2785/tests/capture.py b/tasks/ibhagwan__fzf-lua-2785/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2785/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2785/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e878cbf6958fed6ef53ab1cd82bcc9b817220c9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** ci: fix macos-latest brew lock take 2 + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved macOS continuous integration reliability by preventing conflicts with concurrent Homebrew activity. + * CI now waits for any ongoing Homebrew process to finish before running dependency updates/installs, reducing transient pipeline failures. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `00fdbbe62420`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2785/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2785/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1e02698876ad4f69853de915f18b2a833631b554 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index bbfca5a6..83932e20 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -27,8 +27,12 @@ jobs: + include: + - os: macos-latest + install-deps: | +- brew update +- brew install fzf ripgrep fd gnu-getopt ++ # setup-vim action uses brew to install stable which may lock brew ++ while pgrep -f "[b]rew" >/dev/null; do ++ echo "Waiting for another brew process to finish..." ++ sleep 2 ++ done ++ brew update && brew install fzf ripgrep fd gnu-getopt + brew link --force gnu-getopt + - os: windows-latest + install-deps: | diff --git a/tasks/ibhagwan__fzf-lua-2785/tests/test.sh b/tasks/ibhagwan__fzf-lua-2785/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b82fcf949b7562eddf98445c73096242171e8e8 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 00fdbbe62420222554fce495316f2ce51c721236 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2785/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2785/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2785/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2787/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2787/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a64dd95659e34a9af5b9ac327d0d4c95f15d7a6f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin eced685813841391087fd65f896fc6ce6339a809 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eced685813841391087fd65f896fc6ce6339a809 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eced685813841391087fd65f896fc6ce6339a809 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2787/instruction.md b/tasks/ibhagwan__fzf-lua-2787/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9af3795ea32be675df20aa9c8fecd3c65bc52348 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(utils): don't corrupt UTF-8 in strip_ansi_coloring #2786 + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved removal of ANSI color sequences while preserving UTF-8 characters. + * Fixed handling of ANSI-colored paths so multibyte characters remain intact. + +* **Tests** + * Added coverage for UTF-8 text and ANSI-colored path entries. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eced68581384`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2787/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2787/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e0cc3ca88ee3b861846a9e1bd6fee41465b8d34d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 54f51f67..aaa7aa0b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -947,7 +947,7 @@ function M.strip_ansi_coloring(str) + -- NOTE: didn't work with grep's "^[[K" + -- return str:gsub("%[[%d;]-m", "") + -- https://stackoverflow.com/a/49209650/368691 +- return str:gsub("[\27\155][][()#;?%d]*[A-PRZcf-ntqry=><~]", "") ++ return str:gsub("[\27\155][%[%]][()#;?%d]*[A-PRZcf-ntqry=><~]", "") + end + + function M.ansi_escseq_len(str) +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index bfcdab65..5f413ef3 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -467,6 +467,31 @@ describe("Testing path module", function() + eq(path.entry_to_file("file:///tmp/test.txt:5:6", {}, true), r) + end) + ++ -- #2786: stripping ANSI coloring must not corrupt UTF-8 multibyte chars ++ it("strip_ansi_coloring preserves UTF-8 #2786", function() ++ -- plain ANSI SGR sequences still stripped ++ eq(utils.strip_ansi_coloring("\27[34mfoo\27[0m"), "foo") ++ eq(utils.strip_ansi_coloring("\27[1;34mfoo\27[0m"), "foo") ++ eq(utils.strip_ansi_coloring("\27[mfoo\27[0m"), "foo") ++ -- UTF-8 Polish "ści" (\xC5\x9B\x63\x69) must not have its second ++ -- byte (\x9B) eaten together with the trailing ASCII letter "c" ++ -- by an over-permissive regex ++ local sci = "\197\155" .. "ci.txt" ++ eq(utils.strip_ansi_coloring(sci), sci) ++ -- same but wrapped in SGR escape sequences (typical fzf output) ++ eq(utils.strip_ansi_coloring("\27[0m" .. sci .. "\27[0m"), sci) ++ -- other multibyte characters whose second byte overlaps the ++ -- "final byte" character class of the broken regex ++ eq(utils.strip_ansi_coloring("\195\177"), "\195\177") -- "ñ" ++ eq(utils.strip_ansi_coloring("\195\184"), "\195\184") -- "ø" ++ eq(utils.strip_ansi_coloring("\209\134" .. "x.txt"), "\209\134" .. "x.txt") -- "цx.txt" ++ -- entry_to_file must return the path with UTF-8 bytes intact ++ local p = "/tmp/" .. sci ++ eq(path.entry_to_file(p), { stripped = p, path = p, line = 0, col = 0 }) ++ local e = "\27[0m" .. p .. "\27[0m:42" ++ eq(path.entry_to_file(e), { stripped = p .. ":42", path = p, line = 42, col = 0 }) ++ end) ++ + it("parse loaded path", function() + helpers.SKIP_IF_WIN() + local win = vim.api.nvim_get_current_win() diff --git a/tasks/ibhagwan__fzf-lua-2787/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2787/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2787/task.toml b/tasks/ibhagwan__fzf-lua-2787/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd29f2cdb042537cb7e8fc9cb6d8ece3cdc7ab13 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2787" +description = "fix(utils): don't corrupt UTF-8 in strip_ansi_coloring #2786" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "eced685813841391087fd65f896fc6ce6339a809" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2787" +source_access = "auto" +built_at = "2026-11-16T16:09:55.961317+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1d1530aa9ddd8530f3dea9091e1c6d4f7c5e1de6a24b88099c77924ca890cf5c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-23T02:30:26Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/utils.lua", + "tests/path_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 27 +difficulty = "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:01.059825+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f47b7b3000f2ea09ca22d6da7495b3400d286035439be3810812928d6690817b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2787/tests/capture.py b/tasks/ibhagwan__fzf-lua-2787/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2787/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2787/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9af3795ea32be675df20aa9c8fecd3c65bc52348 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(utils): don't corrupt UTF-8 in strip_ansi_coloring #2786 + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved removal of ANSI color sequences while preserving UTF-8 characters. + * Fixed handling of ANSI-colored paths so multibyte characters remain intact. + +* **Tests** + * Added coverage for UTF-8 text and ANSI-colored path entries. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eced68581384`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2787/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2787/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e0cc3ca88ee3b861846a9e1bd6fee41465b8d34d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 54f51f67..aaa7aa0b 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -947,7 +947,7 @@ function M.strip_ansi_coloring(str) + -- NOTE: didn't work with grep's "^[[K" + -- return str:gsub("%[[%d;]-m", "") + -- https://stackoverflow.com/a/49209650/368691 +- return str:gsub("[\27\155][][()#;?%d]*[A-PRZcf-ntqry=><~]", "") ++ return str:gsub("[\27\155][%[%]][()#;?%d]*[A-PRZcf-ntqry=><~]", "") + end + + function M.ansi_escseq_len(str) +diff --git a/tests/path_spec.lua b/tests/path_spec.lua +index bfcdab65..5f413ef3 100644 +--- a/tests/path_spec.lua ++++ b/tests/path_spec.lua +@@ -467,6 +467,31 @@ describe("Testing path module", function() + eq(path.entry_to_file("file:///tmp/test.txt:5:6", {}, true), r) + end) + ++ -- #2786: stripping ANSI coloring must not corrupt UTF-8 multibyte chars ++ it("strip_ansi_coloring preserves UTF-8 #2786", function() ++ -- plain ANSI SGR sequences still stripped ++ eq(utils.strip_ansi_coloring("\27[34mfoo\27[0m"), "foo") ++ eq(utils.strip_ansi_coloring("\27[1;34mfoo\27[0m"), "foo") ++ eq(utils.strip_ansi_coloring("\27[mfoo\27[0m"), "foo") ++ -- UTF-8 Polish "ści" (\xC5\x9B\x63\x69) must not have its second ++ -- byte (\x9B) eaten together with the trailing ASCII letter "c" ++ -- by an over-permissive regex ++ local sci = "\197\155" .. "ci.txt" ++ eq(utils.strip_ansi_coloring(sci), sci) ++ -- same but wrapped in SGR escape sequences (typical fzf output) ++ eq(utils.strip_ansi_coloring("\27[0m" .. sci .. "\27[0m"), sci) ++ -- other multibyte characters whose second byte overlaps the ++ -- "final byte" character class of the broken regex ++ eq(utils.strip_ansi_coloring("\195\177"), "\195\177") -- "ñ" ++ eq(utils.strip_ansi_coloring("\195\184"), "\195\184") -- "ø" ++ eq(utils.strip_ansi_coloring("\209\134" .. "x.txt"), "\209\134" .. "x.txt") -- "цx.txt" ++ -- entry_to_file must return the path with UTF-8 bytes intact ++ local p = "/tmp/" .. sci ++ eq(path.entry_to_file(p), { stripped = p, path = p, line = 0, col = 0 }) ++ local e = "\27[0m" .. p .. "\27[0m:42" ++ eq(path.entry_to_file(e), { stripped = p .. ":42", path = p, line = 42, col = 0 }) ++ end) ++ + it("parse loaded path", function() + helpers.SKIP_IF_WIN() + local win = vim.api.nvim_get_current_win() diff --git a/tasks/ibhagwan__fzf-lua-2787/tests/test.sh b/tasks/ibhagwan__fzf-lua-2787/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ad8ca68a7b9ec8543b122cd63b3f644ebef2274 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace eced685813841391087fd65f896fc6ce6339a809 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2787/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2787/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2787/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2789/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2789/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c08bd583e36449d4324982939e6567f98195bbac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bb8f7ef06fcbf6f4b31fde344bc16f4d33c8ec7f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bb8f7ef06fcbf6f4b31fde344bc16f4d33c8ec7f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bb8f7ef06fcbf6f4b31fde344bc16f4d33c8ec7f \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2789/instruction.md b/tasks/ibhagwan__fzf-lua-2789/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cae83a3173dbb0b2381fb82fe7926fa21f0b669d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(files): opts.ignore_current_file force make_entry.file + +## Description + +Fix + + +## Summary by CodeRabbit + +* **Bug Fixes** + * File pickers now correctly apply entry processing when the option to ignore the current file is enabled. + * This improves filtering behavior and ensures the current file is excluded as expected. +* **Tests** + * Added coverage for `ignore_current_file` in the files picker (including scenarios with icons disabled). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bb8f7ef06fcb`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2789/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2789/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d7514c6271b11c2ad95fac064e82ce961aeb6cf0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/solution/patch.diff @@ -0,0 +1,76 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 0c6e9fab..548f8de1 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -964,6 +964,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + and (opts.git_icons + or opts.file_icons + or opts.file_ignore_patterns ++ or opts.ignore_current_file + or opts.strip_cwd_prefix + or opts.render_crlf + or opts.path_shorten +diff --git a/tests/files_spec.lua b/tests/files_spec.lua +index 38056613..045ca819 100644 +--- a/tests/files_spec.lua ++++ b/tests/files_spec.lua +@@ -190,6 +190,24 @@ T["files"]["preview should work after chdir #1864"] = function() + }) + end + ++T["files"]["ignore_current_file without icons #2788"] = function() ++ exec_lua([[vim.cmd.edit("LICENSE")]]) ++ helpers.FzfLua.files(child, { ++ __expect_lines = true, ++ __screen_opts = { ignore_text = { 6, 28 } }, ++ debug = 1, ++ hidden = false, ++ file_icons = false, ++ git_icons = false, ++ ignore_current_file = true, ++ previewer = false, ++ cwd_prompt = false, ++ multiprocess = true, ++ cmd = "rg --files --sort=path -g !tests/**", ++ query = "LICENSE", ++ }) ++end ++ + T["files"]["nop on nothing match"] = function() + reload({ "hide" }) + local ctx = exec_lua([[return FzfLua.utils.CTX()]]) +diff --git a/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 b/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 +new file mode 100644 +index 00000000..836e062d +--- /dev/null ++++ b/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|MIT License ++02| ++03|Copyrig╭───────────────────── Files ─────────────────────╮ ++04| │> LICENSE 0/90 (0) │ ++05|Permiss│──────────────────────────────────────────────── │n obta ++06|ining a│ │ ++07|of this│ │Softwa ++08|re"), t│ │ ++09|in the │ │itatio ++10|n the r│ │ ++11|to use,│ │se, an ++12|d/or se│ │ ++13|copies │ │Softwa ++14|re is │ │ ++15|furnish│ │ ++16| │ │ ++17|The abo│ │l be i ++18|ncluded│ │ ++19|copies │ │ ++20| │ │ ++21|THE SOF│ │KIND, ++22|EXPRESS╰─────────────────────────────────────────────────╯ ++23|IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCH@@@ ++24|LICENSE 1,1 Top ++25| ++26| ++27| ++28|-- TERMINAL -- 1,10 All diff --git a/tasks/ibhagwan__fzf-lua-2789/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2789/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2789/task.toml b/tasks/ibhagwan__fzf-lua-2789/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..620ee157d2b98a277cdc102501ac1550bb651118 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2789" +description = "fix(files): opts.ignore_current_file force make_entry.file" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "bb8f7ef06fcbf6f4b31fde344bc16f4d33c8ec7f" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2789" +source_access = "auto" +built_at = "2026-11-16T16:09:55.959983+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d7a1ae9c063d215a7f44ac2af759d3d00ad33a49e17b3bfd690844580f8830a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-23T15:20:23Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/config.lua", + "tests/files_spec.lua", + "tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 48 +difficulty = "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:01.060295+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:330ec34a011df4e4e4a1a0f49662bb06ab052be68e3a4b4213fc5da4236d8f76" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2789/tests/capture.py b/tasks/ibhagwan__fzf-lua-2789/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2789/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2789/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cae83a3173dbb0b2381fb82fe7926fa21f0b669d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(files): opts.ignore_current_file force make_entry.file + +## Description + +Fix + + +## Summary by CodeRabbit + +* **Bug Fixes** + * File pickers now correctly apply entry processing when the option to ignore the current file is enabled. + * This improves filtering behavior and ensures the current file is excluded as expected. +* **Tests** + * Added coverage for `ignore_current_file` in the files picker (including scenarios with icons disabled). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bb8f7ef06fcb`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2789/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2789/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d7514c6271b11c2ad95fac064e82ce961aeb6cf0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/tests/oracle.patch @@ -0,0 +1,76 @@ +diff --git a/lua/fzf-lua/config.lua b/lua/fzf-lua/config.lua +index 0c6e9fab..548f8de1 100644 +--- a/lua/fzf-lua/config.lua ++++ b/lua/fzf-lua/config.lua +@@ -964,6 +964,7 @@ function M.normalize_opts(opts, globals, __resume_key) ---@diagnostic disable + and (opts.git_icons + or opts.file_icons + or opts.file_ignore_patterns ++ or opts.ignore_current_file + or opts.strip_cwd_prefix + or opts.render_crlf + or opts.path_shorten +diff --git a/tests/files_spec.lua b/tests/files_spec.lua +index 38056613..045ca819 100644 +--- a/tests/files_spec.lua ++++ b/tests/files_spec.lua +@@ -190,6 +190,24 @@ T["files"]["preview should work after chdir #1864"] = function() + }) + end + ++T["files"]["ignore_current_file without icons #2788"] = function() ++ exec_lua([[vim.cmd.edit("LICENSE")]]) ++ helpers.FzfLua.files(child, { ++ __expect_lines = true, ++ __screen_opts = { ignore_text = { 6, 28 } }, ++ debug = 1, ++ hidden = false, ++ file_icons = false, ++ git_icons = false, ++ ignore_current_file = true, ++ previewer = false, ++ cwd_prompt = false, ++ multiprocess = true, ++ cmd = "rg --files --sort=path -g !tests/**", ++ query = "LICENSE", ++ }) ++end ++ + T["files"]["nop on nothing match"] = function() + reload({ "hide" }) + local ctx = exec_lua([[return FzfLua.utils.CTX()]]) +diff --git a/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 b/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 +new file mode 100644 +index 00000000..836e062d +--- /dev/null ++++ b/tests/screenshots/tests-files_spec.lua---files---ignore_current_file-without-icons-#2788 +@@ -0,0 +1,29 @@ ++--|---------|---------|---------|---------|---------|---------|---- ++01|MIT License ++02| ++03|Copyrig╭───────────────────── Files ─────────────────────╮ ++04| │> LICENSE 0/90 (0) │ ++05|Permiss│──────────────────────────────────────────────── │n obta ++06|ining a│ │ ++07|of this│ │Softwa ++08|re"), t│ │ ++09|in the │ │itatio ++10|n the r│ │ ++11|to use,│ │se, an ++12|d/or se│ │ ++13|copies │ │Softwa ++14|re is │ │ ++15|furnish│ │ ++16| │ │ ++17|The abo│ │l be i ++18|ncluded│ │ ++19|copies │ │ ++20| │ │ ++21|THE SOF│ │KIND, ++22|EXPRESS╰─────────────────────────────────────────────────╯ ++23|IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCH@@@ ++24|LICENSE 1,1 Top ++25| ++26| ++27| ++28|-- TERMINAL -- 1,10 All diff --git a/tasks/ibhagwan__fzf-lua-2789/tests/test.sh b/tasks/ibhagwan__fzf-lua-2789/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ae903a6fb0b7922cc6749d16365745956da8866 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bb8f7ef06fcbf6f4b31fde344bc16f4d33c8ec7f > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2789/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2789/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2789/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2790/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2790/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..181b8218f0d08e3b8154f82cc4cefb463fe32021 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 511651f198068ef5841ee1635ade58daa2486ef7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 511651f198068ef5841ee1635ade58daa2486ef7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 511651f198068ef5841ee1635ade58daa2486ef7 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2790/instruction.md b/tasks/ibhagwan__fzf-lua-2790/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38d2255b2ee92ac57fc0a30e7529bbb77ecf295a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(helptags): `:help help-tags` + +## Description + +Use puc lua then add an assert on coroutine.resume we can get the trace +``` +Lua callback: +providers/helptags.lua:70: providers/helptags.lua:67: bad argument #5 to +'format' (string expected, got nil) +stack traceback: + [C]: in function 'assert' + providers/helptags.lua:70: in function 'cb' + shell.lua:379: in function +``` + +https://github.com/neovim/neovim/blob/92b2a267723922a60f0716a31d06d7d36115e103/src/gen/gen_helptags.lua#L58 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved help tag navigation by falling back to Neovim’s runtime documentation path when a specific help file cannot be resolved. + * Ensured more help tags open with a valid file location. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `511651f19806`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2790/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2790/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0d887770ed4fd082616eb26c4a2199d8e16a2aa0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/providers/helptags.lua b/lua/fzf-lua/providers/helptags.lua +index 55aee2f9..894c219e 100644 +--- a/lua/fzf-lua/providers/helptags.lua ++++ b/lua/fzf-lua/providers/helptags.lua +@@ -71,6 +71,7 @@ M.helptags = function(opts) + end) + end + ++ local tagpath = vim.env.VIMRUNTIME .. "/doc/tags" + coroutine.wrap(function() + local co = coroutine.running() + ---@cast co thread +@@ -87,7 +88,7 @@ M.helptags = function(opts) + add_tag({ + tag = fields[1], + filename = fields[2], +- filepath = help_files[fields[2]], ++ filepath = help_files[fields[2]] or tagpath, + cmd = fields[3], + lang = lang, + }, cb, co) diff --git a/tasks/ibhagwan__fzf-lua-2790/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2790/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2790/task.toml b/tasks/ibhagwan__fzf-lua-2790/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..518f1864eaf1240191ab3d3e5867438ea4d5d418 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2790" +description = "fix(helptags): `:help help-tags`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "511651f198068ef5841ee1635ade58daa2486ef7" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2790" +source_access = "auto" +built_at = "2026-11-16T16:09:55.958648+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:37ad731f8c80d57d3b608427a86f3aaa4fa994fae271ea4ba92cfeb8bf2253ae" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-24T16:04:56Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/helptags.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "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:01.060775+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a00f4a76e0a5e423065e879bfac685e0b8d35be244dfc437ce667b6bd65d4906" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2790/tests/capture.py b/tasks/ibhagwan__fzf-lua-2790/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2790/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2790/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38d2255b2ee92ac57fc0a30e7529bbb77ecf295a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(helptags): `:help help-tags` + +## Description + +Use puc lua then add an assert on coroutine.resume we can get the trace +``` +Lua callback: +providers/helptags.lua:70: providers/helptags.lua:67: bad argument #5 to +'format' (string expected, got nil) +stack traceback: + [C]: in function 'assert' + providers/helptags.lua:70: in function 'cb' + shell.lua:379: in function +``` + +https://github.com/neovim/neovim/blob/92b2a267723922a60f0716a31d06d7d36115e103/src/gen/gen_helptags.lua#L58 + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved help tag navigation by falling back to Neovim’s runtime documentation path when a specific help file cannot be resolved. + * Ensured more help tags open with a valid file location. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `511651f19806`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2790/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2790/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0d887770ed4fd082616eb26c4a2199d8e16a2aa0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/lua/fzf-lua/providers/helptags.lua b/lua/fzf-lua/providers/helptags.lua +index 55aee2f9..894c219e 100644 +--- a/lua/fzf-lua/providers/helptags.lua ++++ b/lua/fzf-lua/providers/helptags.lua +@@ -71,6 +71,7 @@ M.helptags = function(opts) + end) + end + ++ local tagpath = vim.env.VIMRUNTIME .. "/doc/tags" + coroutine.wrap(function() + local co = coroutine.running() + ---@cast co thread +@@ -87,7 +88,7 @@ M.helptags = function(opts) + add_tag({ + tag = fields[1], + filename = fields[2], +- filepath = help_files[fields[2]], ++ filepath = help_files[fields[2]] or tagpath, + cmd = fields[3], + lang = lang, + }, cb, co) diff --git a/tasks/ibhagwan__fzf-lua-2790/tests/test.sh b/tasks/ibhagwan__fzf-lua-2790/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69a9fb3a6f4fddc761c80ced9872981e5e8d8b93 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 511651f198068ef5841ee1635ade58daa2486ef7 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2790/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2790/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2790/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2791/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2791/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a119938e926388f3e4661b59e314cd08d9a21a0d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9ad7340dcc6d2afc30e64fb4088597c7573ed62c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9ad7340dcc6d2afc30e64fb4088597c7573ed62c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9ad7340dcc6d2afc30e64fb4088597c7573ed62c \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2791/instruction.md b/tasks/ibhagwan__fzf-lua-2791/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0f51d8ed99b75b98c6ad27badbd98791c0f9b1bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** ci: download puc build from neovim/neovim-release + +## Description + +Wait for merge. + + + +## Summary by CodeRabbit + +* **Chores** + * Updated continuous integration configuration for clearer test-matrix exclusions. + * Refined nightly Neovim setup to use the appropriate Linux build during automated checks. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9ad7340dcc6d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2791/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2791/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..730c03710e0a84c18dae2ba8cc60b3ab6b92f17c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 83932e20..afe5c1b1 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -20,10 +20,8 @@ jobs: + os: [ubuntu-latest, macos-latest, windows-latest] + rev: [nightly, stable, puc-lua] + exclude: +- - os: macos-latest +- rev: puc-lua +- - os: windows-latest +- rev: puc-lua ++ - { os: macos-latest, rev: puc-lua } ++ - { os: windows-latest, rev: puc-lua } + include: + - os: macos-latest + install-deps: | +@@ -59,9 +57,9 @@ jobs: + - name: Install puc-lua neovim (nightly) + if: matrix.rev == 'puc-lua' + run: | +- wget -O - https://github.com/phanen/neovim-releases/releases/download/nightly/nvim-linux-x86_64.tar.gz | tar zxfv - +- sudo cp -r nvim-linux-x86_64/* /usr/local/ +- rm nvim-linux-x86_64/ -rf ++ wget -O - https://github.com/neovim/neovim-releases/releases/download/nightly/nvim-linux-x86_64-puc.tar.gz | tar zxfv - ++ sudo cp -r nvim-linux-x86_64-puc/* /usr/local/ ++ rm nvim-linux-x86_64-puc/ -rf + + - name: Install Scoop (Windows) + if: runner.os == 'Windows' diff --git a/tasks/ibhagwan__fzf-lua-2791/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2791/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2791/task.toml b/tasks/ibhagwan__fzf-lua-2791/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c3ed7e5edc01f325205d51b88282f06088d73419 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2791" +description = "ci: download puc build from neovim/neovim-release" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "9ad7340dcc6d2afc30e64fb4088597c7573ed62c" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2791" +source_access = "auto" +built_at = "2026-11-16T16:09:55.957204+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d2190c2fdf36ccaa991ad5b784a650c9ec50c6533324e911e9bc632f123b802c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-07-26T12:23:13Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ci.yaml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[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:01.061240+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9380676fd75a49bcebaa27c44f9c4037714ca89a9abbaf9a2303e597f6498fe" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2791/tests/capture.py b/tasks/ibhagwan__fzf-lua-2791/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2791/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2791/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0f51d8ed99b75b98c6ad27badbd98791c0f9b1bd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** ci: download puc build from neovim/neovim-release + +## Description + +Wait for merge. + + + +## Summary by CodeRabbit + +* **Chores** + * Updated continuous integration configuration for clearer test-matrix exclusions. + * Refined nightly Neovim setup to use the appropriate Linux build during automated checks. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9ad7340dcc6d`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2791/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2791/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..730c03710e0a84c18dae2ba8cc60b3ab6b92f17c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml +index 83932e20..afe5c1b1 100644 +--- a/.github/workflows/ci.yaml ++++ b/.github/workflows/ci.yaml +@@ -20,10 +20,8 @@ jobs: + os: [ubuntu-latest, macos-latest, windows-latest] + rev: [nightly, stable, puc-lua] + exclude: +- - os: macos-latest +- rev: puc-lua +- - os: windows-latest +- rev: puc-lua ++ - { os: macos-latest, rev: puc-lua } ++ - { os: windows-latest, rev: puc-lua } + include: + - os: macos-latest + install-deps: | +@@ -59,9 +57,9 @@ jobs: + - name: Install puc-lua neovim (nightly) + if: matrix.rev == 'puc-lua' + run: | +- wget -O - https://github.com/phanen/neovim-releases/releases/download/nightly/nvim-linux-x86_64.tar.gz | tar zxfv - +- sudo cp -r nvim-linux-x86_64/* /usr/local/ +- rm nvim-linux-x86_64/ -rf ++ wget -O - https://github.com/neovim/neovim-releases/releases/download/nightly/nvim-linux-x86_64-puc.tar.gz | tar zxfv - ++ sudo cp -r nvim-linux-x86_64-puc/* /usr/local/ ++ rm nvim-linux-x86_64-puc/ -rf + + - name: Install Scoop (Windows) + if: runner.os == 'Windows' diff --git a/tasks/ibhagwan__fzf-lua-2791/tests/test.sh b/tasks/ibhagwan__fzf-lua-2791/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..acaa903fa673c10f1d68467a960dd089297f0b7c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9ad7340dcc6d2afc30e64fb4088597c7573ed62c > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2791/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2791/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2791/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2796/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2796/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f654364685e6c8c04e8ebd814ff0cd792e3db6a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d0355a7f30bc0f7a81223ad2d88a019edd91f768 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d0355a7f30bc0f7a81223ad2d88a019edd91f768 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d0355a7f30bc0f7a81223ad2d88a019edd91f768 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2796/instruction.md b/tasks/ibhagwan__fzf-lua-2796/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09874a13e39ea980d18dd81c44f408300b012f38 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** ci: VIMRUNTIME when built from source + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved test environment setup by automatically detecting the Neovim runtime location. + * Added a fallback runtime path when detection is unavailable or invalid. + * Ensured tests consistently use the resolved runtime configuration across supported Neovim executables. + +* **Documentation** + * Clarified which test commands are available for stable and nightly environments. + * Distinguished commands intended for stable releases from those requiring nightly builds. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0355a7f30bc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2796/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2796/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..97f787cdf2b069466fd6952459333eda9ee8b54f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/Makefile b/Makefile +index 165e3615..cd22d2cb 100644 +--- a/Makefile ++++ b/Makefile +@@ -3,8 +3,11 @@ nvim ?= nvim + # + # Run all tests or specic module tests + # +-# Test both stable and nightly (assuming `nv` is linked to nightly): +-# `make test nvim=nv` or `make test nvim="nvim nv"` (for both) ++# Test nightly: ++# `make test nvim=/home/bhagwan/Sources/nvim/neovim/build/bin/nvim ++# ++# Test both stable and nightly: ++# `make test nvim="nvim /home/bhagwan/Sources/nvim/neovim/build/bin/nvim"` + # + # Test specific module(s) with `make test glob=file` + # NOTE: glob is resolved using `vim.fn.globpath` so we can also run: +@@ -15,7 +18,13 @@ test: + for nvim_exec in $(nvim); do \ + printf "\n======\n\n" ; \ + $$nvim_exec --version | head -n 1 && echo '' ; \ +- $$nvim_exec --headless --noplugin -u ./scripts/minimal_init.lua \ ++ VIMRUNTIME="$$($$nvim_exec --clean --headless +'echo $$VIMRUNTIME' +q 2>/dev/null)" ; \ ++ if [ -z "$$VIMRUNTIME" ] || [ ! -d "$$VIMRUNTIME" ]; then \ ++ VIMRUNTIME="$$(realpath "$$(dirname "$$nvim_exec")/../../runtime")" ; \ ++ [ -d "$$VIMRUNTIME" ] || unset VIMRUNTIME ; \ ++ fi ; \ ++ VIMRUNTIME="$$VIMRUNTIME" FZF_LUA_NVIM_RUNTIME="$$VIMRUNTIME" \ ++ $$nvim_exec --headless --noplugin -u ./scripts/minimal_init.lua \ + -l ./scripts/make_cli.lua ; \ + done + diff --git a/tasks/ibhagwan__fzf-lua-2796/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2796/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2796/task.toml b/tasks/ibhagwan__fzf-lua-2796/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f7761955830871f031448110930e4834f49b8cf --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2796" +description = "ci: VIMRUNTIME when built from source" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "d0355a7f30bc0f7a81223ad2d88a019edd91f768" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2796" +source_access = "auto" +built_at = "2026-11-16T16:09:55.954555+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3d20e0d50f076866f7c12404a276b9bd3a88cdd2cf30830f2729bf068319173b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-05T23:40:30Z" +diff_format = "unified" +context_files = [ + "Makefile", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[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:01.061702+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ee46760cc06fb8a25f48877a09f47e6ea7fe7c6e9710406649a25f83408246b4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2796/tests/capture.py b/tasks/ibhagwan__fzf-lua-2796/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2796/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2796/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09874a13e39ea980d18dd81c44f408300b012f38 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** ci: VIMRUNTIME when built from source + +## Description + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved test environment setup by automatically detecting the Neovim runtime location. + * Added a fallback runtime path when detection is unavailable or invalid. + * Ensured tests consistently use the resolved runtime configuration across supported Neovim executables. + +* **Documentation** + * Clarified which test commands are available for stable and nightly environments. + * Distinguished commands intended for stable releases from those requiring nightly builds. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d0355a7f30bc`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2796/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2796/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..97f787cdf2b069466fd6952459333eda9ee8b54f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/Makefile b/Makefile +index 165e3615..cd22d2cb 100644 +--- a/Makefile ++++ b/Makefile +@@ -3,8 +3,11 @@ nvim ?= nvim + # + # Run all tests or specic module tests + # +-# Test both stable and nightly (assuming `nv` is linked to nightly): +-# `make test nvim=nv` or `make test nvim="nvim nv"` (for both) ++# Test nightly: ++# `make test nvim=/home/bhagwan/Sources/nvim/neovim/build/bin/nvim ++# ++# Test both stable and nightly: ++# `make test nvim="nvim /home/bhagwan/Sources/nvim/neovim/build/bin/nvim"` + # + # Test specific module(s) with `make test glob=file` + # NOTE: glob is resolved using `vim.fn.globpath` so we can also run: +@@ -15,7 +18,13 @@ test: + for nvim_exec in $(nvim); do \ + printf "\n======\n\n" ; \ + $$nvim_exec --version | head -n 1 && echo '' ; \ +- $$nvim_exec --headless --noplugin -u ./scripts/minimal_init.lua \ ++ VIMRUNTIME="$$($$nvim_exec --clean --headless +'echo $$VIMRUNTIME' +q 2>/dev/null)" ; \ ++ if [ -z "$$VIMRUNTIME" ] || [ ! -d "$$VIMRUNTIME" ]; then \ ++ VIMRUNTIME="$$(realpath "$$(dirname "$$nvim_exec")/../../runtime")" ; \ ++ [ -d "$$VIMRUNTIME" ] || unset VIMRUNTIME ; \ ++ fi ; \ ++ VIMRUNTIME="$$VIMRUNTIME" FZF_LUA_NVIM_RUNTIME="$$VIMRUNTIME" \ ++ $$nvim_exec --headless --noplugin -u ./scripts/minimal_init.lua \ + -l ./scripts/make_cli.lua ; \ + done + diff --git a/tasks/ibhagwan__fzf-lua-2796/tests/test.sh b/tasks/ibhagwan__fzf-lua-2796/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..812eed24e57a1a96cb6e7ee452ad7fa07a58df17 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d0355a7f30bc0f7a81223ad2d88a019edd91f768 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2796/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2796/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2796/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2798/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2798/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d450af45fd3e65feba713440e4dfe580501814c4 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8671012a7b2a1648595952c655039d51fb301c14 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8671012a7b2a1648595952c655039d51fb301c14 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8671012a7b2a1648595952c655039d51fb301c14 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2798/instruction.md b/tasks/ibhagwan__fzf-lua-2798/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c352c88e8c123e3c69ddaafec9d19e2fb0783d2a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** fix(ui_select): merge _OPTS_ONCE before normalize_opts (fix #2795) + +## Description + +Regression from 4a602e1d ("fix(ui_select): add native preview for fzf-native/fzf-tmux"): `M.ui_select` started normalizing the registered opts via `config.normalize_opts(opts, "ui_select")` while the `_OPTS_ONCE` merge (sent from `lsp_code_actions`) still happened afterwards, inside an `elseif` branch of the `ui_opts.preview_item` check. + +This caused two breakages with `FzfLua.lsp_code_actions({no_resume=true})`: + +1. `no_resume` was invisible to the "hide" profile's `enrich` (which runs during `normalize_opts` and skips only when `opts.no_resume` or `opts.no_hide` are set). Esc (and every other non-reuse action) got wrapped with `fzf.hide()`, so the picker window hid instead of closing and `resume` brought back a picker the user explicitly asked not to resume. + +2. On Neovim >= 0.12 `vim.lsp.buf.code_action` passes `preview_item` to `vim.ui.select`, taking the `if ui_opts.preview_item` branch, which skipped the `elseif _OPTS_ONCE` merge entirely and silently dropped the once-opts (`no_resume`, etc.) on the floor. + +Fix: + +- Move the `_OPTS_ONCE` resolution/merge (including the auto-detected `kind == "codeaction"` path and the non-codeaction fallback deregister) above `config.normalize_opts`, so merged values such as `no_resume` are visible to profile `enrich` functions. + +- The merge now runs regardless of `ui_opts.preview_item`, so once-opts apply to both the native and buffer preview variants. + +- Limit the "disable hide profile" default (`no_hide`, #2439) to `ui_opts.kind == "codeaction"` and set it before `normalize_opts` (post-merge) so the hide `enrich` actually sees it, while an explicit `no_hide = false` from `lsp_code_actions` opts is still respected. Non-codeaction `vim.ui.select` kinds are no longer forced to `no_hide`, i.e. they can be hidden/resumed with the "hide" profile like any other picker. + +Verified with the default profile (includes "hide"): +- `lsp_code_actions({no_resume=true})`: esc/enter close the window, `FzfLua resume` reports "No resume data available." +- `lsp_code_actions()` without `no_resume` behaves as before. +- Normal `vim.ui.select` (non-codeaction) still hides on esc and resumes via unhide; selecting an item still calls `on_choice`. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved LSP code-action selection when one-time UI options are provided. + * Preserved previewer and visibility settings during selection. + * Prevented unintended hiding or resuming after choosing code actions. + * Ensured Enter consistently performs the expected selection action. + +* **Tests** + * Added regression coverage for code-action selections with and without preview items. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8671012a7b2a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2798/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2798/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..37668310fde15a1f635772d12d6710815d581952 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/solution/patch.diff @@ -0,0 +1,257 @@ +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index be2f7b92..996b8f1f 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -112,6 +112,66 @@ M.ui_select = function(items, ui_opts, on_choice) + opts = opts(ui_opts, items) + end + ++ -- ui.select is code actions ++ -- inherit from defaults if not triggered by lsp_code_actions ++ ---@type 'error'|'keep'|'force' ++ local opts_merge_strategy = "keep" ++ ++ -- fix error when vim.lsp.buf.code_action() called but didn't triggers vim.ui.select ++ -- _OPTS_ONCE also means pending deregister ++ -- since we only use it to custom codeaction preview now ++ if _OPTS_ONCE and ui_opts.kind ~= "codeaction" then ++ M.deregister({}, true, true) ++ _OPTS_ONCE = nil ++ return vim.ui.select(items, ui_opts, on_choice) ++ end ++ ++ if not _OPTS_ONCE and ui_opts.kind == "codeaction" then ++ ---@type fzf-lua.config.LspCodeActions ++ _OPTS_ONCE = config.normalize_opts({}, "lsp.code_actions") ++ if not _OPTS_ONCE then return end ++ -- auto-detected code actions, prioritize the ui_select ++ -- options over `lsp.code_actions` (#999) ++ opts_merge_strategy = "force" ++ end ++ ++ if _OPTS_ONCE then ++ -- merge and clear the once opts sent from lsp_code_actions **before** ++ -- normalize so the merge result (e.g. `no_resume`) is visible to the ++ -- profile enrich functions (e.g. "hide" profile skips when ++ -- `no_resume|no_hide` are set) (#2795) ++ local opts_once = _OPTS_ONCE ++ local previewer = opts_once.previewer ++ opts_once.previewer = nil -- can't copy the previewer object ++ ---@diagnostic disable-next-line: param-type-mismatch ++ ---@diagnostic disable-next-line: assign-type-mismatch ++ ---@diagnostic disable-next-line: generic-constraint-mismatch ++ opts = vim.tbl_deep_extend(opts_merge_strategy, opts_once, opts) ++ ---@cast opts table ++ -- We also override actions to guarantee a single default ++ -- action, otherwise selected[1] will be empty due to ++ -- multiple keybinds trigger, sending `--expect` to fzf ++ opts.actions = vim.tbl_deep_extend("force", opts.actions or {}, ++ { ["enter"] = opts.actions and opts.actions.enter or nil }) ++ opts.previewer = previewer ++ -- Callback to set the coroutine so we know if the interface ++ -- was opened or not (e.g. when no code actions are present) ++ opts.cb_co = function(co) ++ ---@diagnostic disable-next-line: inject-field ++ opts_once._co = co ++ end ++ _OPTS_ONCE = nil ++ end ++ ++ -- disable hide profile unless specifically requested, must be set ++ -- prior to `normalize_opts` as the "hide" profile's `enrich` needs ++ -- this to skip setting `` to hide (post-merge so that an ++ -- explicit `no_hide=false` sent via `_OPTS_ONCE` is respected) ++ if ui_opts.kind == "codeaction" then ++ -- casues issues with abort as on_choice(nil) won't be called (#2439) ++ opts.no_hide = opts.no_hide == nil and true or opts.no_hide ++ end ++ + opts = config.normalize_opts(opts, "ui_select") + if not opts then return end + +@@ -170,29 +230,6 @@ M.ui_select = function(items, ui_opts, on_choice) + end) + + +- -- ui.select is code actions +- -- inherit from defaults if not triggered by lsp_code_actions +- ---@type 'error'|'keep'|'force' +- local opts_merge_strategy = "keep" +- +- -- fix error when vim.lsp.buf.code_action() called but didn't triggers vim.ui.select +- -- _OPTS_ONCE also means pending deregister +- -- since we only use it to custom codeaction preview now +- if _OPTS_ONCE and ui_opts.kind ~= "codeaction" then +- M.deregister({}, true, true) +- _OPTS_ONCE = nil +- return vim.ui.select(items, ui_opts, on_choice) +- end +- +- if not _OPTS_ONCE and ui_opts.kind == "codeaction" then +- ---@type fzf-lua.config.LspCodeActions +- _OPTS_ONCE = config.normalize_opts({}, "lsp.code_actions") +- if not _OPTS_ONCE then return end +- -- auto-detected code actions, prioritize the ui_select +- -- options over `lsp.code_actions` (#999) +- opts_merge_strategy = "force" +- end +- + if ui_opts.preview_item then + local preview_type = resolve_preview_type(ui_opts, opts) + if preview_type == "native" then +@@ -266,36 +303,8 @@ M.ui_select = function(items, ui_opts, on_choice) + end, + } + end +- elseif _OPTS_ONCE then +- -- merge and clear the once opts sent from lsp_code_actions. +- -- We also override actions to guarantee a single default +- -- action, otherwise selected[1] will be empty due to +- -- multiple keybinds trigger, sending `--expect` to fzf +- local previewer = _OPTS_ONCE.previewer +- _OPTS_ONCE.previewer = nil -- can't copy the previewer object +- ---@diagnostic disable-next-line: param-type-mismatch +- ---@diagnostic disable-next-line: assign-type-mismatch +- ---@diagnostic disable-next-line: generic-constraint-mismatch +- opts = vim.tbl_deep_extend(opts_merge_strategy, _OPTS_ONCE, opts) +- ---@cast opts table +- opts.actions = vim.tbl_deep_extend("force", opts.actions or {}, +- { ["enter"] = opts.actions.enter }) +- opts.previewer = previewer +- -- Callback to set the coroutine so we know if the interface +- -- was opened or not (e.g. when no code actions are present) +- opts.cb_co = (function() +- -- NOTE: use clojure as `_OPTS_ONCE` is otherwise nullified +- local opts_once_ref = _OPTS_ONCE +- ---@diagnostic disable-next-line: inject-field +- return function(co) opts_once_ref._co = co end +- end)() +- _OPTS_ONCE = nil + end + +- -- disable hide profile unless specifically requested +- -- casues issues with abort as on_choice(nil) won't be called (#2439) +- opts.no_hide = opts.no_hide == nil and true or opts.no_hide +- + core.fzf_exec(entries, opts) + end + +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +index 659cbfa0..c6b9792d 100644 +--- a/tests/ui_select_spec.lua ++++ b/tests/ui_select_spec.lua +@@ -150,6 +150,114 @@ T["ui_select"]["abort via esc"] = function() + eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) + end + ++-- #2795: opts sent once from `lsp_code_actions` (`_OPTS_ONCE`) must be ++-- merged into the picker opts *before* `config.normalize_opts` runs so ++-- that the "hide" profile's `enrich` sees `no_resume`/`no_hide` and does ++-- not set `` (and all other actions) to hide instead of close. ++T["ui_select"]["lsp_code_actions no_resume honored #2795"] = function() ++ -- "default" profile includes "hide" ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ -- emulate `FzfLua.lsp_code_actions({ no_resume = true })` sending ++ -- "once" opts to ui_select (normalized, as done by `normalize_lsp_opts`) ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_resume = true, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ -- capture the final opts passed to `fzf_exec` ++ local core = require("fzf-lua.core") ++ local orig_fzf_exec = core.fzf_exec ++ core.fzf_exec = function(contents, opts) ++ ---@cast opts table ++ _G._fzf_exec_opts = { ++ no_resume = opts.no_resume, ++ no_hide = opts.no_hide, ++ esc_action_type = type(vim.tbl_get(opts, "actions", "esc")), ++ } ++ return orig_fzf_exec(contents, opts) ++ end ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ local captured = child.lua_get([[_G._fzf_exec_opts]]) ++ eq(captured.no_resume, true) ++ eq(captured.no_hide, true) ++ -- "hide" profile must not have enriched the esc action ++ eq(captured.esc_action_type, "nil") ++ close_picker("") ++ -- picker must not have been stored as resume data ++ eq(child.lua_get( ++ [[(require("fzf-lua.config").__resume_data or {}).contents]]), vim.NIL) ++ -- explicit `no_hide = false` sent via once-opts must be respected ++ -- (not replaced by the implicit code-action `no_hide = true` default) ++ exec_lua(function() ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_hide = false, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_exec_opts.no_hide]]), false) ++ close_picker("") ++end ++ ++T["ui_select"]["once opts merged with preview_item #2795"] = function() ++ -- "default" profile includes "hide" ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_resume = true, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ local core = require("fzf-lua.core") ++ local orig_fzf_exec = core.fzf_exec ++ core.fzf_exec = function(contents, opts) ++ ---@cast opts table ++ _G._fzf_exec_opts = { ++ no_resume = opts.no_resume, ++ no_hide = opts.no_hide, ++ esc_action_type = type(vim.tbl_get(opts, "actions", "esc")), ++ } ++ return orig_fzf_exec(contents, opts) ++ end ++ -- nvim >= 0.12 code_action sends `preview_item` which used to skip ++ -- the `_OPTS_ONCE` merge entirely (`elseif`), dropping `no_resume` ++ local buf = vim.api.nvim_create_buf(false, true) ++ vim.api.nvim_buf_set_lines(buf, 0, -1, false, { "preview" }) ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ preview_item = function(_) return { buf = buf } end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ local captured = child.lua_get([[_G._fzf_exec_opts]]) ++ eq(captured.no_resume, true) ++ eq(captured.no_hide, true) ++ eq(captured.esc_action_type, "nil") ++ close_picker("") ++ eq(child.lua_get( ++ [[(require("fzf-lua.config").__resume_data or {}).contents]]), vim.NIL) ++end ++ + T["ui_select"]["registered function opts receive (ui_opts, items) #2770"] = function() + reload({ "default" }) + -- `config.normalize_opts` calls function opts with no args; the wrapper diff --git a/tasks/ibhagwan__fzf-lua-2798/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2798/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2798/task.toml b/tasks/ibhagwan__fzf-lua-2798/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e2951e95171857aa06e6f4f4e5d2165da74937c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2798" +description = "fix(ui_select): merge _OPTS_ONCE before normalize_opts (fix #2795)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "8671012a7b2a1648595952c655039d51fb301c14" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2798" +source_access = "auto" +built_at = "2026-11-16T16:09:55.952766+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5b76ef48784145f527d7e8e53b61ac8aaad29ca7cf8d0cd83a91535d64d5b971" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-13T03:35:04Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/providers/ui_select.lua", + "tests/ui_select_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 219 +difficulty = "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:01.062169+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e4ae13181c2aff06b84ef308176aca2fe3b256ecdec180115822b057ee2eaefe" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2798/tests/capture.py b/tasks/ibhagwan__fzf-lua-2798/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2798/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2798/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c352c88e8c123e3c69ddaafec9d19e2fb0783d2a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** fix(ui_select): merge _OPTS_ONCE before normalize_opts (fix #2795) + +## Description + +Regression from 4a602e1d ("fix(ui_select): add native preview for fzf-native/fzf-tmux"): `M.ui_select` started normalizing the registered opts via `config.normalize_opts(opts, "ui_select")` while the `_OPTS_ONCE` merge (sent from `lsp_code_actions`) still happened afterwards, inside an `elseif` branch of the `ui_opts.preview_item` check. + +This caused two breakages with `FzfLua.lsp_code_actions({no_resume=true})`: + +1. `no_resume` was invisible to the "hide" profile's `enrich` (which runs during `normalize_opts` and skips only when `opts.no_resume` or `opts.no_hide` are set). Esc (and every other non-reuse action) got wrapped with `fzf.hide()`, so the picker window hid instead of closing and `resume` brought back a picker the user explicitly asked not to resume. + +2. On Neovim >= 0.12 `vim.lsp.buf.code_action` passes `preview_item` to `vim.ui.select`, taking the `if ui_opts.preview_item` branch, which skipped the `elseif _OPTS_ONCE` merge entirely and silently dropped the once-opts (`no_resume`, etc.) on the floor. + +Fix: + +- Move the `_OPTS_ONCE` resolution/merge (including the auto-detected `kind == "codeaction"` path and the non-codeaction fallback deregister) above `config.normalize_opts`, so merged values such as `no_resume` are visible to profile `enrich` functions. + +- The merge now runs regardless of `ui_opts.preview_item`, so once-opts apply to both the native and buffer preview variants. + +- Limit the "disable hide profile" default (`no_hide`, #2439) to `ui_opts.kind == "codeaction"` and set it before `normalize_opts` (post-merge) so the hide `enrich` actually sees it, while an explicit `no_hide = false` from `lsp_code_actions` opts is still respected. Non-codeaction `vim.ui.select` kinds are no longer forced to `no_hide`, i.e. they can be hidden/resumed with the "hide" profile like any other picker. + +Verified with the default profile (includes "hide"): +- `lsp_code_actions({no_resume=true})`: esc/enter close the window, `FzfLua resume` reports "No resume data available." +- `lsp_code_actions()` without `no_resume` behaves as before. +- Normal `vim.ui.select` (non-codeaction) still hides on esc and resumes via unhide; selecting an item still calls `on_choice`. + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved LSP code-action selection when one-time UI options are provided. + * Preserved previewer and visibility settings during selection. + * Prevented unintended hiding or resuming after choosing code actions. + * Ensured Enter consistently performs the expected selection action. + +* **Tests** + * Added regression coverage for code-action selections with and without preview items. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8671012a7b2a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2798/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2798/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..37668310fde15a1f635772d12d6710815d581952 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/tests/oracle.patch @@ -0,0 +1,257 @@ +diff --git a/lua/fzf-lua/providers/ui_select.lua b/lua/fzf-lua/providers/ui_select.lua +index be2f7b92..996b8f1f 100644 +--- a/lua/fzf-lua/providers/ui_select.lua ++++ b/lua/fzf-lua/providers/ui_select.lua +@@ -112,6 +112,66 @@ M.ui_select = function(items, ui_opts, on_choice) + opts = opts(ui_opts, items) + end + ++ -- ui.select is code actions ++ -- inherit from defaults if not triggered by lsp_code_actions ++ ---@type 'error'|'keep'|'force' ++ local opts_merge_strategy = "keep" ++ ++ -- fix error when vim.lsp.buf.code_action() called but didn't triggers vim.ui.select ++ -- _OPTS_ONCE also means pending deregister ++ -- since we only use it to custom codeaction preview now ++ if _OPTS_ONCE and ui_opts.kind ~= "codeaction" then ++ M.deregister({}, true, true) ++ _OPTS_ONCE = nil ++ return vim.ui.select(items, ui_opts, on_choice) ++ end ++ ++ if not _OPTS_ONCE and ui_opts.kind == "codeaction" then ++ ---@type fzf-lua.config.LspCodeActions ++ _OPTS_ONCE = config.normalize_opts({}, "lsp.code_actions") ++ if not _OPTS_ONCE then return end ++ -- auto-detected code actions, prioritize the ui_select ++ -- options over `lsp.code_actions` (#999) ++ opts_merge_strategy = "force" ++ end ++ ++ if _OPTS_ONCE then ++ -- merge and clear the once opts sent from lsp_code_actions **before** ++ -- normalize so the merge result (e.g. `no_resume`) is visible to the ++ -- profile enrich functions (e.g. "hide" profile skips when ++ -- `no_resume|no_hide` are set) (#2795) ++ local opts_once = _OPTS_ONCE ++ local previewer = opts_once.previewer ++ opts_once.previewer = nil -- can't copy the previewer object ++ ---@diagnostic disable-next-line: param-type-mismatch ++ ---@diagnostic disable-next-line: assign-type-mismatch ++ ---@diagnostic disable-next-line: generic-constraint-mismatch ++ opts = vim.tbl_deep_extend(opts_merge_strategy, opts_once, opts) ++ ---@cast opts table ++ -- We also override actions to guarantee a single default ++ -- action, otherwise selected[1] will be empty due to ++ -- multiple keybinds trigger, sending `--expect` to fzf ++ opts.actions = vim.tbl_deep_extend("force", opts.actions or {}, ++ { ["enter"] = opts.actions and opts.actions.enter or nil }) ++ opts.previewer = previewer ++ -- Callback to set the coroutine so we know if the interface ++ -- was opened or not (e.g. when no code actions are present) ++ opts.cb_co = function(co) ++ ---@diagnostic disable-next-line: inject-field ++ opts_once._co = co ++ end ++ _OPTS_ONCE = nil ++ end ++ ++ -- disable hide profile unless specifically requested, must be set ++ -- prior to `normalize_opts` as the "hide" profile's `enrich` needs ++ -- this to skip setting `` to hide (post-merge so that an ++ -- explicit `no_hide=false` sent via `_OPTS_ONCE` is respected) ++ if ui_opts.kind == "codeaction" then ++ -- casues issues with abort as on_choice(nil) won't be called (#2439) ++ opts.no_hide = opts.no_hide == nil and true or opts.no_hide ++ end ++ + opts = config.normalize_opts(opts, "ui_select") + if not opts then return end + +@@ -170,29 +230,6 @@ M.ui_select = function(items, ui_opts, on_choice) + end) + + +- -- ui.select is code actions +- -- inherit from defaults if not triggered by lsp_code_actions +- ---@type 'error'|'keep'|'force' +- local opts_merge_strategy = "keep" +- +- -- fix error when vim.lsp.buf.code_action() called but didn't triggers vim.ui.select +- -- _OPTS_ONCE also means pending deregister +- -- since we only use it to custom codeaction preview now +- if _OPTS_ONCE and ui_opts.kind ~= "codeaction" then +- M.deregister({}, true, true) +- _OPTS_ONCE = nil +- return vim.ui.select(items, ui_opts, on_choice) +- end +- +- if not _OPTS_ONCE and ui_opts.kind == "codeaction" then +- ---@type fzf-lua.config.LspCodeActions +- _OPTS_ONCE = config.normalize_opts({}, "lsp.code_actions") +- if not _OPTS_ONCE then return end +- -- auto-detected code actions, prioritize the ui_select +- -- options over `lsp.code_actions` (#999) +- opts_merge_strategy = "force" +- end +- + if ui_opts.preview_item then + local preview_type = resolve_preview_type(ui_opts, opts) + if preview_type == "native" then +@@ -266,36 +303,8 @@ M.ui_select = function(items, ui_opts, on_choice) + end, + } + end +- elseif _OPTS_ONCE then +- -- merge and clear the once opts sent from lsp_code_actions. +- -- We also override actions to guarantee a single default +- -- action, otherwise selected[1] will be empty due to +- -- multiple keybinds trigger, sending `--expect` to fzf +- local previewer = _OPTS_ONCE.previewer +- _OPTS_ONCE.previewer = nil -- can't copy the previewer object +- ---@diagnostic disable-next-line: param-type-mismatch +- ---@diagnostic disable-next-line: assign-type-mismatch +- ---@diagnostic disable-next-line: generic-constraint-mismatch +- opts = vim.tbl_deep_extend(opts_merge_strategy, _OPTS_ONCE, opts) +- ---@cast opts table +- opts.actions = vim.tbl_deep_extend("force", opts.actions or {}, +- { ["enter"] = opts.actions.enter }) +- opts.previewer = previewer +- -- Callback to set the coroutine so we know if the interface +- -- was opened or not (e.g. when no code actions are present) +- opts.cb_co = (function() +- -- NOTE: use clojure as `_OPTS_ONCE` is otherwise nullified +- local opts_once_ref = _OPTS_ONCE +- ---@diagnostic disable-next-line: inject-field +- return function(co) opts_once_ref._co = co end +- end)() +- _OPTS_ONCE = nil + end + +- -- disable hide profile unless specifically requested +- -- casues issues with abort as on_choice(nil) won't be called (#2439) +- opts.no_hide = opts.no_hide == nil and true or opts.no_hide +- + core.fzf_exec(entries, opts) + end + +diff --git a/tests/ui_select_spec.lua b/tests/ui_select_spec.lua +index 659cbfa0..c6b9792d 100644 +--- a/tests/ui_select_spec.lua ++++ b/tests/ui_select_spec.lua +@@ -150,6 +150,114 @@ T["ui_select"]["abort via esc"] = function() + eq(child.lua_get([[_G._ui_select_choice]]), vim.NIL) + end + ++-- #2795: opts sent once from `lsp_code_actions` (`_OPTS_ONCE`) must be ++-- merged into the picker opts *before* `config.normalize_opts` runs so ++-- that the "hide" profile's `enrich` sees `no_resume`/`no_hide` and does ++-- not set `` (and all other actions) to hide instead of close. ++T["ui_select"]["lsp_code_actions no_resume honored #2795"] = function() ++ -- "default" profile includes "hide" ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ -- emulate `FzfLua.lsp_code_actions({ no_resume = true })` sending ++ -- "once" opts to ui_select (normalized, as done by `normalize_lsp_opts`) ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_resume = true, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ -- capture the final opts passed to `fzf_exec` ++ local core = require("fzf-lua.core") ++ local orig_fzf_exec = core.fzf_exec ++ core.fzf_exec = function(contents, opts) ++ ---@cast opts table ++ _G._fzf_exec_opts = { ++ no_resume = opts.no_resume, ++ no_hide = opts.no_hide, ++ esc_action_type = type(vim.tbl_get(opts, "actions", "esc")), ++ } ++ return orig_fzf_exec(contents, opts) ++ end ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ local captured = child.lua_get([[_G._fzf_exec_opts]]) ++ eq(captured.no_resume, true) ++ eq(captured.no_hide, true) ++ -- "hide" profile must not have enriched the esc action ++ eq(captured.esc_action_type, "nil") ++ close_picker("") ++ -- picker must not have been stored as resume data ++ eq(child.lua_get( ++ [[(require("fzf-lua.config").__resume_data or {}).contents]]), vim.NIL) ++ -- explicit `no_hide = false` sent via once-opts must be respected ++ -- (not replaced by the implicit code-action `no_hide = true` default) ++ exec_lua(function() ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_hide = false, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ eq(child.lua_get([[_G._fzf_exec_opts.no_hide]]), false) ++ close_picker("") ++end ++ ++T["ui_select"]["once opts merged with preview_item #2795"] = function() ++ -- "default" profile includes "hide" ++ reload({ "default" }) ++ register() ++ exec_lua(function() ++ local ui_select = require("fzf-lua.providers.ui_select") ++ local opts_once = require("fzf-lua.config").normalize_opts( ++ { no_resume = true, previewer = false }, "lsp.code_actions") ++ ui_select.register(nil, true, opts_once) ++ local core = require("fzf-lua.core") ++ local orig_fzf_exec = core.fzf_exec ++ core.fzf_exec = function(contents, opts) ++ ---@cast opts table ++ _G._fzf_exec_opts = { ++ no_resume = opts.no_resume, ++ no_hide = opts.no_hide, ++ esc_action_type = type(vim.tbl_get(opts, "actions", "esc")), ++ } ++ return orig_fzf_exec(contents, opts) ++ end ++ -- nvim >= 0.12 code_action sends `preview_item` which used to skip ++ -- the `_OPTS_ONCE` merge entirely (`elseif`), dropping `no_resume` ++ local buf = vim.api.nvim_create_buf(false, true) ++ vim.api.nvim_buf_set_lines(buf, 0, -1, false, { "preview" }) ++ vim.ui.select({ "alpha", "beta" }, { ++ prompt = "Code actions:", ++ kind = "codeaction", ++ format_item = function(item) return tostring(item) end, ++ preview_item = function(_) return { buf = buf } end, ++ }, function() end) ++ end) ++ child.wait_until(function() ++ return child.lua_get([[_G._fzf_lua_on_create]]) == true ++ end, 5000) ++ local captured = child.lua_get([[_G._fzf_exec_opts]]) ++ eq(captured.no_resume, true) ++ eq(captured.no_hide, true) ++ eq(captured.esc_action_type, "nil") ++ close_picker("") ++ eq(child.lua_get( ++ [[(require("fzf-lua.config").__resume_data or {}).contents]]), vim.NIL) ++end ++ + T["ui_select"]["registered function opts receive (ui_opts, items) #2770"] = function() + reload({ "default" }) + -- `config.normalize_opts` calls function opts with no args; the wrapper diff --git a/tasks/ibhagwan__fzf-lua-2798/tests/test.sh b/tasks/ibhagwan__fzf-lua-2798/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1461b54a3d7b536796fb597738744949dadd3c6a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8671012a7b2a1648595952c655039d51fb301c14 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2798/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2798/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2798/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2810/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2810/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..356659d8d7dab8240aa0dd32d59d5c49cffa79de --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 02bc882f208f3481aa959dbbee8ce5edad2fd8b2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 02bc882f208f3481aa959dbbee8ce5edad2fd8b2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 02bc882f208f3481aa959dbbee8ce5edad2fd8b2 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2810/instruction.md b/tasks/ibhagwan__fzf-lua-2810/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea28a7d29a82f63f3dc5a4ea2e73e3341791db3e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(oldfiles): async fs_stat with per-file stat_timeout (fix #2793) + +## Description + +`:FzfLua history`/`oldfiles` can hang indefinitely when the stat_file check blocks in `fs_stat` on a broken file/link, stale network mount, etc. + +libuv has no timeout option for fs requests, but as suggested in the issue thread the async version can be combined with a timer: when the request doesn't complete in time an attempt is made to cancel it with `uv.cancel` and the file is skipped: + +- utils.fs_request_timeout: run an async libuv fs request (fs_stat, fs_open, ...) with a timeout, cancelling on expiry. Cancellation is best-effort: it only succeeds for queued requests, a request already executing (hung syscall) can't be interrupted, its callback is then ignored via a `done` guard if it ever fires. +- utils.fs_stat_async / utils.file_is_readable_async wrappers, the latter also protects against `fs_open` hangs (FIFOs #908, stale mounts). +- oldfiles provider: the stat checks inside the contents coroutine now yield and resume with the async result; the resume is scheduled as fs/timer callbacks run in fast-event context where most `vim.api` calls in the loop (`nvim_buf_get_name`, `utils.CTX`, ...) error out. +- new `stat_timeout` option (default: 100), set to `0` to disable and keep the previous blocking stat behavior. + +Note: the header-line session buffer check still uses blocking stat as it runs synchronously before the picker starts. + + +## Summary by CodeRabbit + +- **Bug Fixes** + - Improved the Old Files picker’s handling of unavailable, stale, or special files so checks no longer hang. + - Files that cannot be checked within the configured time are skipped, allowing results to load more reliably. + +- **New Features** + - Added a configurable file-check timeout for the Old Files picker, defaulting to 100 ms. + - Setting the timeout to `0` preserves blocking file checks when needed. + - Added timeout-aware asynchronous file and readability checks. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `02bc882f208f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2810/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2810/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..76a1ca2c1a1aaa7c31e633af6f6eb96dd6512d3b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/solution/patch.diff @@ -0,0 +1,306 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 4d54f224..3a4f4997 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1020,6 +1020,11 @@ M.defaults.args = { + ---@field shada_file? string + ---Only include files that still exist on disk. + ---@field stat_file? boolean ++---Timeout in ms for the per-file stat checks, files whose stat does not ++---complete within the timeout are skipped, protects against hangs caused ++---by `fs_stat` on stale network mounts, broken links, etc. Set to `0` to ++---disable and use blocking stat calls. Requires `stat_file`. ++---@field stat_timeout? integer + ---Include files opened during the current session. + ---@field include_current_session? boolean + ---Exclude the current buffer from the list. +@@ -1030,6 +1035,7 @@ M.defaults.oldfiles = { + color_icons = true, + git_icons = false, + stat_file = true, ++ stat_timeout = 100, + include_current_session = false, + ignore_current_buffer = true, + fzf_opts = { ["--tiebreak"] = "index", ["--multi"] = true }, +diff --git a/lua/fzf-lua/providers/oldfiles.lua b/lua/fzf-lua/providers/oldfiles.lua +index 54f92c65..70dc159e 100644 +--- a/lua/fzf-lua/providers/oldfiles.lua ++++ b/lua/fzf-lua/providers/oldfiles.lua +@@ -20,23 +20,58 @@ M.oldfiles = function(opts, globals) + opts.cwd_only = true + end + ++ -- `fs_stat` can hang indefinitely on broken files/links, stale network ++ -- mounts, etc. When running inside the contents coroutine use the async ++ -- variant with a per-file timeout so such files are skipped instead of ++ -- hanging the picker, disable by setting `stat_timeout=0` (#2793) + local stat_fn = not opts.stat_file and function(_) return true end + or type(opts.stat_file) == "function" and opts.stat_file +- or function(file) +- local stat = uv.fs_stat(file) +- return (not utils.path_is_directory(file, stat) +- -- FIFO blocks `fs_open` indefinitely (#908) +- and not utils.file_is_fifo(file, stat) +- and utils.file_is_readable(file)) ++ or function(file, co) ++ -- outside of a coroutine context (e.g. the header line) we have ++ -- no choice but to use the blocking sync variant ++ if not co or not opts.stat_timeout or opts.stat_timeout <= 0 then ++ local stat = uv.fs_stat(file) ++ return (not utils.path_is_directory(file, stat) ++ -- FIFO blocks `fs_open` indefinitely (#908) ++ and not utils.file_is_fifo(file, stat) ++ and utils.file_is_readable(file)) ++ end ++ -- schedule the resume as the fs/timer callbacks run in fast-event ++ -- context where most `vim.api` calls in the loop are not allowed ++ local resume = function(...) ++ local argv = { n = select("#", ...), ... } ++ vim.schedule(function() ++ if coroutine.status(co) == "suspended" then ++ coroutine.resume(co, unpack(argv, 1, argv.n)) ++ end ++ end) ++ end ++ utils.fs_stat_async(file, opts.stat_timeout, function(stat) ++ if not stat ++ or utils.path_is_directory(file, stat) ++ -- FIFO blocks `fs_open` indefinitely (#908) ++ or utils.file_is_fifo(file, stat) ++ then ++ return resume(false) ++ end ++ -- a stale mount can hang `fs_open` as well (#2793) ++ utils.file_is_readable_async(file, opts.stat_timeout, resume) ++ end) ++ -- resumed with the result by the callbacks above ++ return coroutine.yield() + end + +- local sorted_named_buffers = function() ++ ---@param co thread? contents coroutine, enables async stat (#2793) ++ local sorted_named_buffers = function(co) + local bufnrs = {} ++ -- capture the current buffer once, the context can change while ++ -- waiting on async stat results (e.g. fzf's window opens) ++ local curr_buf = utils.CTX().bufnr + for _, bufnr in ipairs(require("fzf-lua.providers.buffers").list_bufs_sorted()) do + local file = vim.api.nvim_buf_get_name(bufnr) +- local fs_stat = #file > 0 and stat_fn(file) ++ local fs_stat = #file > 0 and stat_fn(file, co) + if fs_stat then +- table.insert(bufnrs, { bufnr = bufnr, file = file, curbuf = bufnr == utils.CTX().bufnr }) ++ table.insert(bufnrs, { bufnr = bufnr, file = file, curbuf = bufnr == curr_buf }) + end + end + return bufnrs +@@ -99,7 +134,7 @@ M.oldfiles = function(opts, globals) + end + + if opts.include_current_session then +- for _, buf in ipairs(sorted_named_buffers()) do ++ for _, buf in ipairs(sorted_named_buffers(co)) do + if not opts.ignore_current_buffer or buf.bufnr ~= curr_buf then + sess_map[buf.file] = true + -- 3rd arg forces addition of current buffer with cwd_only +@@ -110,7 +145,7 @@ M.oldfiles = function(opts, globals) + + -- local start = os.time(); for _ = 1,10000,1 do + for _, file in ipairs(vim.v.oldfiles) do +- local fs_stat = stat_fn(file) ++ local fs_stat = stat_fn(file, co) + if fs_stat and file ~= curr_file and not sess_map[file] then + add_entry(file, co) + end +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 3c17eeda..650e440d 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -450,6 +450,67 @@ M.file_is_readable = function(filepath) + return false + end + ++-- Runs an async libuv fs request (e.g. `uv.fs_stat`, `uv.fs_open`) with ++-- a timeout, when the request fails to complete within `timeout` ms an ++-- attempt is made to cancel it using `uv.cancel` and the callback is ++-- called with `err` set. Cancellation is best-effort, a request already ++-- hung on the threadpool (e.g. stale network mount) can't be cancelled ++-- mid-syscall, its callback is then ignored once (if) it fires (#2793). ++---@param fn function async libuv fs function (e.g. `uv.fs_stat`) ++---@param timeout integer timeout in milliseconds ++---@param cb fun(err?: string, ...: any) called with the request results ++---@param ... any request arguments (i.e. path, flags, mode) ++M.fs_request_timeout = function(fn, timeout, cb, ...) ++ local done = false ++ local timer = assert(uv.new_timer()) ++ local finish = function(err, ...) ++ if done then return end ++ done = true ++ timer:stop() ++ timer:close() ++ cb(err, ...) ++ end ++ local argv = { n = select("#", ...), ... } ++ argv[argv.n + 1] = finish ++ local req = fn(unpack(argv, 1, argv.n + 1)) ++ if not req then ++ -- failed to queue the request, keep the callback async ++ timer:start(0, 0, function() finish("ECANCELED: failed to queue fs request") end) ++ return ++ end ++ timer:start(timeout, 0, function() ++ -- NOTE: when cancel succeeds the fs callback is still invoked with ++ -- "ECANCELED", when it fails (already executing) the fs callback is ++ -- eventually invoked with the result, both are ignored via `done` ++ if uv.cancel then pcall(uv.cancel, req) end ++ finish("ECANCELED: fs request timed out") ++ end) ++end ++ ++--- Async `uv.fs_stat` with a timeout, calls `cb(nil)` when the request ++--- fails or does not complete within `timeout` milliseconds (#2793). ++---@param path string ++---@param timeout integer timeout in milliseconds ++---@param cb fun(stat: table?) ++M.fs_stat_async = function(path, timeout, cb) ++ M.fs_request_timeout(uv.fs_stat, timeout, function(err, stat) ++ cb(not err and stat or nil) ++ end, path) ++end ++ ++--- Async `file_is_readable` with a timeout, calls `cb(false)` when the ++--- request fails or does not complete within `timeout` ms (#2793). ++---@param path string ++---@param timeout integer timeout in milliseconds ++---@param cb fun(readable: boolean) ++M.file_is_readable_async = function(path, timeout, cb) ++ M.fs_request_timeout(uv.fs_open, timeout, function(_err, fd) ++ if not fd then return cb(false) end ++ uv.fs_close(fd, function() end) ++ cb(true) ++ end, path, "r", 438) ++end ++ + M.perl_file_is_binary = function(filepath) + filepath = M.pcall_expand(filepath) + if vim.fn.executable("perl") ~= 1 or +diff --git a/tests/utils_spec.lua b/tests/utils_spec.lua +index 98bfe5dc..f159b142 100644 +--- a/tests/utils_spec.lua ++++ b/tests/utils_spec.lua +@@ -213,4 +213,115 @@ describe("Testing utils module", function() + -- escaped backslash before dot (\. becomes ., then rg_escape escapes both) + eq(utils.ctag_escape("foo\\.bar"), "foo\\\\\\.bar") + end) ++ ++ it("fs_stat_async", function() ++ -- stat an existing path ++ local dir = vim.fn.tempname() ++ vim.fn.mkdir(dir, "p") ++ local done, result = false, nil ++ utils.fs_stat_async(dir, 1000, function(stat) ++ done, result = true, stat ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result and result.type, "directory") ++ vim.fn.delete(dir, "rf") ++ ++ -- stat a non-existent path ++ local nonexistent = dir .. "-nonexistent" ++ done, result = false, "unexpected" ++ utils.fs_stat_async(nonexistent, 1000, function(stat) ++ done, result = true, stat ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, nil) ++ end) ++ ++ it("file_is_readable_async", function() ++ -- readable file ++ local file = vim.fn.tempname() ++ local fd = io.open(file, "w") ++ eq(fd ~= nil, true) ++ if fd then ++ fd:write("test") ++ fd:close() ++ end ++ local done, result = false, nil ++ utils.file_is_readable_async(file, 1000, function(readable) ++ done, result = true, readable ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, true) ++ os.remove(file) ++ ++ -- non-existent file ++ local nonexistent = vim.fn.tempname() .. "-nonexistent" ++ done, result = false, true ++ utils.file_is_readable_async(nonexistent, 1000, function(readable) ++ done, result = true, readable ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, false) ++ end) ++ ++ it("fs_request_timeout times out", function() ++ helpers.SKIP_IF_WIN("requires mkfifo") ++ -- `fs_open` on a fifo with no writer blocks indefinitely (#908), ++ -- simulates a hung fs request on a stale mount (#2793) ++ local fifo = vim.fn.tempname() ++ vim.fn.system({ "mkfifo", fifo }) ++ eq(vim.v.shell_error, 0) ++ local done, result = false, nil ++ utils.file_is_readable_async(fifo, 50, function(readable) ++ done, result = true, readable ++ end) ++ -- capture the results, unblock the stuck `fs_open` request (cancel ++ -- fails with EBUSY when the request is already executing on the ++ -- threadpool) and only then assert, so the cleanup always runs -- ++ -- a request stuck on the threadpool hangs the test process at exit ++ local waited = vim.wait(5000, function() return done end, 10) ++ -- open as read-write so we don't block waiting for a peer ++ local f = io.open(fifo, "r+") ++ -- give the stuck request a chance to complete ++ vim.wait(200, function() return false end, 10) ++ if f then f:close() end ++ os.remove(fifo) ++ eq(waited, true) ++ eq(result, false) ++ end) ++ ++ it("fs_stat_async times out", function() ++ helpers.SKIP_IF_WIN("requires mkfifo") ++ -- occupy the entire threadpool with blocking fifo opens so the ++ -- stat request stays queued and times out (#2793) ++ local fifo = vim.fn.tempname() ++ vim.fn.system({ "mkfifo", fifo }) ++ eq(vim.v.shell_error, 0) ++ local open_cbs = 0 ++ for _ = 1, 32 do ++ vim.uv.fs_open(fifo, "r", 438, function(_, fd) ++ open_cbs = open_cbs + 1 ++ if fd then vim.uv.fs_close(fd) end ++ end) ++ end ++ local done = false ++ ---@type table? ++ local result ++ utils.fs_stat_async(fifo, 50, function(stat) ++ done, result = true, stat ++ end) ++ -- capture the results, unblock the stuck `fs_open` requests and only ++ -- then assert, so the cleanup always runs -- a request stuck on the ++ -- threadpool hangs the test process at exit ++ local waited = vim.wait(5000, function() return done end, 10) ++ -- keep the writer open until all requests complete or the queued ++ -- opens will block again once the writer is gone ++ local f = io.open(fifo, "r+") ++ local drained = vim.wait(5000, function() return open_cbs == 32 end, 10) ++ if f then f:close() end ++ os.remove(fifo) ++ eq(waited, true) ++ eq(result, nil) ++ eq(drained, true) ++ eq(open_cbs, 32) ++ end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2810/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2810/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2810/task.toml b/tasks/ibhagwan__fzf-lua-2810/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8ffddc9986dab740ca10c90d08efe9d3add516e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2810" +description = "fix(oldfiles): async fs_stat with per-file stat_timeout (fix #2793)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "02bc882f208f3481aa959dbbee8ce5edad2fd8b2" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2810" +source_access = "auto" +built_at = "2026-11-16T16:09:55.946286+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6e336738cf533bbde6a473898df7f7a95ced59e1ff404c42549df7740f331e5d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-20T18:54:16Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/oldfiles.lua", + "lua/fzf-lua/utils.lua", + "tests/utils_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 235 +difficulty = "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:01.062667+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f93a23a474d31feb48171a8085f04f0cb65ab790d6562e46b57e20a9211cb62" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2810/tests/capture.py b/tasks/ibhagwan__fzf-lua-2810/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2810/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2810/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea28a7d29a82f63f3dc5a4ea2e73e3341791db3e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(oldfiles): async fs_stat with per-file stat_timeout (fix #2793) + +## Description + +`:FzfLua history`/`oldfiles` can hang indefinitely when the stat_file check blocks in `fs_stat` on a broken file/link, stale network mount, etc. + +libuv has no timeout option for fs requests, but as suggested in the issue thread the async version can be combined with a timer: when the request doesn't complete in time an attempt is made to cancel it with `uv.cancel` and the file is skipped: + +- utils.fs_request_timeout: run an async libuv fs request (fs_stat, fs_open, ...) with a timeout, cancelling on expiry. Cancellation is best-effort: it only succeeds for queued requests, a request already executing (hung syscall) can't be interrupted, its callback is then ignored via a `done` guard if it ever fires. +- utils.fs_stat_async / utils.file_is_readable_async wrappers, the latter also protects against `fs_open` hangs (FIFOs #908, stale mounts). +- oldfiles provider: the stat checks inside the contents coroutine now yield and resume with the async result; the resume is scheduled as fs/timer callbacks run in fast-event context where most `vim.api` calls in the loop (`nvim_buf_get_name`, `utils.CTX`, ...) error out. +- new `stat_timeout` option (default: 100), set to `0` to disable and keep the previous blocking stat behavior. + +Note: the header-line session buffer check still uses blocking stat as it runs synchronously before the picker starts. + + +## Summary by CodeRabbit + +- **Bug Fixes** + - Improved the Old Files picker’s handling of unavailable, stale, or special files so checks no longer hang. + - Files that cannot be checked within the configured time are skipped, allowing results to load more reliably. + +- **New Features** + - Added a configurable file-check timeout for the Old Files picker, defaulting to 100 ms. + - Setting the timeout to `0` preserves blocking file checks when needed. + - Added timeout-aware asynchronous file and readability checks. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `02bc882f208f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2810/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2810/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..76a1ca2c1a1aaa7c31e633af6f6eb96dd6512d3b --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/tests/oracle.patch @@ -0,0 +1,306 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 4d54f224..3a4f4997 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1020,6 +1020,11 @@ M.defaults.args = { + ---@field shada_file? string + ---Only include files that still exist on disk. + ---@field stat_file? boolean ++---Timeout in ms for the per-file stat checks, files whose stat does not ++---complete within the timeout are skipped, protects against hangs caused ++---by `fs_stat` on stale network mounts, broken links, etc. Set to `0` to ++---disable and use blocking stat calls. Requires `stat_file`. ++---@field stat_timeout? integer + ---Include files opened during the current session. + ---@field include_current_session? boolean + ---Exclude the current buffer from the list. +@@ -1030,6 +1035,7 @@ M.defaults.oldfiles = { + color_icons = true, + git_icons = false, + stat_file = true, ++ stat_timeout = 100, + include_current_session = false, + ignore_current_buffer = true, + fzf_opts = { ["--tiebreak"] = "index", ["--multi"] = true }, +diff --git a/lua/fzf-lua/providers/oldfiles.lua b/lua/fzf-lua/providers/oldfiles.lua +index 54f92c65..70dc159e 100644 +--- a/lua/fzf-lua/providers/oldfiles.lua ++++ b/lua/fzf-lua/providers/oldfiles.lua +@@ -20,23 +20,58 @@ M.oldfiles = function(opts, globals) + opts.cwd_only = true + end + ++ -- `fs_stat` can hang indefinitely on broken files/links, stale network ++ -- mounts, etc. When running inside the contents coroutine use the async ++ -- variant with a per-file timeout so such files are skipped instead of ++ -- hanging the picker, disable by setting `stat_timeout=0` (#2793) + local stat_fn = not opts.stat_file and function(_) return true end + or type(opts.stat_file) == "function" and opts.stat_file +- or function(file) +- local stat = uv.fs_stat(file) +- return (not utils.path_is_directory(file, stat) +- -- FIFO blocks `fs_open` indefinitely (#908) +- and not utils.file_is_fifo(file, stat) +- and utils.file_is_readable(file)) ++ or function(file, co) ++ -- outside of a coroutine context (e.g. the header line) we have ++ -- no choice but to use the blocking sync variant ++ if not co or not opts.stat_timeout or opts.stat_timeout <= 0 then ++ local stat = uv.fs_stat(file) ++ return (not utils.path_is_directory(file, stat) ++ -- FIFO blocks `fs_open` indefinitely (#908) ++ and not utils.file_is_fifo(file, stat) ++ and utils.file_is_readable(file)) ++ end ++ -- schedule the resume as the fs/timer callbacks run in fast-event ++ -- context where most `vim.api` calls in the loop are not allowed ++ local resume = function(...) ++ local argv = { n = select("#", ...), ... } ++ vim.schedule(function() ++ if coroutine.status(co) == "suspended" then ++ coroutine.resume(co, unpack(argv, 1, argv.n)) ++ end ++ end) ++ end ++ utils.fs_stat_async(file, opts.stat_timeout, function(stat) ++ if not stat ++ or utils.path_is_directory(file, stat) ++ -- FIFO blocks `fs_open` indefinitely (#908) ++ or utils.file_is_fifo(file, stat) ++ then ++ return resume(false) ++ end ++ -- a stale mount can hang `fs_open` as well (#2793) ++ utils.file_is_readable_async(file, opts.stat_timeout, resume) ++ end) ++ -- resumed with the result by the callbacks above ++ return coroutine.yield() + end + +- local sorted_named_buffers = function() ++ ---@param co thread? contents coroutine, enables async stat (#2793) ++ local sorted_named_buffers = function(co) + local bufnrs = {} ++ -- capture the current buffer once, the context can change while ++ -- waiting on async stat results (e.g. fzf's window opens) ++ local curr_buf = utils.CTX().bufnr + for _, bufnr in ipairs(require("fzf-lua.providers.buffers").list_bufs_sorted()) do + local file = vim.api.nvim_buf_get_name(bufnr) +- local fs_stat = #file > 0 and stat_fn(file) ++ local fs_stat = #file > 0 and stat_fn(file, co) + if fs_stat then +- table.insert(bufnrs, { bufnr = bufnr, file = file, curbuf = bufnr == utils.CTX().bufnr }) ++ table.insert(bufnrs, { bufnr = bufnr, file = file, curbuf = bufnr == curr_buf }) + end + end + return bufnrs +@@ -99,7 +134,7 @@ M.oldfiles = function(opts, globals) + end + + if opts.include_current_session then +- for _, buf in ipairs(sorted_named_buffers()) do ++ for _, buf in ipairs(sorted_named_buffers(co)) do + if not opts.ignore_current_buffer or buf.bufnr ~= curr_buf then + sess_map[buf.file] = true + -- 3rd arg forces addition of current buffer with cwd_only +@@ -110,7 +145,7 @@ M.oldfiles = function(opts, globals) + + -- local start = os.time(); for _ = 1,10000,1 do + for _, file in ipairs(vim.v.oldfiles) do +- local fs_stat = stat_fn(file) ++ local fs_stat = stat_fn(file, co) + if fs_stat and file ~= curr_file and not sess_map[file] then + add_entry(file, co) + end +diff --git a/lua/fzf-lua/utils.lua b/lua/fzf-lua/utils.lua +index 3c17eeda..650e440d 100644 +--- a/lua/fzf-lua/utils.lua ++++ b/lua/fzf-lua/utils.lua +@@ -450,6 +450,67 @@ M.file_is_readable = function(filepath) + return false + end + ++-- Runs an async libuv fs request (e.g. `uv.fs_stat`, `uv.fs_open`) with ++-- a timeout, when the request fails to complete within `timeout` ms an ++-- attempt is made to cancel it using `uv.cancel` and the callback is ++-- called with `err` set. Cancellation is best-effort, a request already ++-- hung on the threadpool (e.g. stale network mount) can't be cancelled ++-- mid-syscall, its callback is then ignored once (if) it fires (#2793). ++---@param fn function async libuv fs function (e.g. `uv.fs_stat`) ++---@param timeout integer timeout in milliseconds ++---@param cb fun(err?: string, ...: any) called with the request results ++---@param ... any request arguments (i.e. path, flags, mode) ++M.fs_request_timeout = function(fn, timeout, cb, ...) ++ local done = false ++ local timer = assert(uv.new_timer()) ++ local finish = function(err, ...) ++ if done then return end ++ done = true ++ timer:stop() ++ timer:close() ++ cb(err, ...) ++ end ++ local argv = { n = select("#", ...), ... } ++ argv[argv.n + 1] = finish ++ local req = fn(unpack(argv, 1, argv.n + 1)) ++ if not req then ++ -- failed to queue the request, keep the callback async ++ timer:start(0, 0, function() finish("ECANCELED: failed to queue fs request") end) ++ return ++ end ++ timer:start(timeout, 0, function() ++ -- NOTE: when cancel succeeds the fs callback is still invoked with ++ -- "ECANCELED", when it fails (already executing) the fs callback is ++ -- eventually invoked with the result, both are ignored via `done` ++ if uv.cancel then pcall(uv.cancel, req) end ++ finish("ECANCELED: fs request timed out") ++ end) ++end ++ ++--- Async `uv.fs_stat` with a timeout, calls `cb(nil)` when the request ++--- fails or does not complete within `timeout` milliseconds (#2793). ++---@param path string ++---@param timeout integer timeout in milliseconds ++---@param cb fun(stat: table?) ++M.fs_stat_async = function(path, timeout, cb) ++ M.fs_request_timeout(uv.fs_stat, timeout, function(err, stat) ++ cb(not err and stat or nil) ++ end, path) ++end ++ ++--- Async `file_is_readable` with a timeout, calls `cb(false)` when the ++--- request fails or does not complete within `timeout` ms (#2793). ++---@param path string ++---@param timeout integer timeout in milliseconds ++---@param cb fun(readable: boolean) ++M.file_is_readable_async = function(path, timeout, cb) ++ M.fs_request_timeout(uv.fs_open, timeout, function(_err, fd) ++ if not fd then return cb(false) end ++ uv.fs_close(fd, function() end) ++ cb(true) ++ end, path, "r", 438) ++end ++ + M.perl_file_is_binary = function(filepath) + filepath = M.pcall_expand(filepath) + if vim.fn.executable("perl") ~= 1 or +diff --git a/tests/utils_spec.lua b/tests/utils_spec.lua +index 98bfe5dc..f159b142 100644 +--- a/tests/utils_spec.lua ++++ b/tests/utils_spec.lua +@@ -213,4 +213,115 @@ describe("Testing utils module", function() + -- escaped backslash before dot (\. becomes ., then rg_escape escapes both) + eq(utils.ctag_escape("foo\\.bar"), "foo\\\\\\.bar") + end) ++ ++ it("fs_stat_async", function() ++ -- stat an existing path ++ local dir = vim.fn.tempname() ++ vim.fn.mkdir(dir, "p") ++ local done, result = false, nil ++ utils.fs_stat_async(dir, 1000, function(stat) ++ done, result = true, stat ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result and result.type, "directory") ++ vim.fn.delete(dir, "rf") ++ ++ -- stat a non-existent path ++ local nonexistent = dir .. "-nonexistent" ++ done, result = false, "unexpected" ++ utils.fs_stat_async(nonexistent, 1000, function(stat) ++ done, result = true, stat ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, nil) ++ end) ++ ++ it("file_is_readable_async", function() ++ -- readable file ++ local file = vim.fn.tempname() ++ local fd = io.open(file, "w") ++ eq(fd ~= nil, true) ++ if fd then ++ fd:write("test") ++ fd:close() ++ end ++ local done, result = false, nil ++ utils.file_is_readable_async(file, 1000, function(readable) ++ done, result = true, readable ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, true) ++ os.remove(file) ++ ++ -- non-existent file ++ local nonexistent = vim.fn.tempname() .. "-nonexistent" ++ done, result = false, true ++ utils.file_is_readable_async(nonexistent, 1000, function(readable) ++ done, result = true, readable ++ end) ++ eq(vim.wait(5000, function() return done end, 10), true) ++ eq(result, false) ++ end) ++ ++ it("fs_request_timeout times out", function() ++ helpers.SKIP_IF_WIN("requires mkfifo") ++ -- `fs_open` on a fifo with no writer blocks indefinitely (#908), ++ -- simulates a hung fs request on a stale mount (#2793) ++ local fifo = vim.fn.tempname() ++ vim.fn.system({ "mkfifo", fifo }) ++ eq(vim.v.shell_error, 0) ++ local done, result = false, nil ++ utils.file_is_readable_async(fifo, 50, function(readable) ++ done, result = true, readable ++ end) ++ -- capture the results, unblock the stuck `fs_open` request (cancel ++ -- fails with EBUSY when the request is already executing on the ++ -- threadpool) and only then assert, so the cleanup always runs -- ++ -- a request stuck on the threadpool hangs the test process at exit ++ local waited = vim.wait(5000, function() return done end, 10) ++ -- open as read-write so we don't block waiting for a peer ++ local f = io.open(fifo, "r+") ++ -- give the stuck request a chance to complete ++ vim.wait(200, function() return false end, 10) ++ if f then f:close() end ++ os.remove(fifo) ++ eq(waited, true) ++ eq(result, false) ++ end) ++ ++ it("fs_stat_async times out", function() ++ helpers.SKIP_IF_WIN("requires mkfifo") ++ -- occupy the entire threadpool with blocking fifo opens so the ++ -- stat request stays queued and times out (#2793) ++ local fifo = vim.fn.tempname() ++ vim.fn.system({ "mkfifo", fifo }) ++ eq(vim.v.shell_error, 0) ++ local open_cbs = 0 ++ for _ = 1, 32 do ++ vim.uv.fs_open(fifo, "r", 438, function(_, fd) ++ open_cbs = open_cbs + 1 ++ if fd then vim.uv.fs_close(fd) end ++ end) ++ end ++ local done = false ++ ---@type table? ++ local result ++ utils.fs_stat_async(fifo, 50, function(stat) ++ done, result = true, stat ++ end) ++ -- capture the results, unblock the stuck `fs_open` requests and only ++ -- then assert, so the cleanup always runs -- a request stuck on the ++ -- threadpool hangs the test process at exit ++ local waited = vim.wait(5000, function() return done end, 10) ++ -- keep the writer open until all requests complete or the queued ++ -- opens will block again once the writer is gone ++ local f = io.open(fifo, "r+") ++ local drained = vim.wait(5000, function() return open_cbs == 32 end, 10) ++ if f then f:close() end ++ os.remove(fifo) ++ eq(waited, true) ++ eq(result, nil) ++ eq(drained, true) ++ eq(open_cbs, 32) ++ end) + end) diff --git a/tasks/ibhagwan__fzf-lua-2810/tests/test.sh b/tasks/ibhagwan__fzf-lua-2810/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..614307a9da47431e6af607dd5471457c00adb9bb --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 02bc882f208f3481aa959dbbee8ce5edad2fd8b2 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2810/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2810/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2810/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2813/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2813/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f4d29982b5b3a87722bc3c943e5144a0dd332dd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 13bb178a299f7493dd64427a58e61904c4b58ecb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 13bb178a299f7493dd64427a58e61904c4b58ecb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 13bb178a299f7493dd64427a58e61904c4b58ecb \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2813/instruction.md b/tasks/ibhagwan__fzf-lua-2813/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c98f3f88460daa0e563b71465c80e256cc7163b7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** fix: do not ignore autocmds when restoring window + +## Description + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Restoring the previous window now switches to it and back while respecting the editor’s current event-ignore setting. Window-change events are no longer suppressed by this restoration step, so the behavior follows the setting active at the time of the switch. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `13bb178a299f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2813/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2813/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e8143a1da88dc444045b146be1b24b3e0f6b817e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 63eaef17..520762eb 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1158,10 +1158,8 @@ local restore_lastwin = function(winid, last_winid) + then + return + end +- utils.eventignore(function() +- api.nvim_set_current_win(last_winid) +- api.nvim_set_current_win(winid) +- end) ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) + end + + ---@param buf? integer diff --git a/tasks/ibhagwan__fzf-lua-2813/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2813/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2813/task.toml b/tasks/ibhagwan__fzf-lua-2813/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a7131787cb97197511cf719f1aefd22ffe28d750 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2813" +description = "fix: do not ignore autocmds when restoring window" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "13bb178a299f7493dd64427a58e61904c4b58ecb" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2813" +source_access = "auto" +built_at = "2026-11-16T16:09:55.940622+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cf01f1ec7b248ea61e835ae90039dc0aede012a7ea823074d21783a8a608d1bc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-27T11:09:14Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/win.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[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:01.063146+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6f9ae0aa33c30fdf9de251d3d16c170a20820fae93ca375b4a61e71b5394a19" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2813/tests/capture.py b/tasks/ibhagwan__fzf-lua-2813/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2813/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2813/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c98f3f88460daa0e563b71465c80e256cc7163b7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** fix: do not ignore autocmds when restoring window + +## Description + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Restoring the previous window now switches to it and back while respecting the editor’s current event-ignore setting. Window-change events are no longer suppressed by this restoration step, so the behavior follows the setting active at the time of the switch. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `13bb178a299f`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2813/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2813/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e8143a1da88dc444045b146be1b24b3e0f6b817e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/lua/fzf-lua/win.lua b/lua/fzf-lua/win.lua +index 63eaef17..520762eb 100644 +--- a/lua/fzf-lua/win.lua ++++ b/lua/fzf-lua/win.lua +@@ -1158,10 +1158,8 @@ local restore_lastwin = function(winid, last_winid) + then + return + end +- utils.eventignore(function() +- api.nvim_set_current_win(last_winid) +- api.nvim_set_current_win(winid) +- end) ++ api.nvim_set_current_win(last_winid) ++ api.nvim_set_current_win(winid) + end + + ---@param buf? integer diff --git a/tasks/ibhagwan__fzf-lua-2813/tests/test.sh b/tasks/ibhagwan__fzf-lua-2813/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f3e828d2281729e28dbeeef0f07dda03dddd6b65 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 13bb178a299f7493dd64427a58e61904c4b58ecb > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2813/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2813/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2813/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2816/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2816/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d04c56c49b2ba6aba421cb41b1287806e3a3e74f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ec1b98d3f5f44a1cff1f2c3832af2f09c3d806ca 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ec1b98d3f5f44a1cff1f2c3832af2f09c3d806ca \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ec1b98d3f5f44a1cff1f2c3832af2f09c3d806ca \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2816/instruction.md b/tasks/ibhagwan__fzf-lua-2816/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dc11aadcf07a58b1281ce2ad54a336c5ebfc841 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(undotree): add tree_style option with :Undotree graph layout + +## Description + +- Add opts.tree_style = "tree" | "graph" (default "tree") in defaults.lua. +- Keep the existing box-drawing tree as the default. +- Port the :Undotree graph-line algorithm for tree_style="graph", including connector rows between branches. +- Use Unicode box-drawing glyphs (│ ● ╲ ╱) instead of ASCII so the graph stays upright even when the highlight group is italicized. +- Skip connector rows (which contain no sequence number) in actions.undo and both undotree previewers. +- Add tests covering tree and graph rendering, connector rows, nested branches, and grandchild ordering. + +PR ready notes: +- make test glob=undotree passes all 13 cases. +- Manually verified both tree and graph styles in a tmux session. + +Fix #2806 + + +## Summary by CodeRabbit + +* **New Features** + * Added a graph-style display option for undo history, showing sequence numbers and relative times. The existing tree style remains the default, and graph orientation adapts to the selected layout. +* **Bug Fixes** + * Undo actions and previews now correctly read sequence numbers from colorized entries. They safely handle entries without a numeric sequence, preventing errors or unintended undo actions. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec1b98d3f5f4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2816/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2816/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5d47b265bf4c9f4768f57cbb61a2df4819acea6f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/solution/patch.diff @@ -0,0 +1,570 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 18b1d0ff..14ee7281 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1337,7 +1337,8 @@ end + + M.undo = function(selected, _opts) + if not selected[1] then return end +- local seq = selected[1]:match("%d+") ++ local seq = utils.strip_ansi_coloring(selected[1]):match("%d+") ++ if not seq then return end + vim.cmd("silent undo " .. tostring(seq)) + utils.info("Undo jump to %s.", seq == "0" and "origin" or "change #" .. tostring(seq)) + end +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 4b1892d7..157e1516 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1932,9 +1932,12 @@ M.defaults.autocmds = { + ---@field __locate_pos? integer + ---Jump to the current undo position on picker open. + ---@field locate boolean ++---Undo tree draw style, `tree` for the existing box-drawing layout or `graph` for the `:Undotree` ASCII graph layout. ++---@field tree_style "tree"|"graph" + M.defaults.undotree = { + previewer = "undotree", + locate = true, ++ tree_style = "tree", + fzf_opts = { ["--no-multi"] = true }, + actions = { ["enter"] = actions.undo }, + _cached_hls = { "buf_linenr", "buf_name", "path_linenr", "dir_part" }, +diff --git a/lua/fzf-lua/providers/undotree.lua b/lua/fzf-lua/providers/undotree.lua +index 4c5c32a8..67786549 100644 +--- a/lua/fzf-lua/providers/undotree.lua ++++ b/lua/fzf-lua/providers/undotree.lua +@@ -108,13 +108,206 @@ end + --- @class (partial) vim.undotree.tree.entry + --- @field traversed? boolean + +---- @param opts fzf-lua.config.Undotree ++--- @class (private) fzf-lua.providers.undotree.GraphLineBase ++--- @field index integer ++--- @field node_count integer ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineNode: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'node'|'remove'|'nochange_remove' ++--- @field node integer ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineBranch: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'branch' ++--- @field node integer[] ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineRemoveBranch: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'remove+branch' ++--- @field node integer ++--- @field index2 integer ++ ++--- @alias fzf-lua.providers.undotree.GraphLine ++--- | fzf-lua.providers.undotree.GraphLineNode ++--- | fzf-lua.providers.undotree.GraphLineBranch ++--- | fzf-lua.providers.undotree.GraphLineRemoveBranch ++ ++--- Ported from neovim/runtime/pack/dist/opt/nvim.undotree/lua/undotree.lua ++--- @param tree vim.undotree.tree ++--- @return fzf-lua.providers.undotree.GraphLine[] ++local function tree_to_graph_lines(tree) ++ --- @type fzf-lua.providers.undotree.GraphLine[] ++ local graph_lines = {} ++ ++ ---@diagnostic disable-next-line: unnecessary-assert ++ assert(tree[0], "tree doesn't have 0-th node") ++ --- @type (integer[]|integer)[] ++ local nodes = { 0 } ++ ++ while #nodes > 0 do ++ local minseq = math.huge ++ --- @type integer ++ local index ++ --- @type integer ++ local node_index ++ ++ for k, v in ipairs(nodes) do ++ if type(v) == 'table' then ++ for i, j in ipairs(v) do ++ if j < minseq then ++ minseq = j ++ index = k ++ node_index = i ++ end ++ end ++ elseif v < minseq then ++ assert(type(v) == 'number') ++ minseq = v ++ index = k ++ end ++ end ++ ++ local node = nodes[index] ++ ++ --- @param kind 'node'|'remove'|'branch'|'nochange_remove' ++ local function add_graph_line(kind) ++ table.insert(graph_lines, { kind = kind, index = index, node_count = #nodes, node = node }) ++ end ++ ++ if type(node) == 'number' then ++ add_graph_line('node') ++ ++ local child = tree[node].child ++ if #child == 0 then ++ if index ~= #nodes then ++ add_graph_line('remove') ++ else ++ add_graph_line('nochange_remove') ++ end ++ ++ table.remove(nodes, index) ++ elseif #child == 1 then ++ nodes[index] = child[1] ++ else ++ nodes[index] = child ++ end ++ else ++ assert(type(node) == 'table') ++ ++ add_graph_line('branch') ++ ++ table.remove(nodes, index) ++ if #node == 2 then ++ ---@diagnostic disable-next-line: param-type-mismatch ++ table.insert(nodes, index, math.min(unpack(node))) ++ ---@diagnostic disable-next-line: param-type-mismatch ++ table.insert(nodes, index, math.max(unpack(node))) ++ elseif #node > 2 then ++ table.insert(nodes, index, node[node_index]) ++ table.insert(nodes, index, node) ++ table.remove(node, node_index) ++ end ++ end ++ end ++ ++ for k, v in ipairs(graph_lines) do ++ local next_line = graph_lines[k + 1] ++ if v.kind == 'remove' and next_line and next_line.kind == 'branch' then ++ v.kind = 'remove+branch' ++ v.index2 = next_line.index ++ table.remove(graph_lines, k + 1) ++ end ++ end ++ ++ return graph_lines ++end ++ ++---@param _opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } ++---@param tree vim.undotree.tree ++---@param v fzf-lua.providers.undotree.GraphLine ++---@param reverse boolean ++---@return string? ++local function format_graph_line(_opts, tree, v, reverse) ++ -- Use Unicode box-drawing glyphs instead of ASCII so the tree stays upright ++ -- even when the highlight group (e.g. Comment) is italicized. ++ local PIPE = "│" ++ local STAR = "●" ++ local SLASH = "╱" ++ local BACKSLASH = "╲" ++ if reverse then ++ SLASH, BACKSLASH = BACKSLASH, SLASH ++ end ++ if v.kind == 'node' then ++ local seq = v.node --[[@as integer]] ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. STAR ++ .. (' ' .. PIPE):rep(v.node_count - v.index) ++ .. ' ' ++ .. seq ++ .. ' (' ++ .. reltime(tree[seq].time) ++ .. ')' ++ elseif v.kind == 'remove' then ++ return (PIPE .. ' '):rep(v.index - 1) .. (' ' .. SLASH):rep(v.node_count - v.index) ++ elseif v.kind == 'branch' then ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. PIPE .. BACKSLASH ++ .. (' ' .. BACKSLASH):rep(v.node_count - v.index) ++ elseif v.kind == 'remove+branch' then ++ local index2 = assert(v.index2) ++ if index2 < v.index then ++ return (PIPE .. ' '):rep(index2 - 1) ++ .. PIPE .. BACKSLASH ++ .. (' ' .. BACKSLASH):rep(v.index - index2 - 1) ++ .. ' ' ++ .. (' ' .. PIPE):rep(v.node_count - v.index) ++ else ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. (' ' .. SLASH):rep(index2 - v.index) ++ .. ' ' .. SLASH .. PIPE ++ .. (' ' .. PIPE):rep(v.node_count - index2 - 1) ++ end ++ elseif v.kind == 'nochange_remove' then ++ return nil ++ end ++ error('unreachable') ++end ++ ++---@param opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } ++---@param cb fun(seq: integer?, line: string) ++---@param tree vim.undotree.tree ++---@param _curseq integer ++---@param reverse boolean ++local function draw_graph(opts, cb, tree, _curseq, reverse) ++ local graph_lines = tree_to_graph_lines(tree) ++ ++ local hl_dir = utils.ansi_codes[opts.hls.dir_part] ++ local hl_seq = utils.ansi_codes[opts.hls.buf_name] ++ local hl_time = utils.ansi_codes[opts.hls.path_linenr] ++ ++ for _, v in ipairs(graph_lines) do ++ (function() ++ local line = format_graph_line(opts, tree, v, reverse) ++ if not line then return end ++ if v.kind == 'node' then ++ local seq = v.node --[[@as integer]] ++ local graph_part, seq_num, time_str = line:match('^(.-) (%d+) %(([^)]+)%)$') ++ assert(graph_part and seq_num and time_str) ++ cb(seq, hl_dir(graph_part) ++ .. ' ' .. hl_seq(seq_num) ++ .. ' (' .. hl_time(time_str) .. ')') ++ else ++ cb(nil, hl_dir(line)) ++ end ++ end)() ++ end ++end ++ ++--- @param opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } + --- @param cb function + --- @param tree vim.undotree.tree +---- @param nodes integer[]? ++--- @param nodes integer[] + --- @param reverse boolean +---- @param parents integer[]? +---- @param prefix string? ++--- @param parents? integer[] ++--- @param prefix? string + local function draw_tree(opts, cb, tree, nodes, reverse, parents, prefix) + if not nodes or #nodes == 0 then return end + local is_root = nodes[1] == 0 +@@ -170,8 +363,13 @@ M.undotree = function(opts) + coroutine.yield() + end + ++ local tree_style = opts.tree_style or "tree" + local reverse = utils.map_get(opts, "fzf_opts.--layout") == "default" +- draw_tree(opts, add_entry, tree, { 0 }, reverse) ++ if tree_style == "graph" then ++ draw_graph(opts, add_entry, tree, curseq, reverse) ++ else ++ draw_tree(opts, add_entry, tree, { 0 }, reverse) ++ end + + cb(nil) -- EOF + end)() +@@ -324,7 +522,9 @@ function M.builtin:toggle_undo_diff() + end + + function M.builtin:populate_preview_buf(entry_str) +- local seq = assert(tonumber(entry_str:match("%d+"))) ++ local seq_str = utils.strip_ansi_coloring(entry_str):match("%d+") ++ if not seq_str then return end ++ local seq = assert(utils.tointeger(seq_str)) + local lines, buf = undo_diff(self.buf, seq, self.diff_opts) + if seq > 0 and not self.show_buf then + if not self.diff_buf or not vim.api.nvim_buf_is_valid(self.diff_buf) then +@@ -378,9 +578,10 @@ end + function M.native:cmdline(o) + o = o or {} + local act = shell.stringify_data(function(entries, _, _) +- ---@diagnostic disable-next-line: undefined-field +- if not entries[1] then return shell.nop() end +- local seq = assert(utils.tointeger(entries[1]:match("%d+"))) ++ if not entries[1] then return utils.shell_nop() end ++ local seq_str = utils.strip_ansi_coloring(entries[1]):match("%d+") ++ if not seq_str then return utils.shell_nop() end ++ local seq = assert(utils.tointeger(seq_str)) + local lines = undo_diff(self.buf, seq, self.diff_opts) + return table.concat(lines, "\r\n") + end, self.opts, "{}") +@@ -390,4 +591,8 @@ function M.native:cmdline(o) + return act + end + ++-- Exposed for tests. ++M._draw_tree = draw_tree ++M._draw_graph = draw_graph ++ + return M +diff --git a/tests/undotree_spec.lua b/tests/undotree_spec.lua +new file mode 100644 +index 00000000..a8fb3b06 +--- /dev/null ++++ b/tests/undotree_spec.lua +@@ -0,0 +1,269 @@ ++local helpers = require("fzf-lua.test.helpers") ++local assert = helpers.assert ++local eq = assert.are.same ++ ++local undotree = require("fzf-lua.providers.undotree") ++local utils = require("fzf-lua.utils") ++ ++local FROZEN_TIME = 1700000000 ++ ++local function freeze_time() ++ local orig = os.time ++ _G.os.time = function() return FROZEN_TIME end ++ return orig ++end ++ ++local function setup_ansi_identity() ++ local orig = {} ++ for _, hl in ipairs({ "Directory", "Number", "Comment" }) do ++ orig[hl] = utils.ansi_codes[hl] ++ utils.ansi_codes[hl] = function(s) return s end ++ end ++ return orig ++end ++ ++local function restore_ansi_identity(orig) ++ for hl, fn in pairs(orig) do ++ utils.ansi_codes[hl] = fn ++ end ++end ++ ++local opts = { ++ hls = { ++ dir_part = "Directory", ++ buf_name = "Number", ++ path_linenr = "Comment", ++ }, ++} ++ ++local function collect_tree(tree, reverse) ++ local rows = {} ++ local cb = function(seq, line) ++ table.insert(rows, { seq = seq, line = utils.strip_ansi_coloring(line) }) ++ end ++ undotree._draw_tree(opts, cb, tree, { 0 }, reverse or false) ++ return rows ++end ++ ++local function collect_graph(tree) ++ local rows = {} ++ local cb = function(seq, line) ++ table.insert(rows, { seq = seq, line = utils.strip_ansi_coloring(line) }) ++ end ++ undotree._draw_graph(opts, cb, tree, 0, false) ++ return rows ++end ++ ++local function origin() ++ return { [0] = { child = {}, time = -1 } } ++end ++ ++local function linear_chain() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 10 }, ++ } ++end ++ ++local function simple_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ } ++end ++ ++local function triple_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ } ++end ++ ++local function nested_branches() ++ return { ++ [0] = { child = { 1, 2 }, time = -1 }, ++ [1] = { child = { 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ } ++end ++ ++local function grandchild_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = { 5 }, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ [5] = { child = {}, time = FROZEN_TIME + 20 }, ++ } ++end ++ ++describe("undotree draw_tree", function() ++ local orig_time, orig_ansi ++ ++ before_each(function() ++ orig_time = freeze_time() ++ orig_ansi = setup_ansi_identity() ++ end) ++ ++ after_each(function() ++ _G.os.time = orig_time ++ restore_ansi_identity(orig_ansi) ++ end) ++ ++ it("renders a single origin node", function() ++ local rows = collect_tree(origin()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ }, rows) ++ end) ++ ++ it("renders a linear chain without branch glyphs", function() ++ local rows = collect_tree(linear_chain()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "2\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders branch children with box-drawing glyphs", function() ++ local rows = collect_tree(simple_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "└── 3\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("uses reversed leaf glyphs when reverse is true", function() ++ local rows = collect_tree(simple_branch(), true) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "┌── 3\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("handles three siblings", function() ++ local rows = collect_tree(triple_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "├── 3\t\tjust now" }, ++ { seq = 4, line = "└── 4\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders nested branches in pre-order", function() ++ local rows = collect_tree(nested_branches()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "├── 1\t\tjust now" }, ++ { seq = 3, line = "│ ├── 3\t\tjust now" }, ++ { seq = 4, line = "│ └── 4\t\tjust now" }, ++ { seq = 2, line = "└── 2\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders a grandchild in pre-order", function() ++ local rows = collect_tree(grandchild_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "├── 3\t\tjust now" }, ++ { seq = 5, line = "│ 5\t\tjust now" }, ++ { seq = 4, line = "└── 4\t\tjust now" }, ++ }, rows) ++ end) ++end) ++ ++describe("undotree draw_graph", function() ++ local orig_time, orig_ansi ++ ++ before_each(function() ++ orig_time = freeze_time() ++ orig_ansi = setup_ansi_identity() ++ end) ++ ++ after_each(function() ++ _G.os.time = orig_time ++ restore_ansi_identity(orig_ansi) ++ end) ++ ++ it("renders a single origin node", function() ++ local rows = collect_graph(origin()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ }, rows) ++ end) ++ ++ it("renders a linear chain", function() ++ local rows = collect_graph(linear_chain()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = 2, line = "● 2 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders a branch with connector and :Undotree-style columns", function() ++ local rows = collect_graph(simple_branch()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 2, line = "│ ● 2 (just now)" }, ++ { seq = 3, line = "● 3 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders three siblings", function() ++ local rows = collect_graph(triple_branch()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 2, line = "│ ● 2 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 3, line = "│ ● 3 (just now)" }, ++ { seq = 4, line = "● 4 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders nested branches with remove/branch connectors", function() ++ local rows = collect_graph(nested_branches()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 1, line = "│ ● 1 (just now)" }, ++ { seq = 2, line = "● │ 2 (just now)" }, ++ { seq = nil, line = " ╱│" }, ++ { seq = 3, line = "│ ● 3 (just now)" }, ++ { seq = 4, line = "● 4 (just now)" }, ++ }, rows) ++ end) ++ ++ it("emits connector rows with no digits and node rows with digits", function() ++ local rows = collect_graph(simple_branch()) ++ for _, r in ipairs(rows) do ++ if r.seq == nil then ++ eq(nil, r.line:match("%d")) ++ else ++ eq(true, r.line:match("%d+") ~= nil) ++ end ++ end ++ end) ++end) diff --git a/tasks/ibhagwan__fzf-lua-2816/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2816/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2816/task.toml b/tasks/ibhagwan__fzf-lua-2816/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..050e6e9d6abf1602533d1d16402baa70388b0753 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2816" +description = "feat(undotree): add tree_style option with :Undotree graph layout" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "ec1b98d3f5f44a1cff1f2c3832af2f09c3d806ca" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2816" +source_access = "auto" +built_at = "2026-11-16T16:09:55.938509+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:08ec6142bd90beabd615fcc23d2daa9f40e69a7228d2d246d360cafa27c170fd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T17:26:17Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/actions.lua", + "lua/fzf-lua/defaults.lua", + "lua/fzf-lua/providers/undotree.lua", + "tests/undotree_spec.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 498 +difficulty = "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:01.063632+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e0e2d5705075356be81ab9254f19c6755a150118a0a45cb74f83ad332511c585" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2816/tests/capture.py b/tasks/ibhagwan__fzf-lua-2816/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2816/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2816/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dc11aadcf07a58b1281ce2ad54a336c5ebfc841 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(undotree): add tree_style option with :Undotree graph layout + +## Description + +- Add opts.tree_style = "tree" | "graph" (default "tree") in defaults.lua. +- Keep the existing box-drawing tree as the default. +- Port the :Undotree graph-line algorithm for tree_style="graph", including connector rows between branches. +- Use Unicode box-drawing glyphs (│ ● ╲ ╱) instead of ASCII so the graph stays upright even when the highlight group is italicized. +- Skip connector rows (which contain no sequence number) in actions.undo and both undotree previewers. +- Add tests covering tree and graph rendering, connector rows, nested branches, and grandchild ordering. + +PR ready notes: +- make test glob=undotree passes all 13 cases. +- Manually verified both tree and graph styles in a tmux session. + +Fix #2806 + + +## Summary by CodeRabbit + +* **New Features** + * Added a graph-style display option for undo history, showing sequence numbers and relative times. The existing tree style remains the default, and graph orientation adapts to the selected layout. +* **Bug Fixes** + * Undo actions and previews now correctly read sequence numbers from colorized entries. They safely handle entries without a numeric sequence, preventing errors or unintended undo actions. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec1b98d3f5f4`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2816/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2816/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5d47b265bf4c9f4768f57cbb61a2df4819acea6f --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/tests/oracle.patch @@ -0,0 +1,570 @@ +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 18b1d0ff..14ee7281 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1337,7 +1337,8 @@ end + + M.undo = function(selected, _opts) + if not selected[1] then return end +- local seq = selected[1]:match("%d+") ++ local seq = utils.strip_ansi_coloring(selected[1]):match("%d+") ++ if not seq then return end + vim.cmd("silent undo " .. tostring(seq)) + utils.info("Undo jump to %s.", seq == "0" and "origin" or "change #" .. tostring(seq)) + end +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 4b1892d7..157e1516 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1932,9 +1932,12 @@ M.defaults.autocmds = { + ---@field __locate_pos? integer + ---Jump to the current undo position on picker open. + ---@field locate boolean ++---Undo tree draw style, `tree` for the existing box-drawing layout or `graph` for the `:Undotree` ASCII graph layout. ++---@field tree_style "tree"|"graph" + M.defaults.undotree = { + previewer = "undotree", + locate = true, ++ tree_style = "tree", + fzf_opts = { ["--no-multi"] = true }, + actions = { ["enter"] = actions.undo }, + _cached_hls = { "buf_linenr", "buf_name", "path_linenr", "dir_part" }, +diff --git a/lua/fzf-lua/providers/undotree.lua b/lua/fzf-lua/providers/undotree.lua +index 4c5c32a8..67786549 100644 +--- a/lua/fzf-lua/providers/undotree.lua ++++ b/lua/fzf-lua/providers/undotree.lua +@@ -108,13 +108,206 @@ end + --- @class (partial) vim.undotree.tree.entry + --- @field traversed? boolean + +---- @param opts fzf-lua.config.Undotree ++--- @class (private) fzf-lua.providers.undotree.GraphLineBase ++--- @field index integer ++--- @field node_count integer ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineNode: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'node'|'remove'|'nochange_remove' ++--- @field node integer ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineBranch: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'branch' ++--- @field node integer[] ++ ++--- @class (private) fzf-lua.providers.undotree.GraphLineRemoveBranch: fzf-lua.providers.undotree.GraphLineBase ++--- @field kind 'remove+branch' ++--- @field node integer ++--- @field index2 integer ++ ++--- @alias fzf-lua.providers.undotree.GraphLine ++--- | fzf-lua.providers.undotree.GraphLineNode ++--- | fzf-lua.providers.undotree.GraphLineBranch ++--- | fzf-lua.providers.undotree.GraphLineRemoveBranch ++ ++--- Ported from neovim/runtime/pack/dist/opt/nvim.undotree/lua/undotree.lua ++--- @param tree vim.undotree.tree ++--- @return fzf-lua.providers.undotree.GraphLine[] ++local function tree_to_graph_lines(tree) ++ --- @type fzf-lua.providers.undotree.GraphLine[] ++ local graph_lines = {} ++ ++ ---@diagnostic disable-next-line: unnecessary-assert ++ assert(tree[0], "tree doesn't have 0-th node") ++ --- @type (integer[]|integer)[] ++ local nodes = { 0 } ++ ++ while #nodes > 0 do ++ local minseq = math.huge ++ --- @type integer ++ local index ++ --- @type integer ++ local node_index ++ ++ for k, v in ipairs(nodes) do ++ if type(v) == 'table' then ++ for i, j in ipairs(v) do ++ if j < minseq then ++ minseq = j ++ index = k ++ node_index = i ++ end ++ end ++ elseif v < minseq then ++ assert(type(v) == 'number') ++ minseq = v ++ index = k ++ end ++ end ++ ++ local node = nodes[index] ++ ++ --- @param kind 'node'|'remove'|'branch'|'nochange_remove' ++ local function add_graph_line(kind) ++ table.insert(graph_lines, { kind = kind, index = index, node_count = #nodes, node = node }) ++ end ++ ++ if type(node) == 'number' then ++ add_graph_line('node') ++ ++ local child = tree[node].child ++ if #child == 0 then ++ if index ~= #nodes then ++ add_graph_line('remove') ++ else ++ add_graph_line('nochange_remove') ++ end ++ ++ table.remove(nodes, index) ++ elseif #child == 1 then ++ nodes[index] = child[1] ++ else ++ nodes[index] = child ++ end ++ else ++ assert(type(node) == 'table') ++ ++ add_graph_line('branch') ++ ++ table.remove(nodes, index) ++ if #node == 2 then ++ ---@diagnostic disable-next-line: param-type-mismatch ++ table.insert(nodes, index, math.min(unpack(node))) ++ ---@diagnostic disable-next-line: param-type-mismatch ++ table.insert(nodes, index, math.max(unpack(node))) ++ elseif #node > 2 then ++ table.insert(nodes, index, node[node_index]) ++ table.insert(nodes, index, node) ++ table.remove(node, node_index) ++ end ++ end ++ end ++ ++ for k, v in ipairs(graph_lines) do ++ local next_line = graph_lines[k + 1] ++ if v.kind == 'remove' and next_line and next_line.kind == 'branch' then ++ v.kind = 'remove+branch' ++ v.index2 = next_line.index ++ table.remove(graph_lines, k + 1) ++ end ++ end ++ ++ return graph_lines ++end ++ ++---@param _opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } ++---@param tree vim.undotree.tree ++---@param v fzf-lua.providers.undotree.GraphLine ++---@param reverse boolean ++---@return string? ++local function format_graph_line(_opts, tree, v, reverse) ++ -- Use Unicode box-drawing glyphs instead of ASCII so the tree stays upright ++ -- even when the highlight group (e.g. Comment) is italicized. ++ local PIPE = "│" ++ local STAR = "●" ++ local SLASH = "╱" ++ local BACKSLASH = "╲" ++ if reverse then ++ SLASH, BACKSLASH = BACKSLASH, SLASH ++ end ++ if v.kind == 'node' then ++ local seq = v.node --[[@as integer]] ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. STAR ++ .. (' ' .. PIPE):rep(v.node_count - v.index) ++ .. ' ' ++ .. seq ++ .. ' (' ++ .. reltime(tree[seq].time) ++ .. ')' ++ elseif v.kind == 'remove' then ++ return (PIPE .. ' '):rep(v.index - 1) .. (' ' .. SLASH):rep(v.node_count - v.index) ++ elseif v.kind == 'branch' then ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. PIPE .. BACKSLASH ++ .. (' ' .. BACKSLASH):rep(v.node_count - v.index) ++ elseif v.kind == 'remove+branch' then ++ local index2 = assert(v.index2) ++ if index2 < v.index then ++ return (PIPE .. ' '):rep(index2 - 1) ++ .. PIPE .. BACKSLASH ++ .. (' ' .. BACKSLASH):rep(v.index - index2 - 1) ++ .. ' ' ++ .. (' ' .. PIPE):rep(v.node_count - v.index) ++ else ++ return (PIPE .. ' '):rep(v.index - 1) ++ .. (' ' .. SLASH):rep(index2 - v.index) ++ .. ' ' .. SLASH .. PIPE ++ .. (' ' .. PIPE):rep(v.node_count - index2 - 1) ++ end ++ elseif v.kind == 'nochange_remove' then ++ return nil ++ end ++ error('unreachable') ++end ++ ++---@param opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } ++---@param cb fun(seq: integer?, line: string) ++---@param tree vim.undotree.tree ++---@param _curseq integer ++---@param reverse boolean ++local function draw_graph(opts, cb, tree, _curseq, reverse) ++ local graph_lines = tree_to_graph_lines(tree) ++ ++ local hl_dir = utils.ansi_codes[opts.hls.dir_part] ++ local hl_seq = utils.ansi_codes[opts.hls.buf_name] ++ local hl_time = utils.ansi_codes[opts.hls.path_linenr] ++ ++ for _, v in ipairs(graph_lines) do ++ (function() ++ local line = format_graph_line(opts, tree, v, reverse) ++ if not line then return end ++ if v.kind == 'node' then ++ local seq = v.node --[[@as integer]] ++ local graph_part, seq_num, time_str = line:match('^(.-) (%d+) %(([^)]+)%)$') ++ assert(graph_part and seq_num and time_str) ++ cb(seq, hl_dir(graph_part) ++ .. ' ' .. hl_seq(seq_num) ++ .. ' (' .. hl_time(time_str) .. ')') ++ else ++ cb(nil, hl_dir(line)) ++ end ++ end)() ++ end ++end ++ ++--- @param opts { hls: { dir_part: string, buf_name: string, path_linenr: string } } + --- @param cb function + --- @param tree vim.undotree.tree +---- @param nodes integer[]? ++--- @param nodes integer[] + --- @param reverse boolean +---- @param parents integer[]? +---- @param prefix string? ++--- @param parents? integer[] ++--- @param prefix? string + local function draw_tree(opts, cb, tree, nodes, reverse, parents, prefix) + if not nodes or #nodes == 0 then return end + local is_root = nodes[1] == 0 +@@ -170,8 +363,13 @@ M.undotree = function(opts) + coroutine.yield() + end + ++ local tree_style = opts.tree_style or "tree" + local reverse = utils.map_get(opts, "fzf_opts.--layout") == "default" +- draw_tree(opts, add_entry, tree, { 0 }, reverse) ++ if tree_style == "graph" then ++ draw_graph(opts, add_entry, tree, curseq, reverse) ++ else ++ draw_tree(opts, add_entry, tree, { 0 }, reverse) ++ end + + cb(nil) -- EOF + end)() +@@ -324,7 +522,9 @@ function M.builtin:toggle_undo_diff() + end + + function M.builtin:populate_preview_buf(entry_str) +- local seq = assert(tonumber(entry_str:match("%d+"))) ++ local seq_str = utils.strip_ansi_coloring(entry_str):match("%d+") ++ if not seq_str then return end ++ local seq = assert(utils.tointeger(seq_str)) + local lines, buf = undo_diff(self.buf, seq, self.diff_opts) + if seq > 0 and not self.show_buf then + if not self.diff_buf or not vim.api.nvim_buf_is_valid(self.diff_buf) then +@@ -378,9 +578,10 @@ end + function M.native:cmdline(o) + o = o or {} + local act = shell.stringify_data(function(entries, _, _) +- ---@diagnostic disable-next-line: undefined-field +- if not entries[1] then return shell.nop() end +- local seq = assert(utils.tointeger(entries[1]:match("%d+"))) ++ if not entries[1] then return utils.shell_nop() end ++ local seq_str = utils.strip_ansi_coloring(entries[1]):match("%d+") ++ if not seq_str then return utils.shell_nop() end ++ local seq = assert(utils.tointeger(seq_str)) + local lines = undo_diff(self.buf, seq, self.diff_opts) + return table.concat(lines, "\r\n") + end, self.opts, "{}") +@@ -390,4 +591,8 @@ function M.native:cmdline(o) + return act + end + ++-- Exposed for tests. ++M._draw_tree = draw_tree ++M._draw_graph = draw_graph ++ + return M +diff --git a/tests/undotree_spec.lua b/tests/undotree_spec.lua +new file mode 100644 +index 00000000..a8fb3b06 +--- /dev/null ++++ b/tests/undotree_spec.lua +@@ -0,0 +1,269 @@ ++local helpers = require("fzf-lua.test.helpers") ++local assert = helpers.assert ++local eq = assert.are.same ++ ++local undotree = require("fzf-lua.providers.undotree") ++local utils = require("fzf-lua.utils") ++ ++local FROZEN_TIME = 1700000000 ++ ++local function freeze_time() ++ local orig = os.time ++ _G.os.time = function() return FROZEN_TIME end ++ return orig ++end ++ ++local function setup_ansi_identity() ++ local orig = {} ++ for _, hl in ipairs({ "Directory", "Number", "Comment" }) do ++ orig[hl] = utils.ansi_codes[hl] ++ utils.ansi_codes[hl] = function(s) return s end ++ end ++ return orig ++end ++ ++local function restore_ansi_identity(orig) ++ for hl, fn in pairs(orig) do ++ utils.ansi_codes[hl] = fn ++ end ++end ++ ++local opts = { ++ hls = { ++ dir_part = "Directory", ++ buf_name = "Number", ++ path_linenr = "Comment", ++ }, ++} ++ ++local function collect_tree(tree, reverse) ++ local rows = {} ++ local cb = function(seq, line) ++ table.insert(rows, { seq = seq, line = utils.strip_ansi_coloring(line) }) ++ end ++ undotree._draw_tree(opts, cb, tree, { 0 }, reverse or false) ++ return rows ++end ++ ++local function collect_graph(tree) ++ local rows = {} ++ local cb = function(seq, line) ++ table.insert(rows, { seq = seq, line = utils.strip_ansi_coloring(line) }) ++ end ++ undotree._draw_graph(opts, cb, tree, 0, false) ++ return rows ++end ++ ++local function origin() ++ return { [0] = { child = {}, time = -1 } } ++end ++ ++local function linear_chain() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 10 }, ++ } ++end ++ ++local function simple_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ } ++end ++ ++local function triple_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ } ++end ++ ++local function nested_branches() ++ return { ++ [0] = { child = { 1, 2 }, time = -1 }, ++ [1] = { child = { 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = {}, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ } ++end ++ ++local function grandchild_branch() ++ return { ++ [0] = { child = { 1 }, time = -1 }, ++ [1] = { child = { 2, 3, 4 }, time = FROZEN_TIME }, ++ [2] = { child = {}, time = FROZEN_TIME + 5 }, ++ [3] = { child = { 5 }, time = FROZEN_TIME + 10 }, ++ [4] = { child = {}, time = FROZEN_TIME + 15 }, ++ [5] = { child = {}, time = FROZEN_TIME + 20 }, ++ } ++end ++ ++describe("undotree draw_tree", function() ++ local orig_time, orig_ansi ++ ++ before_each(function() ++ orig_time = freeze_time() ++ orig_ansi = setup_ansi_identity() ++ end) ++ ++ after_each(function() ++ _G.os.time = orig_time ++ restore_ansi_identity(orig_ansi) ++ end) ++ ++ it("renders a single origin node", function() ++ local rows = collect_tree(origin()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ }, rows) ++ end) ++ ++ it("renders a linear chain without branch glyphs", function() ++ local rows = collect_tree(linear_chain()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "2\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders branch children with box-drawing glyphs", function() ++ local rows = collect_tree(simple_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "└── 3\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("uses reversed leaf glyphs when reverse is true", function() ++ local rows = collect_tree(simple_branch(), true) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "┌── 3\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("handles three siblings", function() ++ local rows = collect_tree(triple_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "├── 3\t\tjust now" }, ++ { seq = 4, line = "└── 4\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders nested branches in pre-order", function() ++ local rows = collect_tree(nested_branches()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "├── 1\t\tjust now" }, ++ { seq = 3, line = "│ ├── 3\t\tjust now" }, ++ { seq = 4, line = "│ └── 4\t\tjust now" }, ++ { seq = 2, line = "└── 2\t\tjust now" }, ++ }, rows) ++ end) ++ ++ it("renders a grandchild in pre-order", function() ++ local rows = collect_tree(grandchild_branch()) ++ eq({ ++ { seq = 0, line = "0\t\torigin" }, ++ { seq = 1, line = "1\t\tjust now" }, ++ { seq = 2, line = "├── 2\t\tjust now" }, ++ { seq = 3, line = "├── 3\t\tjust now" }, ++ { seq = 5, line = "│ 5\t\tjust now" }, ++ { seq = 4, line = "└── 4\t\tjust now" }, ++ }, rows) ++ end) ++end) ++ ++describe("undotree draw_graph", function() ++ local orig_time, orig_ansi ++ ++ before_each(function() ++ orig_time = freeze_time() ++ orig_ansi = setup_ansi_identity() ++ end) ++ ++ after_each(function() ++ _G.os.time = orig_time ++ restore_ansi_identity(orig_ansi) ++ end) ++ ++ it("renders a single origin node", function() ++ local rows = collect_graph(origin()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ }, rows) ++ end) ++ ++ it("renders a linear chain", function() ++ local rows = collect_graph(linear_chain()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = 2, line = "● 2 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders a branch with connector and :Undotree-style columns", function() ++ local rows = collect_graph(simple_branch()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 2, line = "│ ● 2 (just now)" }, ++ { seq = 3, line = "● 3 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders three siblings", function() ++ local rows = collect_graph(triple_branch()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = 1, line = "● 1 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 2, line = "│ ● 2 (just now)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 3, line = "│ ● 3 (just now)" }, ++ { seq = 4, line = "● 4 (just now)" }, ++ }, rows) ++ end) ++ ++ it("renders nested branches with remove/branch connectors", function() ++ local rows = collect_graph(nested_branches()) ++ eq({ ++ { seq = 0, line = "● 0 (origin)" }, ++ { seq = nil, line = "│╲" }, ++ { seq = 1, line = "│ ● 1 (just now)" }, ++ { seq = 2, line = "● │ 2 (just now)" }, ++ { seq = nil, line = " ╱│" }, ++ { seq = 3, line = "│ ● 3 (just now)" }, ++ { seq = 4, line = "● 4 (just now)" }, ++ }, rows) ++ end) ++ ++ it("emits connector rows with no digits and node rows with digits", function() ++ local rows = collect_graph(simple_branch()) ++ for _, r in ipairs(rows) do ++ if r.seq == nil then ++ eq(nil, r.line:match("%d")) ++ else ++ eq(true, r.line:match("%d+") ~= nil) ++ end ++ end ++ end) ++end) diff --git a/tasks/ibhagwan__fzf-lua-2816/tests/test.sh b/tasks/ibhagwan__fzf-lua-2816/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b6b646ed44765d5cd2607e31d6d6f4001cdfbbc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ec1b98d3f5f44a1cff1f2c3832af2f09c3d806ca > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2816/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2816/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2816/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2820/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2820/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee1735f5b9e8d6f4f212952be9d328482185f4fd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin eab53acb3fd36479f084f854b4418d02b5c70382 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eab53acb3fd36479f084f854b4418d02b5c70382 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eab53acb3fd36479f084f854b4418d02b5c70382 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2820/instruction.md b/tasks/ibhagwan__fzf-lua-2820/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461911b489d81d85495bf2ddc62c6ee18a00a0f2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: pcall wrap invalid regex match + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved the reliability of preview highlighting for both case-sensitive and case-insensitive regex searches. Matching errors are now handled safely, helping prevent them from interrupting the preview experience. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eab53acb3fd3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2820/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2820/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..660be169f7739963ef20ab34029f5ffc3c5c1440 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 813cb35b..2e407777 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1335,12 +1335,16 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + ---@diagnostic disable-next-line: param-type-mismatch + local reg = utils.vim_regex(regex, { silent = true }) + if reg then +- if case_sensitive then +- regex_start, regex_end = reg:match_line(buf, lnum - 1, col - 1) +- else +- local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" +- regex_start, regex_end = reg:match_str(line:sub(col):lower()) +- end ++ regex_start, regex_end = utils.npcall(function() ++ if case_sensitive then ++ ---@diagnostic disable-next-line: redundant-return-value ++ return reg:match_line(buf, lnum - 1, col - 1) ++ else ++ local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" ++ ---@diagnostic disable-next-line: redundant-return-value ++ return reg:match_str(line:sub(col):lower()) ++ end ++ end) + end + if regex_start and regex_end then + extmark = api.nvim_buf_set_extmark(buf, self.ns_previewer, lnum - 1, regex_start + col - 1, { diff --git a/tasks/ibhagwan__fzf-lua-2820/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2820/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2820/task.toml b/tasks/ibhagwan__fzf-lua-2820/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..005ca68f730127c2f60c569025c9540244230159 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2820" +description = "fix: pcall wrap invalid regex match" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "eab53acb3fd36479f084f854b4418d02b5c70382" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2820" +source_access = "auto" +built_at = "2026-11-16T16:09:55.935704+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d36a234900f435af144e3078eb0eaa2e03996789013d78a0069b3c627945856c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-02T07:24:35Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/builtin.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[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:01.064169+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:306dc2730162298ad7479f8d3678790b7c8fa9d658ed14b7e0cc355b208037b0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2820/tests/capture.py b/tasks/ibhagwan__fzf-lua-2820/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2820/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2820/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461911b489d81d85495bf2ddc62c6ee18a00a0f2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix: pcall wrap invalid regex match + +## Description + +Fix + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved the reliability of preview highlighting for both case-sensitive and case-insensitive regex searches. Matching errors are now handled safely, helping prevent them from interrupting the preview experience. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eab53acb3fd3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2820/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2820/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..660be169f7739963ef20ab34029f5ffc3c5c1440 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/lua/fzf-lua/previewer/builtin.lua b/lua/fzf-lua/previewer/builtin.lua +index 813cb35b..2e407777 100644 +--- a/lua/fzf-lua/previewer/builtin.lua ++++ b/lua/fzf-lua/previewer/builtin.lua +@@ -1335,12 +1335,16 @@ function Previewer.buffer_or_file:set_cursor_hl(entry) + ---@diagnostic disable-next-line: param-type-mismatch + local reg = utils.vim_regex(regex, { silent = true }) + if reg then +- if case_sensitive then +- regex_start, regex_end = reg:match_line(buf, lnum - 1, col - 1) +- else +- local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" +- regex_start, regex_end = reg:match_str(line:sub(col):lower()) +- end ++ regex_start, regex_end = utils.npcall(function() ++ if case_sensitive then ++ ---@diagnostic disable-next-line: redundant-return-value ++ return reg:match_line(buf, lnum - 1, col - 1) ++ else ++ local line = api.nvim_buf_get_lines(buf, lnum - 1, lnum, false)[1] or "" ++ ---@diagnostic disable-next-line: redundant-return-value ++ return reg:match_str(line:sub(col):lower()) ++ end ++ end) + end + if regex_start and regex_end then + extmark = api.nvim_buf_set_extmark(buf, self.ns_previewer, lnum - 1, regex_start + col - 1, { diff --git a/tasks/ibhagwan__fzf-lua-2820/tests/test.sh b/tasks/ibhagwan__fzf-lua-2820/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..159d45abd437b94a5fb026e7fd5caac7ae7002c0 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace eab53acb3fd36479f084f854b4418d02b5c70382 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2820/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2820/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2820/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2821/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2821/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d59058676fab6748a9709dca160a600ef46f7a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d5c12c6d72ed84554f0f8dacb84f20da094b6a2d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d5c12c6d72ed84554f0f8dacb84f20da094b6a2d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d5c12c6d72ed84554f0f8dacb84f20da094b6a2d \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2821/instruction.md b/tasks/ibhagwan__fzf-lua-2821/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..768f2f62cad45d38868d3b0e6e4450dd399febfc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** ci: fix lint + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * Updated project checks and diagnostics. These changes do not alter application behavior or add user-facing features. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d5c12c6d72ed`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2821/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2821/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f77e6cb8189e536fe9a79b16a5236b8d599458c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index 8339fbb6..df4ba209 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -1,10 +1,6 @@ + name: Lint + +-on: +- push: +- branches: [main, dev] +- pull_request: +- branches: "*" ++on: push + + jobs: + lint: +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 14ee7281..4013039c 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1350,6 +1350,7 @@ end + M.serverlist_kill = function(sel) + ---@diagnostic disable-next-line: redundant-parameter, call-non-callable + vim.iter(sel):map(parse_entry):each(function(addr) ++ ---@cast addr string + local ok, err = utils.rpcexec(addr, "nvim_exec2", "qa!", {}) + assert(ok + or tostring(err):match("Invalid channel") +diff --git a/scripts/gen_options.lua b/scripts/gen_options.lua +index 893393a4..3fa01f6a 100644 +--- a/scripts/gen_options.lua ++++ b/scripts/gen_options.lua +@@ -74,6 +74,7 @@ local function fix_typ(typ, default) + local ty = typ:sub(2, -2) + ---@diagnostic disable-next-line: redundant-parameter, call-non-callable + local is = vim.iter(vim.split(ty, ",")):all(function(t) ++ ---@diagnostic disable-next-line: return-type-mismatch + return t:match([[".-"]]) + end) + if is then diff --git a/tasks/ibhagwan__fzf-lua-2821/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2821/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2821/task.toml b/tasks/ibhagwan__fzf-lua-2821/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..81c50a3c94d412d2783f46f9937643c5ce772f21 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2821" +description = "ci: fix lint" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "d5c12c6d72ed84554f0f8dacb84f20da094b6a2d" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2821" +source_access = "auto" +built_at = "2026-11-16T16:09:55.936939+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6d5fe67d159f2d9409b9a580db4e516f34c890400f8dfb19b69aaf86fbc00984" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-04T17:44:18Z" +diff_format = "unified" +context_files = [ + ".github/workflows/lint.yaml", + "lua/fzf-lua/actions.lua", + "scripts/gen_options.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[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:01.064721+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:09886a7e847727e3d7f5eed90b9b0f0a939dc0086cf89d0c45fa62aa111b3394" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2821/tests/capture.py b/tasks/ibhagwan__fzf-lua-2821/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2821/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2821/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..768f2f62cad45d38868d3b0e6e4450dd399febfc --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** ci: fix lint + +## Description + + +## Summary by CodeRabbit + +* **Chores** + * Updated project checks and diagnostics. These changes do not alter application behavior or add user-facing features. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d5c12c6d72ed`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2821/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2821/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1f77e6cb8189e536fe9a79b16a5236b8d599458c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml +index 8339fbb6..df4ba209 100644 +--- a/.github/workflows/lint.yaml ++++ b/.github/workflows/lint.yaml +@@ -1,10 +1,6 @@ + name: Lint + +-on: +- push: +- branches: [main, dev] +- pull_request: +- branches: "*" ++on: push + + jobs: + lint: +diff --git a/lua/fzf-lua/actions.lua b/lua/fzf-lua/actions.lua +index 14ee7281..4013039c 100644 +--- a/lua/fzf-lua/actions.lua ++++ b/lua/fzf-lua/actions.lua +@@ -1350,6 +1350,7 @@ end + M.serverlist_kill = function(sel) + ---@diagnostic disable-next-line: redundant-parameter, call-non-callable + vim.iter(sel):map(parse_entry):each(function(addr) ++ ---@cast addr string + local ok, err = utils.rpcexec(addr, "nvim_exec2", "qa!", {}) + assert(ok + or tostring(err):match("Invalid channel") +diff --git a/scripts/gen_options.lua b/scripts/gen_options.lua +index 893393a4..3fa01f6a 100644 +--- a/scripts/gen_options.lua ++++ b/scripts/gen_options.lua +@@ -74,6 +74,7 @@ local function fix_typ(typ, default) + local ty = typ:sub(2, -2) + ---@diagnostic disable-next-line: redundant-parameter, call-non-callable + local is = vim.iter(vim.split(ty, ",")):all(function(t) ++ ---@diagnostic disable-next-line: return-type-mismatch + return t:match([[".-"]]) + end) + if is then diff --git a/tasks/ibhagwan__fzf-lua-2821/tests/test.sh b/tasks/ibhagwan__fzf-lua-2821/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b92c96ada6964ef4adacfaf5e2d3961f077dea62 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d5c12c6d72ed84554f0f8dacb84f20da094b6a2d > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2821/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2821/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2821/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2824/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2824/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cdbc7d72a1cdc2684ad5acb89984235aba12d90e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c5e1465b6fc37a98a4b88d883f26050d663048b9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c5e1465b6fc37a98a4b88d883f26050d663048b9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c5e1465b6fc37a98a4b88d883f26050d663048b9 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2824/instruction.md b/tasks/ibhagwan__fzf-lua-2824/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a66b352bd3387cf6c339496a15ed3f2472164f7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(cli): exec /bin/sh in post-fork child to avoid Neovim teardown + +## Description + +In the CLI profile's non-TTY/ZLE path, `Ctrl-Q` forks and the child ran: + + os.execute(shell_cmd) + os.exit(0) + +`os.exit()` is Neovim's Lua exit handler, not a raw POSIX exit, so the post-fork child performed a full Neovim/libuv teardown (`getout -> os_exit -> loop_close -> uv_run`) on the libuv state copied by `fork()`. Continuing to use an inherited libuv loop after `fork()` without `uv_loop_fork()` is undefined behavior; on macOS with Neovim 0.13-dev this leaves a 100%-CPU spinning process stuck in `uv__io_poll/kevent` once the externally opened editor is closed after some time, freezing the shell prompt (parent waits on the child). + +Fix: in the forked child, immediately replace the process image with `/bin/sh -c ` via `execl()`. Since `os.execute()` also runs commands through `/bin/sh -c`, this is behavior-preserving (same shell, same /dev/tty redirections, same 50ms delay letting the parent fzf-lua exit first), while ensuring no Neovim code or teardown ever runs in the post-fork child. If `execl()` fails, fall back to raw `_exit(127)` - no atexit handlers, no Lua GC, no libuv teardown. + + + +## Summary by CodeRabbit + +* **Improvements** + * Shell commands launched through the CLI profile now run in a dedicated child process, keeping command execution isolated from the parent process. If a command cannot be started, the child exits with a failure status. This behavior applies to shell commands invoked through the CLI profile and does not change the parent process’s exit handling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c5e1465b6fc3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2824/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2824/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..823b7817671027d27dc95e555e6ad106c16b3906 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 41e96dab..9c2037d3 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -25,6 +25,7 @@ pcall(function() + int fork(void); + int isatty(int fd); + int fileno(void *stream); ++ void _exit(int status); + ]] + end) + +@@ -56,8 +57,17 @@ local function fork(cmd, ...) + "sleep 0.05; %s %s /dev/tty 2>/dev/tty", cmd, + table.concat(vim.tbl_map(function(x) return FzfLua.libuv.shellescape(x) end, { ... }), " ") + ) +- os.execute(shell_cmd) +- os.exit(0) ++ -- Replace the post-fork child with `/bin/sh` immediately: continuing to ++ -- run Neovim code (and especially Neovim's teardown via `os.exit()`) on ++ -- the libuv state copied by `fork()` is undefined without ++ -- `uv_loop_fork()` and can leave a 100%-CPU spinning process behind ++ -- (observed on macOS with nvim 0.13-dev, #2823). `os.execute()` uses ++ -- `/bin/sh -c` as well, so this is behavior-preserving. ++ ---@diagnostic disable-next-line: call-non-callable, need-check-nil ++ ffi.C.execl("/bin/sh", "sh", "-c", shell_cmd, nil) ++ -- `execl` only returns on failure, exit raw (no atexit handlers/Lua GC) ++ ---@diagnostic disable-next-line: call-non-callable, need-check-nil ++ ffi.C._exit(127) + end + + local function posix_exec(cmd, ...) diff --git a/tasks/ibhagwan__fzf-lua-2824/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2824/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2824/task.toml b/tasks/ibhagwan__fzf-lua-2824/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c71a4a146523e3f70f74ed298a0b4a14671ea89 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2824" +description = "fix(cli): exec /bin/sh in post-fork child to avoid Neovim teardown" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "c5e1465b6fc37a98a4b88d883f26050d663048b9" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2824" +source_access = "auto" +built_at = "2026-11-16T16:09:55.934304+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6c5f6b22b56e1a41725b51e27651aa8411bf64c2b29569e1b716fcfb31c0a9d4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-05T21:27:12Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/profiles/cli.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[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:01.065234+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:93c8a57ca6beb426117fb7d9e342bfac0a8ff81c759dce5e04cdd4757eab0ea7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2824/tests/capture.py b/tasks/ibhagwan__fzf-lua-2824/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2824/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2824/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a66b352bd3387cf6c339496a15ed3f2472164f7 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(cli): exec /bin/sh in post-fork child to avoid Neovim teardown + +## Description + +In the CLI profile's non-TTY/ZLE path, `Ctrl-Q` forks and the child ran: + + os.execute(shell_cmd) + os.exit(0) + +`os.exit()` is Neovim's Lua exit handler, not a raw POSIX exit, so the post-fork child performed a full Neovim/libuv teardown (`getout -> os_exit -> loop_close -> uv_run`) on the libuv state copied by `fork()`. Continuing to use an inherited libuv loop after `fork()` without `uv_loop_fork()` is undefined behavior; on macOS with Neovim 0.13-dev this leaves a 100%-CPU spinning process stuck in `uv__io_poll/kevent` once the externally opened editor is closed after some time, freezing the shell prompt (parent waits on the child). + +Fix: in the forked child, immediately replace the process image with `/bin/sh -c ` via `execl()`. Since `os.execute()` also runs commands through `/bin/sh -c`, this is behavior-preserving (same shell, same /dev/tty redirections, same 50ms delay letting the parent fzf-lua exit first), while ensuring no Neovim code or teardown ever runs in the post-fork child. If `execl()` fails, fall back to raw `_exit(127)` - no atexit handlers, no Lua GC, no libuv teardown. + + + +## Summary by CodeRabbit + +* **Improvements** + * Shell commands launched through the CLI profile now run in a dedicated child process, keeping command execution isolated from the parent process. If a command cannot be started, the child exits with a failure status. This behavior applies to shell commands invoked through the CLI profile and does not change the parent process’s exit handling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c5e1465b6fc3`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2824/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2824/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..823b7817671027d27dc95e555e6ad106c16b3906 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/lua/fzf-lua/profiles/cli.lua b/lua/fzf-lua/profiles/cli.lua +index 41e96dab..9c2037d3 100644 +--- a/lua/fzf-lua/profiles/cli.lua ++++ b/lua/fzf-lua/profiles/cli.lua +@@ -25,6 +25,7 @@ pcall(function() + int fork(void); + int isatty(int fd); + int fileno(void *stream); ++ void _exit(int status); + ]] + end) + +@@ -56,8 +57,17 @@ local function fork(cmd, ...) + "sleep 0.05; %s %s /dev/tty 2>/dev/tty", cmd, + table.concat(vim.tbl_map(function(x) return FzfLua.libuv.shellescape(x) end, { ... }), " ") + ) +- os.execute(shell_cmd) +- os.exit(0) ++ -- Replace the post-fork child with `/bin/sh` immediately: continuing to ++ -- run Neovim code (and especially Neovim's teardown via `os.exit()`) on ++ -- the libuv state copied by `fork()` is undefined without ++ -- `uv_loop_fork()` and can leave a 100%-CPU spinning process behind ++ -- (observed on macOS with nvim 0.13-dev, #2823). `os.execute()` uses ++ -- `/bin/sh -c` as well, so this is behavior-preserving. ++ ---@diagnostic disable-next-line: call-non-callable, need-check-nil ++ ffi.C.execl("/bin/sh", "sh", "-c", shell_cmd, nil) ++ -- `execl` only returns on failure, exit raw (no atexit handlers/Lua GC) ++ ---@diagnostic disable-next-line: call-non-callable, need-check-nil ++ ffi.C._exit(127) + end + + local function posix_exec(cmd, ...) diff --git a/tasks/ibhagwan__fzf-lua-2824/tests/test.sh b/tasks/ibhagwan__fzf-lua-2824/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..792382ab16bd94abc4c1f4ddebde4abff2ad28db --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c5e1465b6fc37a98a4b88d883f26050d663048b9 > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2824/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2824/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2824/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2825/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2825/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1fe768c17dc6f32c8e22c7f02124b19a532067dd --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ed0e0ead1789ee349cbf025900931fb402b1e05e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ed0e0ead1789ee349cbf025900931fb402b1e05e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ed0e0ead1789ee349cbf025900931fb402b1e05e \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2825/instruction.md b/tasks/ibhagwan__fzf-lua-2825/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3b49ca6267b2bec62d9dfde42484b709d9f8fb9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(ts-context): align upstream changes + +## Description + +wrap `render.open` + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved preview context detection across supported rendering configurations, preventing context-related issues when displaying previews. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ed0e0ead1789`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2825/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2825/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..040fa69620902688ba5b009d9eef6c8566a3e6ee --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/previewer/tscontext.lua b/lua/fzf-lua/previewer/tscontext.lua +index 8ede3c44..ceab0d61 100644 +--- a/lua/fzf-lua/previewer/tscontext.lua ++++ b/lua/fzf-lua/previewer/tscontext.lua +@@ -121,8 +121,9 @@ function M.update(winid, bufnr, opts) + if api.nvim_buf_is_valid(bufnr) and api.nvim_win_is_valid(winid) then + api.nvim_win_call(winid, function() + render.open(winid, context_ranges, context_lines) +- M.window_contexts = M.window_contexts or +- utils.upvfind(render.open, "window_contexts") ++ M.window_contexts = M.window_contexts or utils.upvfind(render.open, "window_contexts") ++ -- https://github.com/nvim-treesitter/nvim-treesitter-context/pull/680 ++ or utils.upvfind(utils.upvfind(render.open, "open") or print, "window_contexts") + if not M.window_contexts then return end + local window_context = M.window_contexts[winid] + if not window_context or not M.zindex then return end diff --git a/tasks/ibhagwan__fzf-lua-2825/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2825/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2825/task.toml b/tasks/ibhagwan__fzf-lua-2825/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..98fba5ed238368cbc8bc23c793f1035ad0d7a131 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2825" +description = "fix(ts-context): align upstream changes" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "ed0e0ead1789ee349cbf025900931fb402b1e05e" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2825" +source_access = "auto" +built_at = "2026-11-16T16:09:55.925730+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:97a587715889a890bff7994aa8d03b869465a717c6903032463222e7e7196546" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-10T01:17:02Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/previewer/tscontext.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "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:01.065729+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:80c64035f1baec4708a8c13976aa8b613bfbe0ee10620810c9e1e118b29b7662" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2825/tests/capture.py b/tasks/ibhagwan__fzf-lua-2825/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2825/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2825/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3b49ca6267b2bec62d9dfde42484b709d9f8fb9 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(ts-context): align upstream changes + +## Description + +wrap `render.open` + + + +## Summary by CodeRabbit + +* **Bug Fixes** + * Improved preview context detection across supported rendering configurations, preventing context-related issues when displaying previews. + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ed0e0ead1789`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2825/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2825/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..040fa69620902688ba5b009d9eef6c8566a3e6ee --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lua/fzf-lua/previewer/tscontext.lua b/lua/fzf-lua/previewer/tscontext.lua +index 8ede3c44..ceab0d61 100644 +--- a/lua/fzf-lua/previewer/tscontext.lua ++++ b/lua/fzf-lua/previewer/tscontext.lua +@@ -121,8 +121,9 @@ function M.update(winid, bufnr, opts) + if api.nvim_buf_is_valid(bufnr) and api.nvim_win_is_valid(winid) then + api.nvim_win_call(winid, function() + render.open(winid, context_ranges, context_lines) +- M.window_contexts = M.window_contexts or +- utils.upvfind(render.open, "window_contexts") ++ M.window_contexts = M.window_contexts or utils.upvfind(render.open, "window_contexts") ++ -- https://github.com/nvim-treesitter/nvim-treesitter-context/pull/680 ++ or utils.upvfind(utils.upvfind(render.open, "open") or print, "window_contexts") + if not M.window_contexts then return end + local window_context = M.window_contexts[winid] + if not window_context or not M.zindex then return end diff --git a/tasks/ibhagwan__fzf-lua-2825/tests/test.sh b/tasks/ibhagwan__fzf-lua-2825/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..68ab6dc7e15b17395196e0aa898a2e4e2b3d62e5 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ed0e0ead1789ee349cbf025900931fb402b1e05e > "$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 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$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.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ibhagwan__fzf-lua-2825/tests/verifier.py b/tasks/ibhagwan__fzf-lua-2825/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2825/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its 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 from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — 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 they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable 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 tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import 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/`` 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": , "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 ``/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 + # ); 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", +] diff --git a/tasks/ibhagwan__fzf-lua-2827/environment/Dockerfile b/tasks/ibhagwan__fzf-lua-2827/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f9a17729e2fff69b25675a24d10396b130e7e59e --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/environment/Dockerfile @@ -0,0 +1,37 @@ +# 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-slim +ARG 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 false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ibhagwan/fzf-lua.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ibhagwan/fzf-lua.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ibhagwan/fzf-lua.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 48d7c3db291a2c7c1825905c227a6bc81c83b837 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 48d7c3db291a2c7c1825905c227a6bc81c83b837 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 48d7c3db291a2c7c1825905c227a6bc81c83b837 \ + && git remote remove origin 2>/dev/null || true +RUN 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 || true +RUN 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; \ + fi diff --git a/tasks/ibhagwan__fzf-lua-2827/instruction.md b/tasks/ibhagwan__fzf-lua-2827/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3fa00263ff7925cd3b6804ce315b37d5f6c9678 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** docs(lsp): fix symbol_style description + +## Description + +https://github.com/ibhagwan/fzf-lua/discussions/2826 + + +## Summary by CodeRabbit + +* **Documentation** + * Clarified the available LSP symbol styles: icon plus kind, icon only, or kind only. Documented that `false` disables symbol styling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d7c3db291a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2827/solution/patch.diff b/tasks/ibhagwan__fzf-lua-2827/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..91cbd9747625a5e2321ee42c223ff5cc1c12c5a2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 157e1516..95db05e7 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1569,8 +1569,8 @@ M.defaults.lsp = { + ---@field symbol_hl? fun(s:string):string + ---Custom format function for symbol display. + ---@field symbol_fmt? fun(s:string, ...):string +----Display style for symbol icons, `1` for icon only, `2` for icon+name, `3` for icon+name(colored). +----@field symbol_style? integer ++---Display style for symbol kinds, `1` for icon+kind, `2` for icon only, `3` for kind only. ++---@field symbol_style? integer|false + ---Icons for each symbol kind. + ---@field symbol_icons? table + ---Display child prefix (indentation) for nested symbols. diff --git a/tasks/ibhagwan__fzf-lua-2827/solution/solve.sh b/tasks/ibhagwan__fzf-lua-2827/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ibhagwan__fzf-lua-2827/task.toml b/tasks/ibhagwan__fzf-lua-2827/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c0afaee07b110655d7c66a7a428eb1521b7fb9c --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ibhagwan__fzf-lua-2827" +description = "docs(lsp): fix symbol_style description" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "fzf-lua", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ibhagwan/fzf-lua" +ref = "48d7c3db291a2c7c1825905c227a6bc81c83b837" +reference = "https://github.com/ibhagwan/fzf-lua/pull/2827" +source_access = "auto" +built_at = "2026-11-16T16:09:55.932787+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:73e83eb6f6b7c7f093490997e4e7e0459451028d2ef400406d35d3b1f15d3172" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-12T19:00:20Z" +diff_format = "unified" +context_files = [ + "lua/fzf-lua/defaults.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "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:01.066193+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f74bf5bf9085e8bd547357590740b0fcdff2dad3e6dc0ac2748e654d6f10a8e6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ibhagwan__fzf-lua-2827/tests/capture.py b/tasks/ibhagwan__fzf-lua-2827/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from 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()) diff --git a/tasks/ibhagwan__fzf-lua-2827/tests/instruction.md b/tasks/ibhagwan__fzf-lua-2827/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3fa00263ff7925cd3b6804ce315b37d5f6c9678 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** docs(lsp): fix symbol_style description + +## Description + +https://github.com/ibhagwan/fzf-lua/discussions/2826 + + +## Summary by CodeRabbit + +* **Documentation** + * Clarified the available LSP symbol styles: icon plus kind, icon only, or kind only. Documented that `false` disables symbol styling. + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `48d7c3db291a`. 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. \ No newline at end of file diff --git a/tasks/ibhagwan__fzf-lua-2827/tests/oracle.patch b/tasks/ibhagwan__fzf-lua-2827/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..91cbd9747625a5e2321ee42c223ff5cc1c12c5a2 --- /dev/null +++ b/tasks/ibhagwan__fzf-lua-2827/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/lua/fzf-lua/defaults.lua b/lua/fzf-lua/defaults.lua +index 157e1516..95db05e7 100644 +--- a/lua/fzf-lua/defaults.lua ++++ b/lua/fzf-lua/defaults.lua +@@ -1569,8 +1569,8 @@ M.defaults.lsp = { + ---@field symbol_hl? fun(s:string):string + ---Custom format function for symbol display. + ---@field symbol_fmt? fun(s:string, ...):string +----Display style for symbol icons, `1` for icon only, `2` for icon+name, `3` for icon+name(colored). +----@field symbol_style? integer ++---Display style for symbol kinds, `1` for icon+kind, `2` for icon only, `3` for kind only. ++---@field symbol_style? integer|false + ---Icons for each symbol kind. + ---@field symbol_icons? table + ---Display child prefix (indentation) for nested symbols.