diff --git a/tasks/playframework__playframework-14269/tests/test.sh b/tasks/playframework__playframework-14269/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..697d5455ef26849d24507b0059af58d8daf26a83 --- /dev/null +++ b/tasks/playframework__playframework-14269/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 c63a79e57f00f2905b0624b88b11257fe1635d66 > "$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/playframework__playframework-14269/tests/verifier.py b/tasks/playframework__playframework-14269/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14269/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/playframework__playframework-14278/environment/Dockerfile b/tasks/playframework__playframework-14278/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f3c4c77b5cbc3f49c12cc51cfa4ae556dac7e045 --- /dev/null +++ b/tasks/playframework__playframework-14278/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && 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/playframework__playframework-14278/instruction.md b/tasks/playframework__playframework-14278/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3e4c47c46a6aaa038731ffce59ae7277814d7b --- /dev/null +++ b/tasks/playframework__playframework-14278/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.10.Final (was 7.4.7.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.7.Final` to `7.4.10.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14278/solution/patch.diff b/tasks/playframework__playframework-14278/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f548177dd47187b0b31914427ed9ef44c514187a --- /dev/null +++ b/tasks/playframework__playframework-14278/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index c26296600c..5341d0a198 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 8930e82c69..858ae034ba 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..2e7eeada0e 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.7.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.10.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14278/solution/solve.sh b/tasks/playframework__playframework-14278/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14278/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/playframework__playframework-14278/task.toml b/tasks/playframework__playframework-14278/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c909b455df9873b2e01ac520dcd209a2713266a --- /dev/null +++ b/tasks/playframework__playframework-14278/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14278" +description = "hibernate-core, ... 7.4.10.Final (was 7.4.7.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e" +reference = "https://github.com/playframework/playframework/pull/14278" +source_access = "auto" +built_at = "2026-11-16T16:09:46.515634+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:298caf1f9d7378abc0521a427b06e504ac9777e17644842da8bad8b274bf8564" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:14:45Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.538246+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3c569e88adc3407d0af5c618df23cc6c308180a5e144d96c776c7ecbec1f0676" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14278/tests/capture.py b/tasks/playframework__playframework-14278/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14278/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/playframework__playframework-14278/tests/instruction.md b/tasks/playframework__playframework-14278/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3e4c47c46a6aaa038731ffce59ae7277814d7b --- /dev/null +++ b/tasks/playframework__playframework-14278/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.10.Final (was 7.4.7.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.7.Final` to `7.4.10.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14278/tests/oracle.patch b/tasks/playframework__playframework-14278/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f548177dd47187b0b31914427ed9ef44c514187a --- /dev/null +++ b/tasks/playframework__playframework-14278/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index c26296600c..5341d0a198 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 8930e82c69..858ae034ba 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..2e7eeada0e 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.7.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.7.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.10.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14278/tests/test.sh b/tasks/playframework__playframework-14278/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..237036756b107f9c489e7b07ffd5a299ba2d54b5 --- /dev/null +++ b/tasks/playframework__playframework-14278/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 e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e > "$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/playframework__playframework-14278/tests/verifier.py b/tasks/playframework__playframework-14278/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14278/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/playframework__playframework-14280/environment/Dockerfile b/tasks/playframework__playframework-14280/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f3c4c77b5cbc3f49c12cc51cfa4ae556dac7e045 --- /dev/null +++ b/tasks/playframework__playframework-14280/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && 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/playframework__playframework-14280/instruction.md b/tasks/playframework__playframework-14280/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..808333a09f120169e40fcdef47023144d8212c19 --- /dev/null +++ b/tasks/playframework__playframework-14280/instruction.md @@ -0,0 +1,217 @@ +# Issue + +**Title:** Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [com.eed3si9n:sbt-assembly](https://github.com/sbt/sbt-assembly) from `2.4.1` to `2.4.2` + + 📜 [GitHub Release Notes](https://github.com/sbt/sbt-assembly/releases/tag/v2.4.2) - [Version Diff](https://github.com/sbt/sbt-assembly/compare/v2.4.1...v2.4.2) +* 📦 [com.fasterxml.jackson.core:jackson-databind](https://github.com/FasterXML/jackson-databind) from `2.22.2` to `2.22.3` +* 📦 [com.google.jimfs:jimfs](https://github.com/google/jimfs/) from `1.3.1` to `1.3.2` + + 📜 [GitHub Release Notes](https://github.com/google/jimfs/releases/tag/v1.3.2) - [Version Diff](https://github.com/google/jimfs/compare/v1.3.1...v1.3.2) +* 📦 [joda-time:joda-time](https://github.com/JodaOrg/joda-time) from `2.14.3` to `2.14.4` + + 📜 [GitHub Release Notes](https://github.com/JodaOrg/joda-time/releases/tag/v2.14.4) - [Version Diff](https://github.com/JodaOrg/joda-time/compare/v2.14.3...v2.14.4) +* 📦 org.slf4j:jcl-over-slf4j from `2.0.18` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+🔍 Files still referring to the old version numbers + +The following files still refer to the old version numbers. +You might want to review and update them manually. +``` +transport/server/play-netty-server/src/main/scala/play/core/server/NettyServer.scala +documentation/manual/releases/release26/migration26/JavaConfigMigration26.md +documentation/manual/releases/release28/migration28/Migration28.md +documentation/manual/releases/release29/migration29/Migration29.md +``` +
+
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "com.eed3si9n", artifactId = "sbt-assembly" }, + { groupId = "com.fasterxml.jackson.core", artifactId = "jackson-databind" }, + { groupId = "com.google.jimfs", artifactId = "jimfs" }, + { groupId = "joda-time", artifactId = "joda-time" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.eed3si9n", artifactId = "sbt-assembly" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.fasterxml.jackson.core", artifactId = "jackson-databind" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.google.jimfs", artifactId = "jimfs" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "joda-time", artifactId = "joda-time" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, test-library-update, early-semver-patch, semver-spec-patch, old-version-remains, commit-count:n:5 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14280/solution/patch.diff b/tasks/playframework__playframework-14280/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8dbbd59f1db2efda785a9fe1678d73aa5454e42b --- /dev/null +++ b/tasks/playframework__playframework-14280/solution/patch.diff @@ -0,0 +1,53 @@ +diff --git a/documentation/project/plugins.sbt b/documentation/project/plugins.sbt +index 8971ec00a7..e9587d8fc3 100644 +--- a/documentation/project/plugins.sbt ++++ b/documentation/project/plugins.sbt +@@ -10,7 +10,7 @@ lazy val plugins = (project in file(".")).dependsOn(playDocsPlugin) + lazy val playDocsPlugin = ProjectRef(Path.fileProperty("user.dir").getParentFile, "Play-Docs-Sbt-Plugin") + + // Required for Production.md +-addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.1") ++addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.2") + + // Add headers to example sources + addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..1aff12f793 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -29,7 +29,7 @@ object Dependencies { + "org.scalacheck" %% "scalacheck" % "1.20.0" % Test + ) + +- val jacksonVersion = "2.22.2" ++ val jacksonVersion = "2.22.3" + val jacksonDatabind = Seq("com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion) + val jacksons = Seq( + "com.fasterxml.jackson.core" % "jackson-core", +@@ -46,7 +46,7 @@ object Dependencies { + + val playJson = "org.playframework" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.18" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -108,7 +108,7 @@ object Dependencies { + ) ++ specs2Deps.map(_ % Test) + + val joda = Seq( +- "joda-time" % "joda-time" % "2.14.3", ++ "joda-time" % "joda-time" % "2.14.4", + "org.joda" % "joda-convert" % "3.0.1" + ) + +@@ -177,7 +177,7 @@ object Dependencies { + + val cookieEncodingDependencies = slf4j + +- val jimfs = "com.google.jimfs" % "jimfs" % "1.3.1" ++ val jimfs = "com.google.jimfs" % "jimfs" % "1.3.2" + + val okHttp = "com.squareup.okhttp3" % "okhttp-jvm" % "5.5.0" + diff --git a/tasks/playframework__playframework-14280/solution/solve.sh b/tasks/playframework__playframework-14280/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14280/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/playframework__playframework-14280/task.toml b/tasks/playframework__playframework-14280/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1028db40351630ae438f8430e2df02f51fe84e5d --- /dev/null +++ b/tasks/playframework__playframework-14280/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14280" +description = "Patch updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e" +reference = "https://github.com/playframework/playframework/pull/14280" +source_access = "auto" +built_at = "2026-11-16T16:09:46.528143+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5290b15033e84e0e8d6e9df754e84a4100785208c4d6d76fa0ab418dc6a8482b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:00:07Z" +diff_format = "unified" +context_files = [ + "documentation/project/plugins.sbt", + "project/Dependencies.scala", +] +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:02.538837+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3c569e88adc3407d0af5c618df23cc6c308180a5e144d96c776c7ecbec1f0676" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14280/tests/capture.py b/tasks/playframework__playframework-14280/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14280/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/playframework__playframework-14280/tests/instruction.md b/tasks/playframework__playframework-14280/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..808333a09f120169e40fcdef47023144d8212c19 --- /dev/null +++ b/tasks/playframework__playframework-14280/tests/instruction.md @@ -0,0 +1,217 @@ +# Issue + +**Title:** Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [com.eed3si9n:sbt-assembly](https://github.com/sbt/sbt-assembly) from `2.4.1` to `2.4.2` + + 📜 [GitHub Release Notes](https://github.com/sbt/sbt-assembly/releases/tag/v2.4.2) - [Version Diff](https://github.com/sbt/sbt-assembly/compare/v2.4.1...v2.4.2) +* 📦 [com.fasterxml.jackson.core:jackson-databind](https://github.com/FasterXML/jackson-databind) from `2.22.2` to `2.22.3` +* 📦 [com.google.jimfs:jimfs](https://github.com/google/jimfs/) from `1.3.1` to `1.3.2` + + 📜 [GitHub Release Notes](https://github.com/google/jimfs/releases/tag/v1.3.2) - [Version Diff](https://github.com/google/jimfs/compare/v1.3.1...v1.3.2) +* 📦 [joda-time:joda-time](https://github.com/JodaOrg/joda-time) from `2.14.3` to `2.14.4` + + 📜 [GitHub Release Notes](https://github.com/JodaOrg/joda-time/releases/tag/v2.14.4) - [Version Diff](https://github.com/JodaOrg/joda-time/compare/v2.14.3...v2.14.4) +* 📦 org.slf4j:jcl-over-slf4j from `2.0.18` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+🔍 Files still referring to the old version numbers + +The following files still refer to the old version numbers. +You might want to review and update them manually. +``` +transport/server/play-netty-server/src/main/scala/play/core/server/NettyServer.scala +documentation/manual/releases/release26/migration26/JavaConfigMigration26.md +documentation/manual/releases/release28/migration28/Migration28.md +documentation/manual/releases/release29/migration29/Migration29.md +``` +
+
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "com.eed3si9n", artifactId = "sbt-assembly" }, + { groupId = "com.fasterxml.jackson.core", artifactId = "jackson-databind" }, + { groupId = "com.google.jimfs", artifactId = "jimfs" }, + { groupId = "joda-time", artifactId = "joda-time" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.eed3si9n", artifactId = "sbt-assembly" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.fasterxml.jackson.core", artifactId = "jackson-databind" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.google.jimfs", artifactId = "jimfs" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "joda-time", artifactId = "joda-time" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, test-library-update, early-semver-patch, semver-spec-patch, old-version-remains, commit-count:n:5 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14280/tests/oracle.patch b/tasks/playframework__playframework-14280/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8dbbd59f1db2efda785a9fe1678d73aa5454e42b --- /dev/null +++ b/tasks/playframework__playframework-14280/tests/oracle.patch @@ -0,0 +1,53 @@ +diff --git a/documentation/project/plugins.sbt b/documentation/project/plugins.sbt +index 8971ec00a7..e9587d8fc3 100644 +--- a/documentation/project/plugins.sbt ++++ b/documentation/project/plugins.sbt +@@ -10,7 +10,7 @@ lazy val plugins = (project in file(".")).dependsOn(playDocsPlugin) + lazy val playDocsPlugin = ProjectRef(Path.fileProperty("user.dir").getParentFile, "Play-Docs-Sbt-Plugin") + + // Required for Production.md +-addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.1") ++addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.4.2") + + // Add headers to example sources + addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..1aff12f793 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -29,7 +29,7 @@ object Dependencies { + "org.scalacheck" %% "scalacheck" % "1.20.0" % Test + ) + +- val jacksonVersion = "2.22.2" ++ val jacksonVersion = "2.22.3" + val jacksonDatabind = Seq("com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion) + val jacksons = Seq( + "com.fasterxml.jackson.core" % "jackson-core", +@@ -46,7 +46,7 @@ object Dependencies { + + val playJson = "org.playframework" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.18" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -108,7 +108,7 @@ object Dependencies { + ) ++ specs2Deps.map(_ % Test) + + val joda = Seq( +- "joda-time" % "joda-time" % "2.14.3", ++ "joda-time" % "joda-time" % "2.14.4", + "org.joda" % "joda-convert" % "3.0.1" + ) + +@@ -177,7 +177,7 @@ object Dependencies { + + val cookieEncodingDependencies = slf4j + +- val jimfs = "com.google.jimfs" % "jimfs" % "1.3.1" ++ val jimfs = "com.google.jimfs" % "jimfs" % "1.3.2" + + val okHttp = "com.squareup.okhttp3" % "okhttp-jvm" % "5.5.0" + diff --git a/tasks/playframework__playframework-14280/tests/test.sh b/tasks/playframework__playframework-14280/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..237036756b107f9c489e7b07ffd5a299ba2d54b5 --- /dev/null +++ b/tasks/playframework__playframework-14280/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 e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e > "$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/playframework__playframework-14280/tests/verifier.py b/tasks/playframework__playframework-14280/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14280/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/playframework__playframework-14284/environment/Dockerfile b/tasks/playframework__playframework-14284/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aafdc42b544f8f4fbe25dc82d90da66110faa914 --- /dev/null +++ b/tasks/playframework__playframework-14284/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 117f9cb054c755b30bea852f8e6c2ee562ef6747 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 117f9cb054c755b30bea852f8e6c2ee562ef6747 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 117f9cb054c755b30bea852f8e6c2ee562ef6747 \ + && 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/playframework__playframework-14284/instruction.md b/tasks/playframework__playframework-14284/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34b767e8f42f7b8cc828ea32482b0cdd0a1fcabd --- /dev/null +++ b/tasks/playframework__playframework-14284/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [2.9.x] hibernate-core 6.6.58.Final (was 6.6.56.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.56.Final` to `6.6.58.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `117f9cb054c7`. 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/playframework__playframework-14284/solution/patch.diff b/tasks/playframework__playframework-14284/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..728a2a8e9df69c4cd54d2e17f659c27eab73cd10 --- /dev/null +++ b/tasks/playframework__playframework-14284/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index ec56afe9bf..7b0ae21647 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index a013d51615..e3d590999b 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 2ec09ac0c1..a31c61616a 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -117,7 +117,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14284/solution/solve.sh b/tasks/playframework__playframework-14284/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14284/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/playframework__playframework-14284/task.toml b/tasks/playframework__playframework-14284/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0bee366a4facb7b48ba8ca092085bda84c58dfea --- /dev/null +++ b/tasks/playframework__playframework-14284/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14284" +description = "[2.9.x] hibernate-core 6.6.58.Final (was 6.6.56.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "117f9cb054c755b30bea852f8e6c2ee562ef6747" +reference = "https://github.com/playframework/playframework/pull/14284" +source_access = "auto" +built_at = "2026-11-16T16:09:46.518969+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8c70d829370663dc9d3f43cbdd2f001c4b9b13465365b3e29882022ecd0882aa" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:13:50Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.539406+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:63c8443d47fd97a2485b27897523050f5df59ed67d52f85158dbc970b9069ba2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14284/tests/capture.py b/tasks/playframework__playframework-14284/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14284/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/playframework__playframework-14284/tests/instruction.md b/tasks/playframework__playframework-14284/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34b767e8f42f7b8cc828ea32482b0cdd0a1fcabd --- /dev/null +++ b/tasks/playframework__playframework-14284/tests/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [2.9.x] hibernate-core 6.6.58.Final (was 6.6.56.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.56.Final` to `6.6.58.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `117f9cb054c7`. 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/playframework__playframework-14284/tests/oracle.patch b/tasks/playframework__playframework-14284/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..728a2a8e9df69c4cd54d2e17f659c27eab73cd10 --- /dev/null +++ b/tasks/playframework__playframework-14284/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index ec56afe9bf..7b0ae21647 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index a013d51615..e3d590999b 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 2ec09ac0c1..a31c61616a 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -117,7 +117,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14284/tests/test.sh b/tasks/playframework__playframework-14284/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e45b3ae209bc31ae48d4a4bee97bda806ac28d7e --- /dev/null +++ b/tasks/playframework__playframework-14284/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 117f9cb054c755b30bea852f8e6c2ee562ef6747 > "$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/playframework__playframework-14284/tests/verifier.py b/tasks/playframework__playframework-14284/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14284/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/playframework__playframework-14285/environment/Dockerfile b/tasks/playframework__playframework-14285/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aafdc42b544f8f4fbe25dc82d90da66110faa914 --- /dev/null +++ b/tasks/playframework__playframework-14285/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 117f9cb054c755b30bea852f8e6c2ee562ef6747 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 117f9cb054c755b30bea852f8e6c2ee562ef6747 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 117f9cb054c755b30bea852f8e6c2ee562ef6747 \ + && 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/playframework__playframework-14285/instruction.md b/tasks/playframework__playframework-14285/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4bc7d02a51ceb3d0959b19b8eb5f8e8db36b3b9 --- /dev/null +++ b/tasks/playframework__playframework-14285/instruction.md @@ -0,0 +1,185 @@ +# Issue + +**Title:** [2.9.x] Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [at.yawk.lz4:lz4-java](https://github.com/yawkat/lz4-java) from `1.11.2` to `1.11.3` + + 📜 [GitHub Release Notes](https://github.com/yawkat/lz4-java/releases/tag/v1.11.3) - [Version Diff](https://github.com/yawkat/lz4-java/compare/v1.11.2...v1.11.3) +* 📦 [com.typesafe.netty:netty-reactive-streams-http](https://github.com/playframework/netty-reactive-streams) from `2.0.19` to `2.0.20` +* 📦 [com.typesafe.play:play-ahc-ws-standalone](https://github.com/playframework/play-ws) from `2.2.17` to `2.2.18` + + 📜 [GitHub Release Notes](https://github.com/playframework/play-ws/releases/tag/2.2.18) - [Version Diff](https://github.com/playframework/play-ws/compare/2.2.17...2.2.18) +* 📦 org.slf4j:jcl-over-slf4j from `2.0.19` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "at.yawk.lz4", artifactId = "lz4-java" }, + { groupId = "com.typesafe.netty", artifactId = "netty-reactive-streams-http" }, + { groupId = "com.typesafe.play", artifactId = "play-ahc-ws-standalone" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "at.yawk.lz4", artifactId = "lz4-java" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.typesafe.netty", artifactId = "netty-reactive-streams-http" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.typesafe.play", artifactId = "play-ahc-ws-standalone" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:4 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `117f9cb054c7`. 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/playframework__playframework-14285/solution/patch.diff b/tasks/playframework__playframework-14285/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..37a6ce6a1c24cdac48dc3345ac340aa145da61ee --- /dev/null +++ b/tasks/playframework__playframework-14285/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 2ec09ac0c1..a1c9cd5b20 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -77,7 +77,7 @@ object Dependencies { + + val playJson = "com.typesafe.play" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.19" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -183,7 +183,7 @@ object Dependencies { + .map("com.typesafe.akka" %% _ % akkaVersion) + .map(_.forScala3TestsUse2_13()) + .map(_.excludeAll(ExclusionRule("org.lz4"))) ++ Seq( +- "at.yawk.lz4" % "lz4-java" % "1.11.2" // CVE‐2025‐12183 + CVE-2025-66566 ++ "at.yawk.lz4" % "lz4-java" % "1.11.3" // CVE‐2025‐12183 + CVE-2025-66566 + ) ++ + Seq("akka-testkit", "akka-actor-testkit-typed") + .map("com.typesafe.akka" %% _ % akkaVersion % Test) +@@ -204,7 +204,7 @@ object Dependencies { + val nettyVersion = "4.1.138.Final" + + val netty = Seq( +- "com.typesafe.netty" % "netty-reactive-streams-http" % "2.0.19", ++ "com.typesafe.netty" % "netty-reactive-streams-http" % "2.0.20", + "io.netty" % "netty-codec-http" % nettyVersion, // increases transitive Netty dependency version ... + "io.netty" % "netty-handler" % nettyVersion, // ... pulled in by netty-reactive-streams-http + // Provide various Linux native transport dependencies. Netty automatically loads the correct native library +@@ -337,7 +337,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi + +- val playWsStandaloneVersion = "2.2.17" ++ val playWsStandaloneVersion = "2.2.18" + val playWsDeps = Seq( + ("com.typesafe.play" %% "play-ws-standalone" % playWsStandaloneVersion).forScala3TestsExcludeAkkaOrganization(), + ("com.typesafe.play" %% "play-ws-standalone-xml" % playWsStandaloneVersion).forScala3TestsExcludeAkkaOrganization(), diff --git a/tasks/playframework__playframework-14285/solution/solve.sh b/tasks/playframework__playframework-14285/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14285/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/playframework__playframework-14285/task.toml b/tasks/playframework__playframework-14285/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a594e7041ba30c029325fa686526e287eafe0262 --- /dev/null +++ b/tasks/playframework__playframework-14285/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14285" +description = "[2.9.x] Patch updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "117f9cb054c755b30bea852f8e6c2ee562ef6747" +reference = "https://github.com/playframework/playframework/pull/14285" +source_access = "auto" +built_at = "2026-11-16T16:09:46.525366+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b0e3823fc899695d1eeab5a87b790a5cb7b6e296798fd3a9ca933a258508d82e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:03:40Z" +diff_format = "unified" +context_files = [ + "project/Dependencies.scala", +] +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:02.539984+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:63c8443d47fd97a2485b27897523050f5df59ed67d52f85158dbc970b9069ba2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14285/tests/capture.py b/tasks/playframework__playframework-14285/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14285/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/playframework__playframework-14285/tests/instruction.md b/tasks/playframework__playframework-14285/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f4bc7d02a51ceb3d0959b19b8eb5f8e8db36b3b9 --- /dev/null +++ b/tasks/playframework__playframework-14285/tests/instruction.md @@ -0,0 +1,185 @@ +# Issue + +**Title:** [2.9.x] Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [at.yawk.lz4:lz4-java](https://github.com/yawkat/lz4-java) from `1.11.2` to `1.11.3` + + 📜 [GitHub Release Notes](https://github.com/yawkat/lz4-java/releases/tag/v1.11.3) - [Version Diff](https://github.com/yawkat/lz4-java/compare/v1.11.2...v1.11.3) +* 📦 [com.typesafe.netty:netty-reactive-streams-http](https://github.com/playframework/netty-reactive-streams) from `2.0.19` to `2.0.20` +* 📦 [com.typesafe.play:play-ahc-ws-standalone](https://github.com/playframework/play-ws) from `2.2.17` to `2.2.18` + + 📜 [GitHub Release Notes](https://github.com/playframework/play-ws/releases/tag/2.2.18) - [Version Diff](https://github.com/playframework/play-ws/compare/2.2.17...2.2.18) +* 📦 org.slf4j:jcl-over-slf4j from `2.0.19` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "at.yawk.lz4", artifactId = "lz4-java" }, + { groupId = "com.typesafe.netty", artifactId = "netty-reactive-streams-http" }, + { groupId = "com.typesafe.play", artifactId = "play-ahc-ws-standalone" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "at.yawk.lz4", artifactId = "lz4-java" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.typesafe.netty", artifactId = "netty-reactive-streams-http" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.typesafe.play", artifactId = "play-ahc-ws-standalone" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:4 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `117f9cb054c7`. 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/playframework__playframework-14285/tests/oracle.patch b/tasks/playframework__playframework-14285/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..37a6ce6a1c24cdac48dc3345ac340aa145da61ee --- /dev/null +++ b/tasks/playframework__playframework-14285/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 2ec09ac0c1..a1c9cd5b20 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -77,7 +77,7 @@ object Dependencies { + + val playJson = "com.typesafe.play" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.19" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -183,7 +183,7 @@ object Dependencies { + .map("com.typesafe.akka" %% _ % akkaVersion) + .map(_.forScala3TestsUse2_13()) + .map(_.excludeAll(ExclusionRule("org.lz4"))) ++ Seq( +- "at.yawk.lz4" % "lz4-java" % "1.11.2" // CVE‐2025‐12183 + CVE-2025-66566 ++ "at.yawk.lz4" % "lz4-java" % "1.11.3" // CVE‐2025‐12183 + CVE-2025-66566 + ) ++ + Seq("akka-testkit", "akka-actor-testkit-typed") + .map("com.typesafe.akka" %% _ % akkaVersion % Test) +@@ -204,7 +204,7 @@ object Dependencies { + val nettyVersion = "4.1.138.Final" + + val netty = Seq( +- "com.typesafe.netty" % "netty-reactive-streams-http" % "2.0.19", ++ "com.typesafe.netty" % "netty-reactive-streams-http" % "2.0.20", + "io.netty" % "netty-codec-http" % nettyVersion, // increases transitive Netty dependency version ... + "io.netty" % "netty-handler" % nettyVersion, // ... pulled in by netty-reactive-streams-http + // Provide various Linux native transport dependencies. Netty automatically loads the correct native library +@@ -337,7 +337,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi + +- val playWsStandaloneVersion = "2.2.17" ++ val playWsStandaloneVersion = "2.2.18" + val playWsDeps = Seq( + ("com.typesafe.play" %% "play-ws-standalone" % playWsStandaloneVersion).forScala3TestsExcludeAkkaOrganization(), + ("com.typesafe.play" %% "play-ws-standalone-xml" % playWsStandaloneVersion).forScala3TestsExcludeAkkaOrganization(), diff --git a/tasks/playframework__playframework-14285/tests/test.sh b/tasks/playframework__playframework-14285/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e45b3ae209bc31ae48d4a4bee97bda806ac28d7e --- /dev/null +++ b/tasks/playframework__playframework-14285/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 117f9cb054c755b30bea852f8e6c2ee562ef6747 > "$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/playframework__playframework-14285/tests/verifier.py b/tasks/playframework__playframework-14285/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14285/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/playframework__playframework-14289/environment/Dockerfile b/tasks/playframework__playframework-14289/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0c92f6f12ae9e6b40e2912082c8b383830c23a8b --- /dev/null +++ b/tasks/playframework__playframework-14289/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 69dbf805c095403fb13af747c2aea65cc92c7d5c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 69dbf805c095403fb13af747c2aea65cc92c7d5c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 69dbf805c095403fb13af747c2aea65cc92c7d5c \ + && 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/playframework__playframework-14289/instruction.md b/tasks/playframework__playframework-14289/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cf1e45f9aa68dc9b273c1fa730b781df136f567a --- /dev/null +++ b/tasks/playframework__playframework-14289/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [3.0.x] hibernate-core 6.6.58.Final (was 6.6.56.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.56.Final` to `6.6.58.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69dbf805c095`. 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/playframework__playframework-14289/solution/patch.diff b/tasks/playframework__playframework-14289/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c1be8ee4246f458ff5f01cc70dd52307df188d04 --- /dev/null +++ b/tasks/playframework__playframework-14289/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index ec56afe9bf..7b0ae21647 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index a013d51615..e3d590999b 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 4e39428d95..5d8b69ef69 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -101,7 +101,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14289/solution/solve.sh b/tasks/playframework__playframework-14289/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14289/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/playframework__playframework-14289/task.toml b/tasks/playframework__playframework-14289/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59d47f5de3d8c2a93e24a83cf2b91449aac0381a --- /dev/null +++ b/tasks/playframework__playframework-14289/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14289" +description = "[3.0.x] hibernate-core 6.6.58.Final (was 6.6.56.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "69dbf805c095403fb13af747c2aea65cc92c7d5c" +reference = "https://github.com/playframework/playframework/pull/14289" +source_access = "auto" +built_at = "2026-11-16T16:09:46.520579+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6e7261f3824a33189ebf0dfa1d415761d3505d8715d5282c487119c1cf0f4427" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:13:21Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.540521+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:71c0c566eea7afbf9861ce2d264fa1e6c42fdbfea7b7cfd276e3bb6c9fa92d8a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14289/tests/capture.py b/tasks/playframework__playframework-14289/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14289/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/playframework__playframework-14289/tests/instruction.md b/tasks/playframework__playframework-14289/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cf1e45f9aa68dc9b273c1fa730b781df136f567a --- /dev/null +++ b/tasks/playframework__playframework-14289/tests/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [3.0.x] hibernate-core 6.6.58.Final (was 6.6.56.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.56.Final` to `6.6.58.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69dbf805c095`. 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/playframework__playframework-14289/tests/oracle.patch b/tasks/playframework__playframework-14289/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c1be8ee4246f458ff5f01cc70dd52307df188d04 --- /dev/null +++ b/tasks/playframework__playframework-14289/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index ec56afe9bf..7b0ae21647 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index a013d51615..e3d590999b 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 4e39428d95..5d8b69ef69 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -101,7 +101,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.56.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14289/tests/test.sh b/tasks/playframework__playframework-14289/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ccf76f1348aa146bb6fa6c3e3528353d4cf61c4 --- /dev/null +++ b/tasks/playframework__playframework-14289/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 69dbf805c095403fb13af747c2aea65cc92c7d5c > "$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/playframework__playframework-14289/tests/verifier.py b/tasks/playframework__playframework-14289/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14289/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/playframework__playframework-14290/environment/Dockerfile b/tasks/playframework__playframework-14290/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0c92f6f12ae9e6b40e2912082c8b383830c23a8b --- /dev/null +++ b/tasks/playframework__playframework-14290/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 69dbf805c095403fb13af747c2aea65cc92c7d5c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 69dbf805c095403fb13af747c2aea65cc92c7d5c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 69dbf805c095403fb13af747c2aea65cc92c7d5c \ + && 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/playframework__playframework-14290/instruction.md b/tasks/playframework__playframework-14290/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4124094633556742c2453db9087b41e12c4ffec1 --- /dev/null +++ b/tasks/playframework__playframework-14290/instruction.md @@ -0,0 +1,185 @@ +# Issue + +**Title:** [3.0.x] Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [at.yawk.lz4:lz4-java](https://github.com/yawkat/lz4-java) from `1.11.2` to `1.11.3` + + 📜 [GitHub Release Notes](https://github.com/yawkat/lz4-java/releases/tag/v1.11.3) - [Version Diff](https://github.com/yawkat/lz4-java/compare/v1.11.2...v1.11.3) +* 📦 [org.playframework:play-ahc-ws-standalone](https://github.com/playframework/play-ws) from `3.0.13` to `3.0.14` + + 📜 [GitHub Release Notes](https://github.com/playframework/play-ws/releases/tag/3.0.14) - [Version Diff](https://github.com/playframework/play-ws/compare/3.0.13...3.0.14) +* 📦 [org.playframework.netty:netty-reactive-streams-http](https://github.com/playframework/netty-reactive-streams) from `3.0.9` to `3.0.10` +* 📦 org.slf4j:jcl-over-slf4j from `2.0.19` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "at.yawk.lz4", artifactId = "lz4-java" }, + { groupId = "org.playframework", artifactId = "play-ahc-ws-standalone" }, + { groupId = "org.playframework.netty", artifactId = "netty-reactive-streams-http" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "at.yawk.lz4", artifactId = "lz4-java" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.playframework", artifactId = "play-ahc-ws-standalone" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.playframework.netty", artifactId = "netty-reactive-streams-http" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:4 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69dbf805c095`. 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/playframework__playframework-14290/solution/patch.diff b/tasks/playframework__playframework-14290/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1396b03933aeb556e7db15b7e43f896420606ba3 --- /dev/null +++ b/tasks/playframework__playframework-14290/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 4e39428d95..daa75e0105 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -61,7 +61,7 @@ object Dependencies { + + val playJson = "org.playframework" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.19" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -166,7 +166,7 @@ object Dependencies { + Seq("pekko-actor", "pekko-actor-typed", "pekko-slf4j", "pekko-serialization-jackson") + .map("org.apache.pekko" %% _ % pekkoVersion) + .map(_.excludeAll(ExclusionRule("org.lz4"))) ++ Seq( +- "at.yawk.lz4" % "lz4-java" % "1.11.2" // CVE‐2025‐12183 + CVE-2025-66566 ++ "at.yawk.lz4" % "lz4-java" % "1.11.3" // CVE‐2025‐12183 + CVE-2025-66566 + ) ++ + Seq("pekko-testkit", "pekko-actor-testkit-typed") + .map("org.apache.pekko" %% _ % pekkoVersion % Test) ++ +@@ -184,7 +184,7 @@ object Dependencies { + val nettyVersion = "4.1.138.Final" + + val netty = Seq( +- "org.playframework.netty" % "netty-reactive-streams-http" % "3.0.9", ++ "org.playframework.netty" % "netty-reactive-streams-http" % "3.0.10", + "io.netty" % "netty-codec-http" % nettyVersion, // increases transitive Netty dependency version ... + "io.netty" % "netty-handler" % nettyVersion, // ... pulled in by netty-reactive-streams-http + // Provide various Linux native transport dependencies. Netty automatically loads the correct native library +@@ -311,7 +311,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi + +- val playWsStandaloneVersion = "3.0.13" ++ val playWsStandaloneVersion = "3.0.14" + val playWsDeps = Seq( + "org.playframework" %% "play-ws-standalone" % playWsStandaloneVersion, + "org.playframework" %% "play-ws-standalone-xml" % playWsStandaloneVersion, diff --git a/tasks/playframework__playframework-14290/solution/solve.sh b/tasks/playframework__playframework-14290/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14290/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/playframework__playframework-14290/task.toml b/tasks/playframework__playframework-14290/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1693620d5076fa6d25a78be45514cfc096cc8e7 --- /dev/null +++ b/tasks/playframework__playframework-14290/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14290" +description = "[3.0.x] Patch updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "69dbf805c095403fb13af747c2aea65cc92c7d5c" +reference = "https://github.com/playframework/playframework/pull/14290" +source_access = "auto" +built_at = "2026-11-16T16:09:46.522623+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:711fa16961805699065d3bbabb22343dfa1a09ea2ffe39ccce0309ee23e5abc3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:04:12Z" +diff_format = "unified" +context_files = [ + "project/Dependencies.scala", +] +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:02.541056+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:71c0c566eea7afbf9861ce2d264fa1e6c42fdbfea7b7cfd276e3bb6c9fa92d8a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14290/tests/capture.py b/tasks/playframework__playframework-14290/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14290/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/playframework__playframework-14290/tests/instruction.md b/tasks/playframework__playframework-14290/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4124094633556742c2453db9087b41e12c4ffec1 --- /dev/null +++ b/tasks/playframework__playframework-14290/tests/instruction.md @@ -0,0 +1,185 @@ +# Issue + +**Title:** [3.0.x] Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [at.yawk.lz4:lz4-java](https://github.com/yawkat/lz4-java) from `1.11.2` to `1.11.3` + + 📜 [GitHub Release Notes](https://github.com/yawkat/lz4-java/releases/tag/v1.11.3) - [Version Diff](https://github.com/yawkat/lz4-java/compare/v1.11.2...v1.11.3) +* 📦 [org.playframework:play-ahc-ws-standalone](https://github.com/playframework/play-ws) from `3.0.13` to `3.0.14` + + 📜 [GitHub Release Notes](https://github.com/playframework/play-ws/releases/tag/3.0.14) - [Version Diff](https://github.com/playframework/play-ws/compare/3.0.13...3.0.14) +* 📦 [org.playframework.netty:netty-reactive-streams-http](https://github.com/playframework/netty-reactive-streams) from `3.0.9` to `3.0.10` +* 📦 org.slf4j:jcl-over-slf4j from `2.0.19` to `2.0.20` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/e81c5410e0afd3c58b4e1327786c527641de543c/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "at.yawk.lz4", artifactId = "lz4-java" }, + { groupId = "org.playframework", artifactId = "play-ahc-ws-standalone" }, + { groupId = "org.playframework.netty", artifactId = "netty-reactive-streams-http" }, + { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "at.yawk.lz4", artifactId = "lz4-java" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.playframework", artifactId = "play-ahc-ws-standalone" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.playframework.netty", artifactId = "netty-reactive-streams-http" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.slf4j", artifactId = "jcl-over-slf4j" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:4 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69dbf805c095`. 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/playframework__playframework-14290/tests/oracle.patch b/tasks/playframework__playframework-14290/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1396b03933aeb556e7db15b7e43f896420606ba3 --- /dev/null +++ b/tasks/playframework__playframework-14290/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 4e39428d95..daa75e0105 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -61,7 +61,7 @@ object Dependencies { + + val playJson = "org.playframework" %% "play-json" % playJsonVersion + +- val slf4jVersion = "2.0.19" ++ val slf4jVersion = "2.0.20" + val slf4j = Seq("slf4j-api", "jul-to-slf4j", "jcl-over-slf4j").map("org.slf4j" % _ % slf4jVersion) + val slf4jApi = "org.slf4j" % "slf4j-api" % slf4jVersion + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion +@@ -166,7 +166,7 @@ object Dependencies { + Seq("pekko-actor", "pekko-actor-typed", "pekko-slf4j", "pekko-serialization-jackson") + .map("org.apache.pekko" %% _ % pekkoVersion) + .map(_.excludeAll(ExclusionRule("org.lz4"))) ++ Seq( +- "at.yawk.lz4" % "lz4-java" % "1.11.2" // CVE‐2025‐12183 + CVE-2025-66566 ++ "at.yawk.lz4" % "lz4-java" % "1.11.3" // CVE‐2025‐12183 + CVE-2025-66566 + ) ++ + Seq("pekko-testkit", "pekko-actor-testkit-typed") + .map("org.apache.pekko" %% _ % pekkoVersion % Test) ++ +@@ -184,7 +184,7 @@ object Dependencies { + val nettyVersion = "4.1.138.Final" + + val netty = Seq( +- "org.playframework.netty" % "netty-reactive-streams-http" % "3.0.9", ++ "org.playframework.netty" % "netty-reactive-streams-http" % "3.0.10", + "io.netty" % "netty-codec-http" % nettyVersion, // increases transitive Netty dependency version ... + "io.netty" % "netty-handler" % nettyVersion, // ... pulled in by netty-reactive-streams-http + // Provide various Linux native transport dependencies. Netty automatically loads the correct native library +@@ -311,7 +311,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi + +- val playWsStandaloneVersion = "3.0.13" ++ val playWsStandaloneVersion = "3.0.14" + val playWsDeps = Seq( + "org.playframework" %% "play-ws-standalone" % playWsStandaloneVersion, + "org.playframework" %% "play-ws-standalone-xml" % playWsStandaloneVersion, diff --git a/tasks/playframework__playframework-14290/tests/test.sh b/tasks/playframework__playframework-14290/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ccf76f1348aa146bb6fa6c3e3528353d4cf61c4 --- /dev/null +++ b/tasks/playframework__playframework-14290/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 69dbf805c095403fb13af747c2aea65cc92c7d5c > "$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/playframework__playframework-14290/tests/verifier.py b/tasks/playframework__playframework-14290/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14290/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/playframework__playframework-14291/environment/Dockerfile b/tasks/playframework__playframework-14291/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f3c4c77b5cbc3f49c12cc51cfa4ae556dac7e045 --- /dev/null +++ b/tasks/playframework__playframework-14291/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && 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/playframework__playframework-14291/instruction.md b/tasks/playframework__playframework-14291/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a48d1744fb9b7e4719c6649934662f7c195bb76 --- /dev/null +++ b/tasks/playframework__playframework-14291/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Restore IOResult extractor matching for multipart file uploads + +## Description + +## Summary + +Restore extractor matching for Pekko Stream's `IOResult` in the multipart temporary-file handler. The typed matches and status guards were a workaround for calling a Scala 2 extractor from Scala 3. Play now uses native Scala 3 Pekko artifacts, whose `IOResult.unapply` has the expected signature, so the original failure/success patterns work again. + +This removes the workaround without changing the public API. + +## Verification + +- `Play / compile` passed on Scala 3.3.8 and Scala 2.13.18. +- `Play / scalafmtCheck` passed. +- `Play / testOnly play.api.mvc.MultipartBodyParserSpec` passed on both Scala versions. + +Prepared with OpenAI Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14291/solution/patch.diff b/tasks/playframework__playframework-14291/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1dea65a12525182fa51c2d6735f22969131cbecf --- /dev/null +++ b/tasks/playframework__playframework-14291/solution/patch.diff @@ -0,0 +1,35 @@ +diff --git a/core/play/src/main/scala/play/core/parsers/Multipart.scala b/core/play/src/main/scala/play/core/parsers/Multipart.scala +index f8d126d75f..4f2c0dd126 100644 +--- a/core/play/src/main/scala/play/core/parsers/Multipart.scala ++++ b/core/play/src/main/scala/play/core/parsers/Multipart.scala +@@ -11,6 +11,7 @@ import scala.collection.mutable.ListBuffer + import scala.concurrent.duration.Duration + import scala.concurrent.Await + import scala.concurrent.Future ++import scala.util.Failure + + import org.apache.pekko.stream.scaladsl._ + import org.apache.pekko.stream.stage._ +@@ -183,19 +184,15 @@ object Multipart { + case FileInfo(partName, filename, contentType, dispositionType) => + val tempFile = temporaryFileCreator.create("multipartBody", "asTemporaryFile") + Accumulator(FileIO.toPath(tempFile.path)).mapFuture { +- // Can't use unapply in Scala 3 here as long as we use the .cross(CrossVersion.for3Use2_13) workaround for pekko-http +- // That's because Scala 3 changed the unapply signature/behaviour and here we try to call unapply of a Scala 2 artifacts +- // from a Scala 3 artifact, which results in: +- // [error] java.lang.NoSuchMethodError: 'org.apache.pekko.stream.IOResult org.apache.pekko.stream.IOResult$.unapply(org.apache.pekko.stream.IOResult)' +- case r: IOResult if r.status.isFailure => Future.failed(r.status.failed.get) +- case r: IOResult if r.status.isSuccess => ++ case IOResult(_, Failure(error)) => Future.failed(error) ++ case IOResult(count, _) => + Future.successful( + FilePart( + partName, + filename, + contentType, + tempFile, +- r.count, ++ count, + dispositionType, + tf => Some(ByteString.fromArray(java.nio.file.Files.readAllBytes(tf.path))) + ) diff --git a/tasks/playframework__playframework-14291/solution/solve.sh b/tasks/playframework__playframework-14291/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14291/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/playframework__playframework-14291/task.toml b/tasks/playframework__playframework-14291/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a9ecc4ae81416b088df96e46952c79cdca6c8b9e --- /dev/null +++ b/tasks/playframework__playframework-14291/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14291" +description = "Restore IOResult extractor matching for multipart file uploads" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e" +reference = "https://github.com/playframework/playframework/pull/14291" +source_access = "auto" +built_at = "2026-11-16T16:09:46.530116+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2bc1cd63cf4a7863c9bb8b01cf173ef6bba4ac14518816bb8684d7ca6558a765" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T20:55:49Z" +diff_format = "unified" +context_files = [ + "core/play/src/main/scala/play/core/parsers/Multipart.scala", +] +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:02.541640+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3c569e88adc3407d0af5c618df23cc6c308180a5e144d96c776c7ecbec1f0676" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14291/tests/capture.py b/tasks/playframework__playframework-14291/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14291/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/playframework__playframework-14291/tests/instruction.md b/tasks/playframework__playframework-14291/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a48d1744fb9b7e4719c6649934662f7c195bb76 --- /dev/null +++ b/tasks/playframework__playframework-14291/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Restore IOResult extractor matching for multipart file uploads + +## Description + +## Summary + +Restore extractor matching for Pekko Stream's `IOResult` in the multipart temporary-file handler. The typed matches and status guards were a workaround for calling a Scala 2 extractor from Scala 3. Play now uses native Scala 3 Pekko artifacts, whose `IOResult.unapply` has the expected signature, so the original failure/success patterns work again. + +This removes the workaround without changing the public API. + +## Verification + +- `Play / compile` passed on Scala 3.3.8 and Scala 2.13.18. +- `Play / scalafmtCheck` passed. +- `Play / testOnly play.api.mvc.MultipartBodyParserSpec` passed on both Scala versions. + +Prepared with OpenAI Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14291/tests/oracle.patch b/tasks/playframework__playframework-14291/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1dea65a12525182fa51c2d6735f22969131cbecf --- /dev/null +++ b/tasks/playframework__playframework-14291/tests/oracle.patch @@ -0,0 +1,35 @@ +diff --git a/core/play/src/main/scala/play/core/parsers/Multipart.scala b/core/play/src/main/scala/play/core/parsers/Multipart.scala +index f8d126d75f..4f2c0dd126 100644 +--- a/core/play/src/main/scala/play/core/parsers/Multipart.scala ++++ b/core/play/src/main/scala/play/core/parsers/Multipart.scala +@@ -11,6 +11,7 @@ import scala.collection.mutable.ListBuffer + import scala.concurrent.duration.Duration + import scala.concurrent.Await + import scala.concurrent.Future ++import scala.util.Failure + + import org.apache.pekko.stream.scaladsl._ + import org.apache.pekko.stream.stage._ +@@ -183,19 +184,15 @@ object Multipart { + case FileInfo(partName, filename, contentType, dispositionType) => + val tempFile = temporaryFileCreator.create("multipartBody", "asTemporaryFile") + Accumulator(FileIO.toPath(tempFile.path)).mapFuture { +- // Can't use unapply in Scala 3 here as long as we use the .cross(CrossVersion.for3Use2_13) workaround for pekko-http +- // That's because Scala 3 changed the unapply signature/behaviour and here we try to call unapply of a Scala 2 artifacts +- // from a Scala 3 artifact, which results in: +- // [error] java.lang.NoSuchMethodError: 'org.apache.pekko.stream.IOResult org.apache.pekko.stream.IOResult$.unapply(org.apache.pekko.stream.IOResult)' +- case r: IOResult if r.status.isFailure => Future.failed(r.status.failed.get) +- case r: IOResult if r.status.isSuccess => ++ case IOResult(_, Failure(error)) => Future.failed(error) ++ case IOResult(count, _) => + Future.successful( + FilePart( + partName, + filename, + contentType, + tempFile, +- r.count, ++ count, + dispositionType, + tf => Some(ByteString.fromArray(java.nio.file.Files.readAllBytes(tf.path))) + ) diff --git a/tasks/playframework__playframework-14291/tests/test.sh b/tasks/playframework__playframework-14291/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..237036756b107f9c489e7b07ffd5a299ba2d54b5 --- /dev/null +++ b/tasks/playframework__playframework-14291/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 e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e > "$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/playframework__playframework-14291/tests/verifier.py b/tasks/playframework__playframework-14291/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14291/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/playframework__playframework-14292/environment/Dockerfile b/tasks/playframework__playframework-14292/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f3c4c77b5cbc3f49c12cc51cfa4ae556dac7e045 --- /dev/null +++ b/tasks/playframework__playframework-14292/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e \ + && 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/playframework__playframework-14292/instruction.md b/tasks/playframework__playframework-14292/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..360995cca3c16c37e3e1915722146865abc18ecf --- /dev/null +++ b/tasks/playframework__playframework-14292/instruction.md @@ -0,0 +1,97 @@ +# Issue + +**Title:** mockito-core 5.24.0 (was 5.23.0) + +## Description + +## About this PR +📦 Updates [org.mockito:mockito-core](https://github.com/mockito/mockito) from `5.23.0` to `5.24.0` + +📜 [GitHub Release Notes](https://github.com/mockito/mockito/releases/tag/v5.24.0) - [Version Diff](https://github.com/mockito/mockito/compare/v5.23.0...v5.24.0) + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/53df72cfbd45dfae6c2486be071bcd5fe2d19df4/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+🔍 Files still referring to the old version number + +The following files still refer to the old version number (5.23.0). +You might want to review and update them manually. +``` +dev-mode/gradle-plugin/gradle/libs.versions.toml +``` +
+
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.mockito", artifactId = "mockito-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.mockito", artifactId = "mockito-core" } +}] +``` +
+ + +labels: library-update, early-semver-minor, semver-spec-minor, old-version-remains, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14292/solution/patch.diff b/tasks/playframework__playframework-14292/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7a556a6e544124cb7b21133df8ce5d3ce6e1207e --- /dev/null +++ b/tasks/playframework__playframework-14292/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/documentation/build.sbt b/documentation/build.sbt +index b2f12a5c73..1a4dbd3690 100644 +--- a/documentation/build.sbt ++++ b/documentation/build.sbt +@@ -39,7 +39,7 @@ lazy val main = Project("Play-Documentation", file(".")) + libraryDependencies ++= Seq( + "com.typesafe" % "config" % "1.4.4" % Test, + "com.h2database" % "h2" % "2.5.250" % Test, +- "org.mockito" % "mockito-core" % "5.23.0" % Test, ++ "org.mockito" % "mockito-core" % "5.24.0" % Test, + "org.assertj" % "assertj-core" % "3.27.7" % Test, + // https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.9#including + ("net.logstash.logback" % "logstash-logback-encoder" % "9.0" % Test) +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..2ec190590e 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -52,7 +52,7 @@ object Dependencies { + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion + + val guava = "com.google.guava" % "guava" % "33.7.1-jre" +- val mockitoAll = "org.mockito" % "mockito-core" % "5.23.0" ++ val mockitoAll = "org.mockito" % "mockito-core" % "5.24.0" + + val jakartaInject = "jakarta.inject" % "jakarta.inject-api" % "2.0.1" + diff --git a/tasks/playframework__playframework-14292/solution/solve.sh b/tasks/playframework__playframework-14292/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14292/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/playframework__playframework-14292/task.toml b/tasks/playframework__playframework-14292/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10fb9550aa9793ad0ba3f21909a164d30f682e5a --- /dev/null +++ b/tasks/playframework__playframework-14292/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14292" +description = "mockito-core 5.24.0 (was 5.23.0)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e" +reference = "https://github.com/playframework/playframework/pull/14292" +source_access = "auto" +built_at = "2026-11-16T16:09:46.517338+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eb27bd57ef1a2dff2bd54677ac69150b3f4417ad73fa70ea1275758f062e0164" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T07:14:35Z" +diff_format = "unified" +context_files = [ + "documentation/build.sbt", + "project/Dependencies.scala", +] +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:02.542159+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3c569e88adc3407d0af5c618df23cc6c308180a5e144d96c776c7ecbec1f0676" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14292/tests/capture.py b/tasks/playframework__playframework-14292/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14292/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/playframework__playframework-14292/tests/instruction.md b/tasks/playframework__playframework-14292/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..360995cca3c16c37e3e1915722146865abc18ecf --- /dev/null +++ b/tasks/playframework__playframework-14292/tests/instruction.md @@ -0,0 +1,97 @@ +# Issue + +**Title:** mockito-core 5.24.0 (was 5.23.0) + +## Description + +## About this PR +📦 Updates [org.mockito:mockito-core](https://github.com/mockito/mockito) from `5.23.0` to `5.24.0` + +📜 [GitHub Release Notes](https://github.com/mockito/mockito/releases/tag/v5.24.0) - [Version Diff](https://github.com/mockito/mockito/compare/v5.23.0...v5.24.0) + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/53df72cfbd45dfae6c2486be071bcd5fe2d19df4/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+🔍 Files still referring to the old version number + +The following files still refer to the old version number (5.23.0). +You might want to review and update them manually. +``` +dev-mode/gradle-plugin/gradle/libs.versions.toml +``` +
+
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.mockito", artifactId = "mockito-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.mockito", artifactId = "mockito-core" } +}] +``` +
+ + +labels: library-update, early-semver-minor, semver-spec-minor, old-version-remains, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e1f3c2a92be8`. 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/playframework__playframework-14292/tests/oracle.patch b/tasks/playframework__playframework-14292/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7a556a6e544124cb7b21133df8ce5d3ce6e1207e --- /dev/null +++ b/tasks/playframework__playframework-14292/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/documentation/build.sbt b/documentation/build.sbt +index b2f12a5c73..1a4dbd3690 100644 +--- a/documentation/build.sbt ++++ b/documentation/build.sbt +@@ -39,7 +39,7 @@ lazy val main = Project("Play-Documentation", file(".")) + libraryDependencies ++= Seq( + "com.typesafe" % "config" % "1.4.4" % Test, + "com.h2database" % "h2" % "2.5.250" % Test, +- "org.mockito" % "mockito-core" % "5.23.0" % Test, ++ "org.mockito" % "mockito-core" % "5.24.0" % Test, + "org.assertj" % "assertj-core" % "3.27.7" % Test, + // https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.9#including + ("net.logstash.logback" % "logstash-logback-encoder" % "9.0" % Test) +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5c3e18854e..2ec190590e 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -52,7 +52,7 @@ object Dependencies { + val slf4jSimple = "org.slf4j" % "slf4j-simple" % slf4jVersion + + val guava = "com.google.guava" % "guava" % "33.7.1-jre" +- val mockitoAll = "org.mockito" % "mockito-core" % "5.23.0" ++ val mockitoAll = "org.mockito" % "mockito-core" % "5.24.0" + + val jakartaInject = "jakarta.inject" % "jakarta.inject-api" % "2.0.1" + diff --git a/tasks/playframework__playframework-14292/tests/test.sh b/tasks/playframework__playframework-14292/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..237036756b107f9c489e7b07ffd5a299ba2d54b5 --- /dev/null +++ b/tasks/playframework__playframework-14292/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 e1f3c2a92be8aa8b2f853d7d3175955efbe18a1e > "$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/playframework__playframework-14292/tests/verifier.py b/tasks/playframework__playframework-14292/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14292/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/playframework__playframework-14300/environment/Dockerfile b/tasks/playframework__playframework-14300/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d6d2474195379578d472322dba8ca82a5208fe1b --- /dev/null +++ b/tasks/playframework__playframework-14300/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 880c58c2d01c39f1b077dfe3f8c7e34bcdd2d5ec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 880c58c2d01c39f1b077dfe3f8c7e34bcdd2d5ec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 880c58c2d01c39f1b077dfe3f8c7e34bcdd2d5ec \ + && 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/playframework__playframework-14300/instruction.md b/tasks/playframework__playframework-14300/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7204fa5fda60801ffdbc8007f6e3831598441eb8 --- /dev/null +++ b/tasks/playframework__playframework-14300/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.11.Final (was 7.4.10.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.10.Final` to `7.4.11.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/6bad96dbcdf22d1c2cd2c5e9b97959cc001d3edd/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `880c58c2d01c`. 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/playframework__playframework-14300/solution/patch.diff b/tasks/playframework__playframework-14300/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5c9d789b63466a01fca5cd33ba63fe2b96111b41 --- /dev/null +++ b/tasks/playframework__playframework-14300/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 5341d0a198..c9a24b3286 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 858ae034ba..53be40a7be 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 736a1a7470..93df22b945 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.10.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.11.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14300/solution/solve.sh b/tasks/playframework__playframework-14300/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14300/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/playframework__playframework-14300/task.toml b/tasks/playframework__playframework-14300/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d2a02009b82a8b90704a3fabd47f0c40d180eb5 --- /dev/null +++ b/tasks/playframework__playframework-14300/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14300" +description = "hibernate-core, ... 7.4.11.Final (was 7.4.10.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "880c58c2d01c39f1b077dfe3f8c7e34bcdd2d5ec" +reference = "https://github.com/playframework/playframework/pull/14300" +source_access = "auto" +built_at = "2026-11-16T16:09:46.513882+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:aa36ce73af443a5aeff7847085c82ad9d690bf4345c2b9c04effce73468ba129" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-27T14:58:51Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.542723+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:343c276f8a7a16aa8059d333ff4e23f657ee3cc86d5271ba832696f656026792" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14300/tests/capture.py b/tasks/playframework__playframework-14300/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14300/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/playframework__playframework-14300/tests/instruction.md b/tasks/playframework__playframework-14300/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7204fa5fda60801ffdbc8007f6e3831598441eb8 --- /dev/null +++ b/tasks/playframework__playframework-14300/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.11.Final (was 7.4.10.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.10.Final` to `7.4.11.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/6bad96dbcdf22d1c2cd2c5e9b97959cc001d3edd/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `880c58c2d01c`. 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/playframework__playframework-14300/tests/oracle.patch b/tasks/playframework__playframework-14300/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5c9d789b63466a01fca5cd33ba63fe2b96111b41 --- /dev/null +++ b/tasks/playframework__playframework-14300/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 5341d0a198..c9a24b3286 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 858ae034ba..53be40a7be 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 736a1a7470..93df22b945 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.10.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.10.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.11.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14300/tests/test.sh b/tasks/playframework__playframework-14300/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..63034baab1319a97b771166f4122af54a83f1544 --- /dev/null +++ b/tasks/playframework__playframework-14300/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 880c58c2d01c39f1b077dfe3f8c7e34bcdd2d5ec > "$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/playframework__playframework-14300/tests/verifier.py b/tasks/playframework__playframework-14300/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14300/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/playframework__playframework-14303/environment/Dockerfile b/tasks/playframework__playframework-14303/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0f08f370bf0a02abc82df06f4b3e0fa998f04de5 --- /dev/null +++ b/tasks/playframework__playframework-14303/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 77db0e4ef450d68a77670f5c76d3b82cff1a8ba3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 77db0e4ef450d68a77670f5c76d3b82cff1a8ba3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 77db0e4ef450d68a77670f5c76d3b82cff1a8ba3 \ + && 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/playframework__playframework-14303/instruction.md b/tasks/playframework__playframework-14303/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f19eb57659bdb4273b07f46be83e4fef09dd4b5 --- /dev/null +++ b/tasks/playframework__playframework-14303/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Latest sbt nightly + Scala 3.10.0-RC3 + +## 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 `77db0e4ef450`. 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/playframework__playframework-14303/solution/patch.diff b/tasks/playframework__playframework-14303/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1477d4b48a1ac81599fcf7d0bafd1f4fcc348b33 --- /dev/null +++ b/tasks/playframework__playframework-14303/solution/patch.diff @@ -0,0 +1,53 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 00929a5878..295ce51b06 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.12.15", "2.1.0-bin-20260921-2124f13-NIGHTLY" ], ++ "sbt": [ "1.12.15", "2.1.0-bin-20260928-0a70458-NIGHTLY" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index 8a81b210b4..a36e407df5 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-bin-20260921-2124f13-NIGHTLY ++sbt.version=2.1.0-bin-20260928-0a70458-NIGHTLY +diff --git a/project/Versions.scala b/project/Versions.scala +index 4c02676d2f..aee5fe7d65 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -7,7 +7,7 @@ object ScalaVersions { + val scala213Version = "2.13.18" + val scala33LTSVersion = "3.3.8" + val scala39LTSVersion = "3.9.0" +- val scala3NextVersion = "3.10.0-RC2" ++ val scala3NextVersion = "3.10.0-RC3" + + val publishedScalaVersions = Seq(scala213Version, scala33LTSVersion) + val testedScalaVersions = +@@ -25,5 +25,5 @@ object ScalaVersions { + + object SbtVersions { + val sbt1 = "1.12.15" +- val sbt2 = "2.1.0-bin-20260921-2124f13-NIGHTLY" ++ val sbt2 = "2.1.0-bin-20260928-0a70458-NIGHTLY" + } +diff --git a/project/build.properties b/project/build.properties +index b4b72318f4..40747f4584 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-bin-20260921-2124f13-NIGHTLY ++sbt.version=2.1.0-bin-20260928-0a70458-NIGHTLY diff --git a/tasks/playframework__playframework-14303/solution/solve.sh b/tasks/playframework__playframework-14303/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14303/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/playframework__playframework-14303/task.toml b/tasks/playframework__playframework-14303/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0e7d1846b344618dbc18fa59c93f6fb3265bd1e5 --- /dev/null +++ b/tasks/playframework__playframework-14303/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14303" +description = "Latest sbt nightly + Scala 3.10.0-RC3" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "77db0e4ef450d68a77670f5c76d3b82cff1a8ba3" +reference = "https://github.com/playframework/playframework/pull/14303" +source_access = "auto" +built_at = "2026-11-16T16:09:46.512408+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5387b520066d7a1e86dd75ea041229fe39dfb86b1b0a947377ccf9c824c2a879" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T17:01:19Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-test.yml", + "documentation/project/build.properties", + "project/Versions.scala", + "project/build.properties", +] +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:02.543256+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:34ebca29375a7ee35776ada4fbcf8ddb1c1fd3f723dad4d65cd560a320dab9a6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14303/tests/capture.py b/tasks/playframework__playframework-14303/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14303/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/playframework__playframework-14303/tests/instruction.md b/tasks/playframework__playframework-14303/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f19eb57659bdb4273b07f46be83e4fef09dd4b5 --- /dev/null +++ b/tasks/playframework__playframework-14303/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Latest sbt nightly + Scala 3.10.0-RC3 + +## 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 `77db0e4ef450`. 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/playframework__playframework-14303/tests/oracle.patch b/tasks/playframework__playframework-14303/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1477d4b48a1ac81599fcf7d0bafd1f4fcc348b33 --- /dev/null +++ b/tasks/playframework__playframework-14303/tests/oracle.patch @@ -0,0 +1,53 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 00929a5878..295ce51b06 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.12.15", "2.1.0-bin-20260921-2124f13-NIGHTLY" ], ++ "sbt": [ "1.12.15", "2.1.0-bin-20260928-0a70458-NIGHTLY" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index 8a81b210b4..a36e407df5 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-bin-20260921-2124f13-NIGHTLY ++sbt.version=2.1.0-bin-20260928-0a70458-NIGHTLY +diff --git a/project/Versions.scala b/project/Versions.scala +index 4c02676d2f..aee5fe7d65 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -7,7 +7,7 @@ object ScalaVersions { + val scala213Version = "2.13.18" + val scala33LTSVersion = "3.3.8" + val scala39LTSVersion = "3.9.0" +- val scala3NextVersion = "3.10.0-RC2" ++ val scala3NextVersion = "3.10.0-RC3" + + val publishedScalaVersions = Seq(scala213Version, scala33LTSVersion) + val testedScalaVersions = +@@ -25,5 +25,5 @@ object ScalaVersions { + + object SbtVersions { + val sbt1 = "1.12.15" +- val sbt2 = "2.1.0-bin-20260921-2124f13-NIGHTLY" ++ val sbt2 = "2.1.0-bin-20260928-0a70458-NIGHTLY" + } +diff --git a/project/build.properties b/project/build.properties +index b4b72318f4..40747f4584 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-bin-20260921-2124f13-NIGHTLY ++sbt.version=2.1.0-bin-20260928-0a70458-NIGHTLY diff --git a/tasks/playframework__playframework-14303/tests/test.sh b/tasks/playframework__playframework-14303/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fcc463433a9f614add8d05da259e6c1ea832c47 --- /dev/null +++ b/tasks/playframework__playframework-14303/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 77db0e4ef450d68a77670f5c76d3b82cff1a8ba3 > "$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/playframework__playframework-14303/tests/verifier.py b/tasks/playframework__playframework-14303/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14303/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/playframework__playframework-14315/environment/Dockerfile b/tasks/playframework__playframework-14315/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0801700f9ca4ee7726f4f97e625bc302142a12ab --- /dev/null +++ b/tasks/playframework__playframework-14315/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 53f31694fedffaef85462ba3061f349916353d1f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 53f31694fedffaef85462ba3061f349916353d1f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 53f31694fedffaef85462ba3061f349916353d1f \ + && 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/playframework__playframework-14315/instruction.md b/tasks/playframework__playframework-14315/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03dc42b8b7504cd0a8f2c285155235398973edd8 --- /dev/null +++ b/tasks/playframework__playframework-14315/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** [2.9.x] Fix reverse router for OptionalInt/Long/Double query params (backport #14252) by @arimu1 + +## Description + +## Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? +* [x] Have you added copyright headers to new files? (N/A — no new files) +* [x] Have you checked that both Scala and Java APIs are updated? +* [x] Have you updated the documentation for both Scala and Java sections? (N/A — bugfix only) +* [x] Have you added tests for any changed functionality? + +## Fixes + +## Purpose + +Backport of #12995 to the `3.0.x` branch. `QueryStringBindable` for `java.util.OptionalInt`, `OptionalLong`, and `OptionalDouble` used `value.toScala.getOrElse(0).toString` in `unbind`, which dropped the query parameter name and produced invalid reversed URLs (e.g. `?111` instead of `?key=111`). + +The fix delegates `unbind` to the existing boxed `Integer` / `Long` / `Double` binders when a value is present, matching `Optional[T]` behavior. + +## Background Context + +This is a straight backport of the merged main-line fix; no API or behavioral changes beyond correcting reverse routing for these Java optional primitive types. + +## References + +- #14244 — [3.0.x] Wrong unbind method for OptionalInt, OptionalLong, OptionalDouble +- #12995 — Fix reverse router for `Optional[Int|Long|Double]` type of query param (merged on `main`) + +## Test plan + +- [x] `sbt "project Play" "Test / testOnly play.api.mvc.BindersSpec"` (55 examples, 0 failures) +- [x] Added `RouterSpec` reverse-route assertions from #12995 (routes-compiler sbt scripted test)
This is an automatic backport of pull request #14252 done by [Mergify](https://mergify.com). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53f31694fedf`. 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/playframework__playframework-14315/solution/patch.diff b/tasks/playframework__playframework-14315/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5506a0063417575ebd82e599c9fdff6ef9068430 --- /dev/null +++ b/tasks/playframework__playframework-14315/solution/patch.diff @@ -0,0 +1,71 @@ +diff --git a/core/play/src/main/scala/play/api/mvc/Binders.scala b/core/play/src/main/scala/play/api/mvc/Binders.scala +index 39d10fd7a1..5e31b1616a 100644 +--- a/core/play/src/main/scala/play/api/mvc/Binders.scala ++++ b/core/play/src/main/scala/play/api/mvc/Binders.scala +@@ -505,8 +505,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalInt.empty)) + ) + } +- def unbind(key: String, value: OptionalInt) = value.toScala.getOrElse(0).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalInt) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Integer]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + /** +@@ -521,8 +522,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalLong.empty)) + ) + } +- def unbind(key: String, value: OptionalLong) = value.toScala.getOrElse(0L).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalLong) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Long]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + /** +@@ -538,8 +540,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalDouble.empty)) + ) + } +- def unbind(key: String, value: OptionalDouble) = value.toScala.getOrElse(0.0).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalDouble) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Double]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + private def javascriptUnbindOption(jsUnbindT: String) = "function(k,v){return v!=null?(" + jsUnbindT + ")(k,v):''}" +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala +index 67745e7d8a..7385282cf1 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala +@@ -40,6 +40,26 @@ object RouterSpec extends PlaySpecification { + } + } + ++ "reverse routes containing Optional[Int|Long|Double] parameters" in { ++ "the query string" in { ++ controllers.routes.Application.takeOptionalInt(java.util.OptionalInt.of(789)).url must equalTo("/take-joptint?x=789") ++ controllers.routes.Application.takeOptionalInt(java.util.OptionalInt.empty()).url must equalTo("/take-joptint") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.empty()).url must equalTo("/take-joptint-d") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.of(123)).url must equalTo("/take-joptint-d") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.of(987)).url must equalTo("/take-joptint-d?x=987") ++ controllers.routes.Application.takeOptionalLong(java.util.OptionalLong.of(789L)).url must equalTo("/take-joptlong?x=789") ++ controllers.routes.Application.takeOptionalLong(java.util.OptionalLong.empty()).url must equalTo("/take-joptlong") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.empty()).url must equalTo("/take-joptlong-d") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.of(123L)).url must equalTo("/take-joptlong-d") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.of(987)).url must equalTo("/take-joptlong-d?x=987") ++ controllers.routes.Application.takeOptionalDouble(java.util.OptionalDouble.of(7.89)).url must equalTo("/take-joptdouble?x=7.89") ++ controllers.routes.Application.takeOptionalDouble(java.util.OptionalDouble.empty()).url must equalTo("/take-joptdouble") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.empty()).url must equalTo("/take-joptdouble-d") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.of(1.23)).url must equalTo("/take-joptdouble-d") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.of(9.87)).url must equalTo("/take-joptdouble-d?x=9.87") ++ } ++ } ++ + "bind boolean parameters" in { + "from the query string" in new WithApplication() { + override def running() = { diff --git a/tasks/playframework__playframework-14315/solution/solve.sh b/tasks/playframework__playframework-14315/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14315/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/playframework__playframework-14315/task.toml b/tasks/playframework__playframework-14315/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6eaf9343504b616c48963a69463ed34ebe71aa9b --- /dev/null +++ b/tasks/playframework__playframework-14315/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14315" +description = "[2.9.x] Fix reverse router for OptionalInt/Long/Double query params (backport #14252) by @arimu1" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "53f31694fedffaef85462ba3061f349916353d1f" +reference = "https://github.com/playframework/playframework/pull/14315" +source_access = "auto" +built_at = "2026-11-16T16:09:46.509289+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:38bbbad9217c550ddd339cce1678080134203f0be7773cab24f56eb9f266238f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-30T10:01:36Z" +diff_format = "unified" +context_files = [ + "core/play/src/main/scala/play/api/mvc/Binders.scala", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala", +] +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:02.543776+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9934d268a654fc53d66faf45199012949855a156dfeab682cdfbfbbcee9a3fd0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14315/tests/capture.py b/tasks/playframework__playframework-14315/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14315/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/playframework__playframework-14315/tests/instruction.md b/tasks/playframework__playframework-14315/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03dc42b8b7504cd0a8f2c285155235398973edd8 --- /dev/null +++ b/tasks/playframework__playframework-14315/tests/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** [2.9.x] Fix reverse router for OptionalInt/Long/Double query params (backport #14252) by @arimu1 + +## Description + +## Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? +* [x] Have you added copyright headers to new files? (N/A — no new files) +* [x] Have you checked that both Scala and Java APIs are updated? +* [x] Have you updated the documentation for both Scala and Java sections? (N/A — bugfix only) +* [x] Have you added tests for any changed functionality? + +## Fixes + +## Purpose + +Backport of #12995 to the `3.0.x` branch. `QueryStringBindable` for `java.util.OptionalInt`, `OptionalLong`, and `OptionalDouble` used `value.toScala.getOrElse(0).toString` in `unbind`, which dropped the query parameter name and produced invalid reversed URLs (e.g. `?111` instead of `?key=111`). + +The fix delegates `unbind` to the existing boxed `Integer` / `Long` / `Double` binders when a value is present, matching `Optional[T]` behavior. + +## Background Context + +This is a straight backport of the merged main-line fix; no API or behavioral changes beyond correcting reverse routing for these Java optional primitive types. + +## References + +- #14244 — [3.0.x] Wrong unbind method for OptionalInt, OptionalLong, OptionalDouble +- #12995 — Fix reverse router for `Optional[Int|Long|Double]` type of query param (merged on `main`) + +## Test plan + +- [x] `sbt "project Play" "Test / testOnly play.api.mvc.BindersSpec"` (55 examples, 0 failures) +- [x] Added `RouterSpec` reverse-route assertions from #12995 (routes-compiler sbt scripted test)
This is an automatic backport of pull request #14252 done by [Mergify](https://mergify.com). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53f31694fedf`. 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/playframework__playframework-14315/tests/oracle.patch b/tasks/playframework__playframework-14315/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5506a0063417575ebd82e599c9fdff6ef9068430 --- /dev/null +++ b/tasks/playframework__playframework-14315/tests/oracle.patch @@ -0,0 +1,71 @@ +diff --git a/core/play/src/main/scala/play/api/mvc/Binders.scala b/core/play/src/main/scala/play/api/mvc/Binders.scala +index 39d10fd7a1..5e31b1616a 100644 +--- a/core/play/src/main/scala/play/api/mvc/Binders.scala ++++ b/core/play/src/main/scala/play/api/mvc/Binders.scala +@@ -505,8 +505,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalInt.empty)) + ) + } +- def unbind(key: String, value: OptionalInt) = value.toScala.getOrElse(0).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalInt) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Integer]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + /** +@@ -521,8 +522,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalLong.empty)) + ) + } +- def unbind(key: String, value: OptionalLong) = value.toScala.getOrElse(0L).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalLong) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Long]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + /** +@@ -538,8 +540,9 @@ object QueryStringBindable extends QueryStringBindableMacros { + .getOrElse(Right(OptionalDouble.empty)) + ) + } +- def unbind(key: String, value: OptionalDouble) = value.toScala.getOrElse(0.0).toString +- override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) ++ def unbind(key: String, value: OptionalDouble) = ++ value.toScala.map(implicitly[QueryStringBindable[java.lang.Double]].unbind(key, _)).getOrElse("") ++ override def javascriptUnbind = javascriptUnbindOption(super.javascriptUnbind) + } + + private def javascriptUnbindOption(jsUnbindT: String) = "function(k,v){return v!=null?(" + jsUnbindT + ")(k,v):''}" +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala +index 67745e7d8a..7385282cf1 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/tests/RouterSpec.scala +@@ -40,6 +40,26 @@ object RouterSpec extends PlaySpecification { + } + } + ++ "reverse routes containing Optional[Int|Long|Double] parameters" in { ++ "the query string" in { ++ controllers.routes.Application.takeOptionalInt(java.util.OptionalInt.of(789)).url must equalTo("/take-joptint?x=789") ++ controllers.routes.Application.takeOptionalInt(java.util.OptionalInt.empty()).url must equalTo("/take-joptint") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.empty()).url must equalTo("/take-joptint-d") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.of(123)).url must equalTo("/take-joptint-d") ++ controllers.routes.Application.takeOptionalIntWithDefault(java.util.OptionalInt.of(987)).url must equalTo("/take-joptint-d?x=987") ++ controllers.routes.Application.takeOptionalLong(java.util.OptionalLong.of(789L)).url must equalTo("/take-joptlong?x=789") ++ controllers.routes.Application.takeOptionalLong(java.util.OptionalLong.empty()).url must equalTo("/take-joptlong") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.empty()).url must equalTo("/take-joptlong-d") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.of(123L)).url must equalTo("/take-joptlong-d") ++ controllers.routes.Application.takeOptionalLongWithDefault(java.util.OptionalLong.of(987)).url must equalTo("/take-joptlong-d?x=987") ++ controllers.routes.Application.takeOptionalDouble(java.util.OptionalDouble.of(7.89)).url must equalTo("/take-joptdouble?x=7.89") ++ controllers.routes.Application.takeOptionalDouble(java.util.OptionalDouble.empty()).url must equalTo("/take-joptdouble") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.empty()).url must equalTo("/take-joptdouble-d") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.of(1.23)).url must equalTo("/take-joptdouble-d") ++ controllers.routes.Application.takeOptionalDoubleWithDefault(java.util.OptionalDouble.of(9.87)).url must equalTo("/take-joptdouble-d?x=9.87") ++ } ++ } ++ + "bind boolean parameters" in { + "from the query string" in new WithApplication() { + override def running() = { diff --git a/tasks/playframework__playframework-14315/tests/test.sh b/tasks/playframework__playframework-14315/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..19238d79359dbf3effff4c66f3d0653fb35199da --- /dev/null +++ b/tasks/playframework__playframework-14315/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 53f31694fedffaef85462ba3061f349916353d1f > "$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/playframework__playframework-14315/tests/verifier.py b/tasks/playframework__playframework-14315/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14315/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/playframework__playframework-14330/environment/Dockerfile b/tasks/playframework__playframework-14330/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..99a9b9f68c542845a9ea6e2285d4bae8489a2be3 --- /dev/null +++ b/tasks/playframework__playframework-14330/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0170e351371db009463a48f41a43f7a69bf52143 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0170e351371db009463a48f41a43f7a69bf52143 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0170e351371db009463a48f41a43f7a69bf52143 \ + && 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/playframework__playframework-14330/instruction.md b/tasks/playframework__playframework-14330/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ffee3b3ac518456e3ce58842d93be5948d01501 --- /dev/null +++ b/tasks/playframework__playframework-14330/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.12.Final (was 7.4.11.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.11.Final` to `7.4.12.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/3dda7279d3db54a066b81223e9e1e07b2b3543d0/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0170e351371d`. 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/playframework__playframework-14330/solution/patch.diff b/tasks/playframework__playframework-14330/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0cbe19782a76448c35c0f212cba12374b8c01420 --- /dev/null +++ b/tasks/playframework__playframework-14330/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index c9a24b3286..9cf5266083 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 53be40a7be..335ab3a008 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index b5386a5653..c7f9c4f13d 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.11.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.12.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14330/solution/solve.sh b/tasks/playframework__playframework-14330/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14330/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/playframework__playframework-14330/task.toml b/tasks/playframework__playframework-14330/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8b33abc78462ce76c4f93281eb311b54ad0e4227 --- /dev/null +++ b/tasks/playframework__playframework-14330/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14330" +description = "hibernate-core, ... 7.4.12.Final (was 7.4.11.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "0170e351371db009463a48f41a43f7a69bf52143" +reference = "https://github.com/playframework/playframework/pull/14330" +source_access = "auto" +built_at = "2026-11-16T16:09:46.507529+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3ab9da5de0e4c748038adfe96d38118ced7caf0563727c082d95b64b4b024e76" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-04T20:55:37Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.544326+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:76939c2f8135341133ef98b403666a773ba7f97668fa67f7bf224ea8975fe449" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14330/tests/capture.py b/tasks/playframework__playframework-14330/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14330/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/playframework__playframework-14330/tests/instruction.md b/tasks/playframework__playframework-14330/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ffee3b3ac518456e3ce58842d93be5948d01501 --- /dev/null +++ b/tasks/playframework__playframework-14330/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.12.Final (was 7.4.11.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.11.Final` to `7.4.12.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/3dda7279d3db54a066b81223e9e1e07b2b3543d0/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0170e351371d`. 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/playframework__playframework-14330/tests/oracle.patch b/tasks/playframework__playframework-14330/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0cbe19782a76448c35c0f212cba12374b8c01420 --- /dev/null +++ b/tasks/playframework__playframework-14330/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index c9a24b3286..9cf5266083 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 53be40a7be..335ab3a008 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index b5386a5653..c7f9c4f13d 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.11.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.11.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.12.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14330/tests/test.sh b/tasks/playframework__playframework-14330/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6eea10e5c4087db3f3e57417a2aa287ff27fbc77 --- /dev/null +++ b/tasks/playframework__playframework-14330/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 0170e351371db009463a48f41a43f7a69bf52143 > "$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/playframework__playframework-14330/tests/verifier.py b/tasks/playframework__playframework-14330/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14330/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/playframework__playframework-14339/environment/Dockerfile b/tasks/playframework__playframework-14339/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..34b2a413b9d8b503db72894caf63d6b6d7425740 --- /dev/null +++ b/tasks/playframework__playframework-14339/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 73a8172ce9f9e711eeccd43937890159bd04acff 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 73a8172ce9f9e711eeccd43937890159bd04acff \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 73a8172ce9f9e711eeccd43937890159bd04acff \ + && 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/playframework__playframework-14339/instruction.md b/tasks/playframework__playframework-14339/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fecd8e1991d6d63af5ff306c7d19822725c527aa --- /dev/null +++ b/tasks/playframework__playframework-14339/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Document accessing the database while the application starts + +## Description + +## Purpose + +In DEV mode, the application starts even if evolutions still need to be applied (since #8875), so that the evolutions page can be shown. Therefore, components that access the database while they get created can't rely on the schema being up to date. `ApplicationEvolutions.upToDate` exists for exactly that, but so far it was only explained in the 2.7 migration guide. + +This adds a section to the evolutions docs, with a Java and a Scala sample of a component that injects `ApplicationEvolutions` and only accesses the database if `upToDate` returns `true`. It also explains that applying (or resolving) the evolutions reloads the application, which creates the component again, as the `evolutions-auto-apply-false` scripted test verifies. + +## References + +- + +- playframework/play-ebean#65 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73a8172ce9f9`. 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/playframework__playframework-14339/solution/patch.diff b/tasks/playframework__playframework-14339/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aedf911e90c72fcd7b1d6dad9d8d9795fbbc4d53 --- /dev/null +++ b/tasks/playframework__playframework-14339/solution/patch.diff @@ -0,0 +1,85 @@ +diff --git a/documentation/manual/working/commonGuide/database/Evolutions.md b/documentation/manual/working/commonGuide/database/Evolutions.md +index 448da4899c..31e4ccae7e 100644 +--- a/documentation/manual/working/commonGuide/database/Evolutions.md ++++ b/documentation/manual/working/commonGuide/database/Evolutions.md +@@ -68,6 +68,18 @@ When evolutions are activated, Play will check your database schema state before + + If you agree with the SQL script, you can apply it directly by clicking on the ‘Apply evolutions’ button. + ++### Accessing the database while the application starts ++ ++In DEV mode, the application starts even if evolutions still need to be applied (unless `autoApply` is enabled, see [below](#Evolutions-configuration)), so that Play can show the page above. Therefore, a component that accesses the database while it gets created, e.g. to insert some initial data, can't rely on the database schema being up to date. Inject `ApplicationEvolutions` into such a component, so that Play checks (and, if `autoApply` is enabled, applies) the evolutions before creating it, and only access the database if `upToDate` returns `true`: ++ ++Java ++: @[startup-evolutions](code/jdatabase/StartupDataLoader.java) ++ ++Scala ++: @[startup-evolutions](code/sdatabase/StartupDataLoader.scala) ++ ++Once you apply (or resolve) the evolutions in the browser, Play reloads the application, which creates the component again, this time with `upToDate` returning `true`. ++ + ## Evolutions configuration + + Evolutions can be configured both globally and per datasource. For global configuration, keys should be prefixed with `play.evolutions`. For per datasource configuration, keys should be prefixed with `play.evolutions.db.`, for example `play.evolutions.db.default`. The following configuration options are supported: +diff --git a/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java b/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java +new file mode 100644 +index 0000000000..c14824853f +--- /dev/null ++++ b/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java +@@ -0,0 +1,27 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package jdatabase; ++ ++// #startup-evolutions ++import jakarta.inject.*; ++import play.api.db.evolutions.ApplicationEvolutions; ++import play.db.Database; ++ ++@Singleton ++public class StartupDataLoader { ++ ++ @Inject ++ public StartupDataLoader(Database db, ApplicationEvolutions evolutions) { ++ // Only access the schema once all evolutions have been applied. In DEV mode, applying them ++ // in the browser reloads the application, which creates this component again. ++ if (evolutions.upToDate()) { ++ db.withConnection( ++ connection -> { ++ // e.g. insert some initial data ++ }); ++ } ++ } ++} ++// #startup-evolutions +diff --git a/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala b/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala +new file mode 100644 +index 0000000000..19e4883079 +--- /dev/null ++++ b/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala +@@ -0,0 +1,23 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package sdatabase ++ ++//#startup-evolutions ++import jakarta.inject.Inject ++import jakarta.inject.Singleton ++import play.api.db.evolutions.ApplicationEvolutions ++import play.api.db.Database ++ ++@Singleton ++class StartupDataLoader @Inject() (db: Database, evolutions: ApplicationEvolutions) { ++ // Only access the schema once all evolutions have been applied. In DEV mode, applying them ++ // in the browser reloads the application, which creates this component again. ++ if (evolutions.upToDate) { ++ db.withConnection { connection => ++ // e.g. insert some initial data ++ } ++ } ++} ++//#startup-evolutions diff --git a/tasks/playframework__playframework-14339/solution/solve.sh b/tasks/playframework__playframework-14339/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14339/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/playframework__playframework-14339/task.toml b/tasks/playframework__playframework-14339/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5e0df495bd10907b72f19f013f2fc4bf2cdda75 --- /dev/null +++ b/tasks/playframework__playframework-14339/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14339" +description = "Document accessing the database while the application starts" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "73a8172ce9f9e711eeccd43937890159bd04acff" +reference = "https://github.com/playframework/playframework/pull/14339" +source_access = "auto" +built_at = "2026-11-16T16:09:46.505915+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ad1b4ec2ffd8c455fba87f4801966cdd42259f27407e5a77d66a3138e9c0d274" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T08:12:17Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/database/Evolutions.md", + "documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java", + "documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 62 +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:02.544862+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8f5d56b6231b51a717fea5f13a6257479dcf179696810eb60904eb080cdc6f23" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14339/tests/capture.py b/tasks/playframework__playframework-14339/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14339/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/playframework__playframework-14339/tests/instruction.md b/tasks/playframework__playframework-14339/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fecd8e1991d6d63af5ff306c7d19822725c527aa --- /dev/null +++ b/tasks/playframework__playframework-14339/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Document accessing the database while the application starts + +## Description + +## Purpose + +In DEV mode, the application starts even if evolutions still need to be applied (since #8875), so that the evolutions page can be shown. Therefore, components that access the database while they get created can't rely on the schema being up to date. `ApplicationEvolutions.upToDate` exists for exactly that, but so far it was only explained in the 2.7 migration guide. + +This adds a section to the evolutions docs, with a Java and a Scala sample of a component that injects `ApplicationEvolutions` and only accesses the database if `upToDate` returns `true`. It also explains that applying (or resolving) the evolutions reloads the application, which creates the component again, as the `evolutions-auto-apply-false` scripted test verifies. + +## References + +- + +- playframework/play-ebean#65 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73a8172ce9f9`. 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/playframework__playframework-14339/tests/oracle.patch b/tasks/playframework__playframework-14339/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..aedf911e90c72fcd7b1d6dad9d8d9795fbbc4d53 --- /dev/null +++ b/tasks/playframework__playframework-14339/tests/oracle.patch @@ -0,0 +1,85 @@ +diff --git a/documentation/manual/working/commonGuide/database/Evolutions.md b/documentation/manual/working/commonGuide/database/Evolutions.md +index 448da4899c..31e4ccae7e 100644 +--- a/documentation/manual/working/commonGuide/database/Evolutions.md ++++ b/documentation/manual/working/commonGuide/database/Evolutions.md +@@ -68,6 +68,18 @@ When evolutions are activated, Play will check your database schema state before + + If you agree with the SQL script, you can apply it directly by clicking on the ‘Apply evolutions’ button. + ++### Accessing the database while the application starts ++ ++In DEV mode, the application starts even if evolutions still need to be applied (unless `autoApply` is enabled, see [below](#Evolutions-configuration)), so that Play can show the page above. Therefore, a component that accesses the database while it gets created, e.g. to insert some initial data, can't rely on the database schema being up to date. Inject `ApplicationEvolutions` into such a component, so that Play checks (and, if `autoApply` is enabled, applies) the evolutions before creating it, and only access the database if `upToDate` returns `true`: ++ ++Java ++: @[startup-evolutions](code/jdatabase/StartupDataLoader.java) ++ ++Scala ++: @[startup-evolutions](code/sdatabase/StartupDataLoader.scala) ++ ++Once you apply (or resolve) the evolutions in the browser, Play reloads the application, which creates the component again, this time with `upToDate` returning `true`. ++ + ## Evolutions configuration + + Evolutions can be configured both globally and per datasource. For global configuration, keys should be prefixed with `play.evolutions`. For per datasource configuration, keys should be prefixed with `play.evolutions.db.`, for example `play.evolutions.db.default`. The following configuration options are supported: +diff --git a/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java b/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java +new file mode 100644 +index 0000000000..c14824853f +--- /dev/null ++++ b/documentation/manual/working/commonGuide/database/code/jdatabase/StartupDataLoader.java +@@ -0,0 +1,27 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package jdatabase; ++ ++// #startup-evolutions ++import jakarta.inject.*; ++import play.api.db.evolutions.ApplicationEvolutions; ++import play.db.Database; ++ ++@Singleton ++public class StartupDataLoader { ++ ++ @Inject ++ public StartupDataLoader(Database db, ApplicationEvolutions evolutions) { ++ // Only access the schema once all evolutions have been applied. In DEV mode, applying them ++ // in the browser reloads the application, which creates this component again. ++ if (evolutions.upToDate()) { ++ db.withConnection( ++ connection -> { ++ // e.g. insert some initial data ++ }); ++ } ++ } ++} ++// #startup-evolutions +diff --git a/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala b/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala +new file mode 100644 +index 0000000000..19e4883079 +--- /dev/null ++++ b/documentation/manual/working/commonGuide/database/code/sdatabase/StartupDataLoader.scala +@@ -0,0 +1,23 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package sdatabase ++ ++//#startup-evolutions ++import jakarta.inject.Inject ++import jakarta.inject.Singleton ++import play.api.db.evolutions.ApplicationEvolutions ++import play.api.db.Database ++ ++@Singleton ++class StartupDataLoader @Inject() (db: Database, evolutions: ApplicationEvolutions) { ++ // Only access the schema once all evolutions have been applied. In DEV mode, applying them ++ // in the browser reloads the application, which creates this component again. ++ if (evolutions.upToDate) { ++ db.withConnection { connection => ++ // e.g. insert some initial data ++ } ++ } ++} ++//#startup-evolutions diff --git a/tasks/playframework__playframework-14339/tests/test.sh b/tasks/playframework__playframework-14339/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a37c3551b1885674c09ec9bca2a2256ddb786f54 --- /dev/null +++ b/tasks/playframework__playframework-14339/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 73a8172ce9f9e711eeccd43937890159bd04acff > "$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/playframework__playframework-14339/tests/verifier.py b/tasks/playframework__playframework-14339/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14339/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/playframework__playframework-14340/environment/Dockerfile b/tasks/playframework__playframework-14340/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..275f1d961cf8cf6cdae39c1e92f29bbdaaf3b6da --- /dev/null +++ b/tasks/playframework__playframework-14340/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 65ebfe4c42f8e7170dc877f13dccfbd85ebbbb0e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 65ebfe4c42f8e7170dc877f13dccfbd85ebbbb0e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 65ebfe4c42f8e7170dc877f13dccfbd85ebbbb0e \ + && 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/playframework__playframework-14340/instruction.md b/tasks/playframework__playframework-14340/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eddd9ea70d6d8a1ba3bf4547cabd9b24ce146d43 --- /dev/null +++ b/tasks/playframework__playframework-14340/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Resolve an inconsistent database after a reload in dev mode + +## Description + +## Purpose + +In DEV mode, when applying an evolution fails, the database is in an inconsistent state, and the error page offers to mark it as resolved. That works as long as the application doesn't get reloaded. But once it does, e.g. after changing some code or restarting sbt, the application fails to start, as `ApplicationEvolutions` throws `InconsistentDatabase`. Web commands only get handled by a started application, so "Mark it resolved" then only shows the same error page again, and the database has to be fixed manually. + +On top of that, the buttons of the evolutions pages pass the current URL as the URL to return to. On the error page of a failed attempt, that's the URL of that attempt, which carries a `redirect` parameter itself, so the URL got nested with each attempt until it hit the URL length limit. + +This PR: + +- Lets the application start anyway in DEV mode if the database is in an inconsistent state, like it already does when evolutions still need to be applied (#8875). `ApplicationEvolutions.upToDate` returns `false` in that case. `EvolutionsWebCommands` keeps blocking all other requests and shows the inconsistent state, so that it can be resolved. In PROD and TEST mode, starting the application still fails. +- Reuses the original URL to return to, if the current page is an `/@evolutions/...` page with a `redirect` parameter. + +Most of the diff in `ApplicationEvolutions.scala` is indentation, hiding whitespace changes makes it easier to review. + +## Tests + +- New `ApplicationEvolutionsSpec`: DEV mode starts with `upToDate == false`, other requests stay blocked, resolving redirects to the original URL and reloads, afterwards the application is up to date; PROD and TEST mode still fail. Without the fix, the DEV mode and the redirect examples fail. +- The `evolutions-auto-apply-false` scripted test now reloads the application (by adding a class) while the database is in an inconsistent state, and then resolves it. Without the fix, the application fails to start after the reload, resolving returns the same error page, and the test fails. + +## References + +- playframework/play-ebean#220 (runs into this) +- #8875 (DEV mode starts with pending evolutions) +- #14339 (docs on accessing the database while the application starts, which relies on `upToDate`) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65ebfe4c42f8`. 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/playframework__playframework-14340/solution/patch.diff b/tasks/playframework__playframework-14340/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a207793b8208f103f031a8be28713ea6f94edae6 --- /dev/null +++ b/tasks/playframework__playframework-14340/solution/patch.diff @@ -0,0 +1,387 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java +new file mode 100644 +index 0000000000..6b65ce2ed9 +--- /dev/null ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java +@@ -0,0 +1,8 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package controllers; ++ ++/** Added by the test to make the application reload. */ ++public class Reload {} +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test +index 4bd8ee2cb5..b8a73970a1 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test +@@ -25,6 +25,11 @@ $ sleep 2000 + # It will then fail since there is error + > verifyResourceContains / 500 evolution + ++# Reloading the application (e.g. after changing some code) must keep the inconsistent state resolvable ++$ copy-file changes/Reload.java app/controllers/Reload.java ++$ sleep 2000 ++> verifyResourceContains / 500 evolution ++ + # And it can be market as resolved + > applyEvolutions /@evolutions/resolve/default/3 + > verifyResourceContains / 200 7_PlayerFromThirdEvolution +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala +index e803f7aa4e..ea92016b86 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala +@@ -57,94 +57,100 @@ class ApplicationEvolutions @Inject() ( + + dbApi + .databases() +- .foreach( +- ApplicationEvolutions.runEvolutions( +- _, +- config, +- evolutions, +- reader, +- (db, dbConfig, scripts, hasDown) => { +- import Evolutions.toHumanReadableScript +- +- def invalidDatabaseRevision() = { +- invalidDatabaseRevisions += 1 +- throw InvalidDatabaseRevision(db, toHumanReadableScript(scripts)) ++ .foreach(database => ++ try { ++ ApplicationEvolutions.runEvolutions( ++ database, ++ config, ++ evolutions, ++ reader, ++ (db, dbConfig, scripts, hasDown) => { ++ import Evolutions.toHumanReadableScript ++ ++ def invalidDatabaseRevision() = { ++ invalidDatabaseRevisions += 1 ++ throw InvalidDatabaseRevision(db, toHumanReadableScript(scripts)) ++ } ++ ++ environment.mode match { ++ case Mode.Test => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Dev if !dbConfig.autoApply => ++ invalidDatabaseRevisions += 1 // In DEV mode EvolutionsWebCommands handle non-autoApply evolutions ++ case Mode.Dev if dbConfig.autoApply => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if !hasDown && dbConfig.autoApply => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if hasDown && dbConfig.autoApply && dbConfig.autoApplyDowns => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if hasDown => ++ logger.warn( ++ s"Your production database [$db] needs evolutions, including downs! \n\n${toHumanReadableScript(scripts)}" ++ ) ++ logger.warn( ++ s"Run with -Dplay.evolutions.db.$db.autoApply=true and -Dplay.evolutions.db.$db.autoApplyDowns=true if you want to run them automatically, including downs (be careful, especially if your down evolutions drop existing data)" ++ ) ++ ++ invalidDatabaseRevision() ++ ++ case Mode.Prod => ++ logger.warn(s"Your production database [$db] needs evolutions! \n\n${toHumanReadableScript(scripts)}") ++ logger.warn( ++ s"Run with -Dplay.evolutions.db.$db.autoApply=true if you want to run them automatically (be careful)" ++ ) ++ ++ invalidDatabaseRevision() ++ ++ case _ => ++ invalidDatabaseRevision() ++ } + } +- +- environment.mode match { +- case Mode.Test => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Dev if !dbConfig.autoApply => +- invalidDatabaseRevisions += 1 // In DEV mode EvolutionsWebCommands handle non-autoApply evolutions +- case Mode.Dev if dbConfig.autoApply => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if !hasDown && dbConfig.autoApply => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if hasDown && dbConfig.autoApply && dbConfig.autoApplyDowns => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if hasDown => +- logger.warn( +- s"Your production database [$db] needs evolutions, including downs! \n\n${toHumanReadableScript(scripts)}" +- ) +- logger.warn( +- s"Run with -Dplay.evolutions.db.$db.autoApply=true and -Dplay.evolutions.db.$db.autoApplyDowns=true if you want to run them automatically, including downs (be careful, especially if your down evolutions drop existing data)" +- ) +- +- invalidDatabaseRevision() +- +- case Mode.Prod => +- logger.warn(s"Your production database [$db] needs evolutions! \n\n${toHumanReadableScript(scripts)}") +- logger.warn( +- s"Run with -Dplay.evolutions.db.$db.autoApply=true if you want to run them automatically (be careful)" +- ) +- +- invalidDatabaseRevision() +- +- case _ => +- invalidDatabaseRevision() +- } +- } +- ) ++ ) ++ } catch { ++ // In DEV mode, start the application anyway, so that the EvolutionsWebCommands can show the inconsistent ++ // state and resolving it works, like for evolutions that still need to be applied ++ case _: InconsistentDatabase if environment.mode == Mode.Dev => invalidDatabaseRevisions += 1 ++ } + ) + } + +@@ -632,8 +638,8 @@ case class InvalidDatabaseRevision(db: String, script: String) + + private val javascript = + """ +- window.location = window.location.href.split(/[?#]/)[0].replace(/\/@evolutions.*$|\/$/, '') + '/@evolutions/apply/%s?redirect=' + encodeURIComponent(location) +- """.format(db).trim ++ window.location = window.location.href.split(/[?#]/)[0].replace(/\/@evolutions.*$|\/$/, '') + '/@evolutions/apply/%s?redirect=' + encodeURIComponent(%s) ++ """.format(db, EvolutionsJavascript.ReturnUrl).trim + + def htmlDescription = { + An SQL script will be run on your database - +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala +index d706a3a3c3..840456eea1 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala +@@ -874,6 +874,20 @@ object SimpleEvolutionsReader { + def forDefault(evolutions: Evolution*) = new SimpleEvolutionsReader(Map("default" -> evolutions)) + } + ++/** ++ * JavaScript snippets for the evolutions pages. ++ */ ++private[evolutions] object EvolutionsJavascript { ++ ++ /** ++ * The URL to return to after applying or resolving evolutions. If the current page is the result of that itself, e.g. ++ * because applying the evolutions failed, it's the URL that page returns to. So that one doesn't get nested again, ++ * which would let the URL grow with each attempt. ++ */ ++ val ReturnUrl: String = ++ """((/\/@evolutions\//.test(window.location.pathname) && new URLSearchParams(window.location.search).get('redirect')) || window.location.href)""" ++} ++ + /** + * Exception thrown when the database is in an inconsistent state. + * +@@ -893,7 +907,7 @@ case class InconsistentDatabase(db: String, script: String, error: String, rev: + def content = script + + private val resolvePathJavascript = +- if (autocommit) s"'/@evolutions/resolve/$db/$rev?redirect=' + encodeURIComponent(window.location)" ++ if (autocommit) s"'/@evolutions/resolve/$db/$rev?redirect=' + encodeURIComponent(${EvolutionsJavascript.ReturnUrl})" + else "'/@evolutions'" + private val redirectJavascript = + s"""window.location = window.location.href.split(/[?#]/)[0].replace(/\\/@evolutions.*$$|\\/$$/, '') + $resolvePathJavascript""" +diff --git a/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala +new file mode 100644 +index 0000000000..2061523eba +--- /dev/null ++++ b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala +@@ -0,0 +1,114 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.api.db.evolutions ++ ++import java.io.File ++import java.util.UUID ++ ++import org.mockito.Mockito ++import org.specs2.mutable.After ++import org.specs2.mutable.Specification ++import play.api.db.DBApi ++import play.api.db.Database ++import play.api.db.Databases ++import play.api.mvc.RequestHeader ++import play.api.mvc.Result ++import play.api.Configuration ++import play.api.Environment ++import play.api.Mode ++import play.core.BuildLink ++import play.core.DefaultWebCommands ++ ++class ApplicationEvolutionsSpec extends Specification { ++ sequential ++ ++ "ApplicationEvolutions" should { ++ ++ "start in DEV mode although the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Dev).upToDate must beFalse ++ } ++ ++ "let the evolutions web commands handle the inconsistent state in DEV mode" in new WithInconsistentDatabase { ++ start(Mode.Dev) ++ ++ // Other requests stay blocked ++ handle("/") must throwAn[InconsistentDatabase] ++ ++ val result = handle("/@evolutions/resolve/default/1", "redirect" -> "/foo") ++ result.map(_.header.status) must beSome(303) ++ result.flatMap(_.header.headers.get("Location")) must beSome("/foo") ++ forcedReloads must_== 1 ++ ++ // The reloaded application is up to date ++ start(Mode.Dev).upToDate must beTrue ++ } ++ ++ "fail to start in PROD mode if the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Prod) must throwAn[InconsistentDatabase] ++ } ++ ++ "fail to start in TEST mode if the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Test) must throwAn[InconsistentDatabase] ++ } ++ ++ "not nest the URL to return to when applying or resolving evolutions" in { ++ InvalidDatabaseRevision("default", "script").htmlDescription must contain("get('redirect')") ++ InconsistentDatabase("default", "script", "error", 1, autocommit = true).htmlDescription must contain( ++ "get('redirect')" ++ ) ++ } ++ } ++ ++ trait WithInconsistentDatabase extends After { ++ lazy val db: Database = ++ Databases("org.h2.Driver", s"jdbc:h2:mem:application-evolutions-${UUID.randomUUID()}", "default") ++ ++ lazy val dbApi: DBApi = new DBApi { ++ def databases(): Seq[Database] = Seq(db) ++ def database(name: String): Database = db ++ def shutdown(): Unit = db.shutdown() ++ } ++ ++ lazy val evolutionsApi = new DefaultEvolutionsApi(dbApi) ++ lazy val config = new DefaultEvolutionsConfigParser(Configuration.reference).get ++ lazy val reader = ++ SimpleEvolutionsReader.forDefault(Evolution(1, "creaTYPOe table test (id bigint);", "drop table test;")) ++ ++ // Applying the broken evolution leaves the database in an inconsistent state ++ try evolutionsApi.evolve("default", evolutionsApi.scripts("default", reader, ""), autocommit = true, "") ++ catch { case _: InconsistentDatabase => } ++ ++ var forcedReloads = 0 ++ val buildLink = new BuildLink { ++ def reload(): AnyRef = null ++ def findSource(className: String, line: Integer): Array[AnyRef] = null ++ def projectPath(): File = new File(".") ++ def forceReload(): Unit = forcedReloads += 1 ++ def settings(): java.util.Map[String, String] = java.util.Collections.emptyMap() ++ } ++ ++ val webCommands = new DefaultWebCommands ++ ++ def start(mode: Mode): ApplicationEvolutions = ++ new ApplicationEvolutions( ++ config, ++ reader, ++ evolutionsApi, ++ new DynamicEvolutions, ++ dbApi, ++ Environment.simple(mode = mode), ++ webCommands ++ ) ++ ++ def handle(path: String, query: (String, String)*): Option[Result] = { ++ val request = Mockito.mock(classOf[RequestHeader]) ++ Mockito.when(request.path).thenReturn(path) ++ Mockito.when(request.queryString).thenReturn(query.map { case (k, v) => k -> Seq(v) }.toMap) ++ webCommands.handleWebCommand(request, buildLink, new File(".")) ++ } ++ ++ def after: Any = db.shutdown() ++ } ++} diff --git a/tasks/playframework__playframework-14340/solution/solve.sh b/tasks/playframework__playframework-14340/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14340/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/playframework__playframework-14340/task.toml b/tasks/playframework__playframework-14340/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23e58007ee1a701653fe88e18f932c6ab940cc6a --- /dev/null +++ b/tasks/playframework__playframework-14340/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14340" +description = "Resolve an inconsistent database after a reload in dev mode" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "65ebfe4c42f8e7170dc877f13dccfbd85ebbbb0e" +reference = "https://github.com/playframework/playframework/pull/14340" +source_access = "auto" +built_at = "2026-11-16T16:09:46.504135+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:92d382b94ae9ff89caa841c86135e207351dc852faecb071676b4cbb945c3f03" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T11:17:44Z" +diff_format = "unified" +context_files = [ + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test", + "persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala", + "persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala", + "persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 327 +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:02.545407+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c28c834ddb7dd7422894743fee7f5035734bd1b45b5f83c66098a5d4565068e8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14340/tests/capture.py b/tasks/playframework__playframework-14340/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14340/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/playframework__playframework-14340/tests/instruction.md b/tasks/playframework__playframework-14340/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eddd9ea70d6d8a1ba3bf4547cabd9b24ce146d43 --- /dev/null +++ b/tasks/playframework__playframework-14340/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Resolve an inconsistent database after a reload in dev mode + +## Description + +## Purpose + +In DEV mode, when applying an evolution fails, the database is in an inconsistent state, and the error page offers to mark it as resolved. That works as long as the application doesn't get reloaded. But once it does, e.g. after changing some code or restarting sbt, the application fails to start, as `ApplicationEvolutions` throws `InconsistentDatabase`. Web commands only get handled by a started application, so "Mark it resolved" then only shows the same error page again, and the database has to be fixed manually. + +On top of that, the buttons of the evolutions pages pass the current URL as the URL to return to. On the error page of a failed attempt, that's the URL of that attempt, which carries a `redirect` parameter itself, so the URL got nested with each attempt until it hit the URL length limit. + +This PR: + +- Lets the application start anyway in DEV mode if the database is in an inconsistent state, like it already does when evolutions still need to be applied (#8875). `ApplicationEvolutions.upToDate` returns `false` in that case. `EvolutionsWebCommands` keeps blocking all other requests and shows the inconsistent state, so that it can be resolved. In PROD and TEST mode, starting the application still fails. +- Reuses the original URL to return to, if the current page is an `/@evolutions/...` page with a `redirect` parameter. + +Most of the diff in `ApplicationEvolutions.scala` is indentation, hiding whitespace changes makes it easier to review. + +## Tests + +- New `ApplicationEvolutionsSpec`: DEV mode starts with `upToDate == false`, other requests stay blocked, resolving redirects to the original URL and reloads, afterwards the application is up to date; PROD and TEST mode still fail. Without the fix, the DEV mode and the redirect examples fail. +- The `evolutions-auto-apply-false` scripted test now reloads the application (by adding a class) while the database is in an inconsistent state, and then resolves it. Without the fix, the application fails to start after the reload, resolving returns the same error page, and the test fails. + +## References + +- playframework/play-ebean#220 (runs into this) +- #8875 (DEV mode starts with pending evolutions) +- #14339 (docs on accessing the database while the application starts, which relies on `upToDate`) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65ebfe4c42f8`. 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/playframework__playframework-14340/tests/oracle.patch b/tasks/playframework__playframework-14340/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a207793b8208f103f031a8be28713ea6f94edae6 --- /dev/null +++ b/tasks/playframework__playframework-14340/tests/oracle.patch @@ -0,0 +1,387 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java +new file mode 100644 +index 0000000000..6b65ce2ed9 +--- /dev/null ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/changes/Reload.java +@@ -0,0 +1,8 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package controllers; ++ ++/** Added by the test to make the application reload. */ ++public class Reload {} +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test +index 4bd8ee2cb5..b8a73970a1 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/evolutions-auto-apply-false/test +@@ -25,6 +25,11 @@ $ sleep 2000 + # It will then fail since there is error + > verifyResourceContains / 500 evolution + ++# Reloading the application (e.g. after changing some code) must keep the inconsistent state resolvable ++$ copy-file changes/Reload.java app/controllers/Reload.java ++$ sleep 2000 ++> verifyResourceContains / 500 evolution ++ + # And it can be market as resolved + > applyEvolutions /@evolutions/resolve/default/3 + > verifyResourceContains / 200 7_PlayerFromThirdEvolution +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala +index e803f7aa4e..ea92016b86 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/ApplicationEvolutions.scala +@@ -57,94 +57,100 @@ class ApplicationEvolutions @Inject() ( + + dbApi + .databases() +- .foreach( +- ApplicationEvolutions.runEvolutions( +- _, +- config, +- evolutions, +- reader, +- (db, dbConfig, scripts, hasDown) => { +- import Evolutions.toHumanReadableScript +- +- def invalidDatabaseRevision() = { +- invalidDatabaseRevisions += 1 +- throw InvalidDatabaseRevision(db, toHumanReadableScript(scripts)) ++ .foreach(database => ++ try { ++ ApplicationEvolutions.runEvolutions( ++ database, ++ config, ++ evolutions, ++ reader, ++ (db, dbConfig, scripts, hasDown) => { ++ import Evolutions.toHumanReadableScript ++ ++ def invalidDatabaseRevision() = { ++ invalidDatabaseRevisions += 1 ++ throw InvalidDatabaseRevision(db, toHumanReadableScript(scripts)) ++ } ++ ++ environment.mode match { ++ case Mode.Test => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Dev if !dbConfig.autoApply => ++ invalidDatabaseRevisions += 1 // In DEV mode EvolutionsWebCommands handle non-autoApply evolutions ++ case Mode.Dev if dbConfig.autoApply => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if !hasDown && dbConfig.autoApply => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if hasDown && dbConfig.autoApply && dbConfig.autoApplyDowns => ++ evolutions.evolve( ++ db, ++ scripts, ++ dbConfig.autocommit, ++ dbConfig.schema, ++ dbConfig.metaTable, ++ dbConfig.substitutionsMappings, ++ dbConfig.substitutionsPrefix, ++ dbConfig.substitutionsSuffix, ++ dbConfig.substitutionsEscape ++ ) ++ case Mode.Prod if hasDown => ++ logger.warn( ++ s"Your production database [$db] needs evolutions, including downs! \n\n${toHumanReadableScript(scripts)}" ++ ) ++ logger.warn( ++ s"Run with -Dplay.evolutions.db.$db.autoApply=true and -Dplay.evolutions.db.$db.autoApplyDowns=true if you want to run them automatically, including downs (be careful, especially if your down evolutions drop existing data)" ++ ) ++ ++ invalidDatabaseRevision() ++ ++ case Mode.Prod => ++ logger.warn(s"Your production database [$db] needs evolutions! \n\n${toHumanReadableScript(scripts)}") ++ logger.warn( ++ s"Run with -Dplay.evolutions.db.$db.autoApply=true if you want to run them automatically (be careful)" ++ ) ++ ++ invalidDatabaseRevision() ++ ++ case _ => ++ invalidDatabaseRevision() ++ } + } +- +- environment.mode match { +- case Mode.Test => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Dev if !dbConfig.autoApply => +- invalidDatabaseRevisions += 1 // In DEV mode EvolutionsWebCommands handle non-autoApply evolutions +- case Mode.Dev if dbConfig.autoApply => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if !hasDown && dbConfig.autoApply => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if hasDown && dbConfig.autoApply && dbConfig.autoApplyDowns => +- evolutions.evolve( +- db, +- scripts, +- dbConfig.autocommit, +- dbConfig.schema, +- dbConfig.metaTable, +- dbConfig.substitutionsMappings, +- dbConfig.substitutionsPrefix, +- dbConfig.substitutionsSuffix, +- dbConfig.substitutionsEscape +- ) +- case Mode.Prod if hasDown => +- logger.warn( +- s"Your production database [$db] needs evolutions, including downs! \n\n${toHumanReadableScript(scripts)}" +- ) +- logger.warn( +- s"Run with -Dplay.evolutions.db.$db.autoApply=true and -Dplay.evolutions.db.$db.autoApplyDowns=true if you want to run them automatically, including downs (be careful, especially if your down evolutions drop existing data)" +- ) +- +- invalidDatabaseRevision() +- +- case Mode.Prod => +- logger.warn(s"Your production database [$db] needs evolutions! \n\n${toHumanReadableScript(scripts)}") +- logger.warn( +- s"Run with -Dplay.evolutions.db.$db.autoApply=true if you want to run them automatically (be careful)" +- ) +- +- invalidDatabaseRevision() +- +- case _ => +- invalidDatabaseRevision() +- } +- } +- ) ++ ) ++ } catch { ++ // In DEV mode, start the application anyway, so that the EvolutionsWebCommands can show the inconsistent ++ // state and resolving it works, like for evolutions that still need to be applied ++ case _: InconsistentDatabase if environment.mode == Mode.Dev => invalidDatabaseRevisions += 1 ++ } + ) + } + +@@ -632,8 +638,8 @@ case class InvalidDatabaseRevision(db: String, script: String) + + private val javascript = + """ +- window.location = window.location.href.split(/[?#]/)[0].replace(/\/@evolutions.*$|\/$/, '') + '/@evolutions/apply/%s?redirect=' + encodeURIComponent(location) +- """.format(db).trim ++ window.location = window.location.href.split(/[?#]/)[0].replace(/\/@evolutions.*$|\/$/, '') + '/@evolutions/apply/%s?redirect=' + encodeURIComponent(%s) ++ """.format(db, EvolutionsJavascript.ReturnUrl).trim + + def htmlDescription = { + An SQL script will be run on your database - +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala +index d706a3a3c3..840456eea1 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/EvolutionsApi.scala +@@ -874,6 +874,20 @@ object SimpleEvolutionsReader { + def forDefault(evolutions: Evolution*) = new SimpleEvolutionsReader(Map("default" -> evolutions)) + } + ++/** ++ * JavaScript snippets for the evolutions pages. ++ */ ++private[evolutions] object EvolutionsJavascript { ++ ++ /** ++ * The URL to return to after applying or resolving evolutions. If the current page is the result of that itself, e.g. ++ * because applying the evolutions failed, it's the URL that page returns to. So that one doesn't get nested again, ++ * which would let the URL grow with each attempt. ++ */ ++ val ReturnUrl: String = ++ """((/\/@evolutions\//.test(window.location.pathname) && new URLSearchParams(window.location.search).get('redirect')) || window.location.href)""" ++} ++ + /** + * Exception thrown when the database is in an inconsistent state. + * +@@ -893,7 +907,7 @@ case class InconsistentDatabase(db: String, script: String, error: String, rev: + def content = script + + private val resolvePathJavascript = +- if (autocommit) s"'/@evolutions/resolve/$db/$rev?redirect=' + encodeURIComponent(window.location)" ++ if (autocommit) s"'/@evolutions/resolve/$db/$rev?redirect=' + encodeURIComponent(${EvolutionsJavascript.ReturnUrl})" + else "'/@evolutions'" + private val redirectJavascript = + s"""window.location = window.location.href.split(/[?#]/)[0].replace(/\\/@evolutions.*$$|\\/$$/, '') + $resolvePathJavascript""" +diff --git a/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala +new file mode 100644 +index 0000000000..2061523eba +--- /dev/null ++++ b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/ApplicationEvolutionsSpec.scala +@@ -0,0 +1,114 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.api.db.evolutions ++ ++import java.io.File ++import java.util.UUID ++ ++import org.mockito.Mockito ++import org.specs2.mutable.After ++import org.specs2.mutable.Specification ++import play.api.db.DBApi ++import play.api.db.Database ++import play.api.db.Databases ++import play.api.mvc.RequestHeader ++import play.api.mvc.Result ++import play.api.Configuration ++import play.api.Environment ++import play.api.Mode ++import play.core.BuildLink ++import play.core.DefaultWebCommands ++ ++class ApplicationEvolutionsSpec extends Specification { ++ sequential ++ ++ "ApplicationEvolutions" should { ++ ++ "start in DEV mode although the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Dev).upToDate must beFalse ++ } ++ ++ "let the evolutions web commands handle the inconsistent state in DEV mode" in new WithInconsistentDatabase { ++ start(Mode.Dev) ++ ++ // Other requests stay blocked ++ handle("/") must throwAn[InconsistentDatabase] ++ ++ val result = handle("/@evolutions/resolve/default/1", "redirect" -> "/foo") ++ result.map(_.header.status) must beSome(303) ++ result.flatMap(_.header.headers.get("Location")) must beSome("/foo") ++ forcedReloads must_== 1 ++ ++ // The reloaded application is up to date ++ start(Mode.Dev).upToDate must beTrue ++ } ++ ++ "fail to start in PROD mode if the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Prod) must throwAn[InconsistentDatabase] ++ } ++ ++ "fail to start in TEST mode if the database is in an inconsistent state" in new WithInconsistentDatabase { ++ start(Mode.Test) must throwAn[InconsistentDatabase] ++ } ++ ++ "not nest the URL to return to when applying or resolving evolutions" in { ++ InvalidDatabaseRevision("default", "script").htmlDescription must contain("get('redirect')") ++ InconsistentDatabase("default", "script", "error", 1, autocommit = true).htmlDescription must contain( ++ "get('redirect')" ++ ) ++ } ++ } ++ ++ trait WithInconsistentDatabase extends After { ++ lazy val db: Database = ++ Databases("org.h2.Driver", s"jdbc:h2:mem:application-evolutions-${UUID.randomUUID()}", "default") ++ ++ lazy val dbApi: DBApi = new DBApi { ++ def databases(): Seq[Database] = Seq(db) ++ def database(name: String): Database = db ++ def shutdown(): Unit = db.shutdown() ++ } ++ ++ lazy val evolutionsApi = new DefaultEvolutionsApi(dbApi) ++ lazy val config = new DefaultEvolutionsConfigParser(Configuration.reference).get ++ lazy val reader = ++ SimpleEvolutionsReader.forDefault(Evolution(1, "creaTYPOe table test (id bigint);", "drop table test;")) ++ ++ // Applying the broken evolution leaves the database in an inconsistent state ++ try evolutionsApi.evolve("default", evolutionsApi.scripts("default", reader, ""), autocommit = true, "") ++ catch { case _: InconsistentDatabase => } ++ ++ var forcedReloads = 0 ++ val buildLink = new BuildLink { ++ def reload(): AnyRef = null ++ def findSource(className: String, line: Integer): Array[AnyRef] = null ++ def projectPath(): File = new File(".") ++ def forceReload(): Unit = forcedReloads += 1 ++ def settings(): java.util.Map[String, String] = java.util.Collections.emptyMap() ++ } ++ ++ val webCommands = new DefaultWebCommands ++ ++ def start(mode: Mode): ApplicationEvolutions = ++ new ApplicationEvolutions( ++ config, ++ reader, ++ evolutionsApi, ++ new DynamicEvolutions, ++ dbApi, ++ Environment.simple(mode = mode), ++ webCommands ++ ) ++ ++ def handle(path: String, query: (String, String)*): Option[Result] = { ++ val request = Mockito.mock(classOf[RequestHeader]) ++ Mockito.when(request.path).thenReturn(path) ++ Mockito.when(request.queryString).thenReturn(query.map { case (k, v) => k -> Seq(v) }.toMap) ++ webCommands.handleWebCommand(request, buildLink, new File(".")) ++ } ++ ++ def after: Any = db.shutdown() ++ } ++} diff --git a/tasks/playframework__playframework-14340/tests/test.sh b/tasks/playframework__playframework-14340/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7a1376d1888bc1d9303ffb2101408085f902974 --- /dev/null +++ b/tasks/playframework__playframework-14340/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 65ebfe4c42f8e7170dc877f13dccfbd85ebbbb0e > "$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/playframework__playframework-14340/tests/verifier.py b/tasks/playframework__playframework-14340/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14340/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/playframework__playframework-14341/environment/Dockerfile b/tasks/playframework__playframework-14341/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c480942c8511e9dc771322214e19a0b6214d766d --- /dev/null +++ b/tasks/playframework__playframework-14341/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8f99eb81d26f4ce5f97495bf38826a6f61040c60 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8f99eb81d26f4ce5f97495bf38826a6f61040c60 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8f99eb81d26f4ce5f97495bf38826a6f61040c60 \ + && 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/playframework__playframework-14341/instruction.md b/tasks/playframework__playframework-14341/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..482bc544fe113e31fb4e49a3bcdf587bb2776d54 --- /dev/null +++ b/tasks/playframework__playframework-14341/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Run the stop hooks of an application that failed to start in dev mode + +## Description + +## Purpose + +In DEV mode, when the application fails to start, e.g. because a component throws an exception in its constructor, components that got created before may have registered stop hooks already, like the database connection pools of `play-jdbc`. As there is no application that could be stopped, these stop hooks never ran, so their resources leaked with each failed reload. + +Before #10661, `DevServerStart` stopped the lifecycle of the last application before each reload, "no matter if the last state was a Success", which covered this case. #10661 removed that, as for an application that started successfully, `Play.stop` already runs the stop hooks via the coordinated shutdown. But after a failed start, `lastState` is a `Failure`, so `lastState.foreach(Play.stop)` doesn't stop anything, and `lastLifecycle` has been assigned but never used since. + +This PR stops the lifecycle of an application that failed to start right away, so that its resources get released before the error page is shown and before the next reload. `DefaultApplicationLifecycle.stop()` only runs the hooks once, so nothing runs twice. + +The stop hooks run in a separate thread, and the dev server waits for them at most as long as they get when the application gets stopped: the timeout of the coordinated shutdown phase that runs them, `pekko.coordinated-shutdown.phases.service-stop.timeout`, or `pekko.coordinated-shutdown.default-phase-timeout` if that isn't set (5 seconds by default). It gets read from the configuration of the application that failed to start, on each reload, and falls back to 5 seconds if there is no valid timeout, so that reading it never replaces the startup error. So a stop hook that blocks, or whose future never completes, can't keep the dev server from showing the startup error and from reloading. If they don't complete in time, a warning gets logged, they keep running in the background, and the startup error gets shown as usual. + +The timeout gets read from the configuration that `ApplicationLoader.Context.create` loads. A custom `ApplicationLoader` that changes that configuration before creating the actor system could end up with a different timeout for the application itself, but the wait is bounded either way. + +## Tests + +The new `DevServerStartSpec` checks that the stop hooks run with the class loader of the application, that the dev server waits for them to complete, and that it doesn't block if a stop hook blocks or its future never completes. Without the timeout, the last two examples fail. It also checks which timeout gets used: Pekko's default, a configured `service-stop` timeout, a configured default phase timeout, and the fallback for an invalid or missing one. + +The `dev-mode` scripted test now registers a stop hook in an eager singleton, and lets the startup failure happen in another eager singleton that gets created afterwards, instead of in `Module.configure()`, where nothing has been created yet. It checks that the stop hooks ran once for every stopped application, including the one that failed to start. Without the fix, it fails with `Expected 4 stops but got 3`. + +## Not covered + +The application's `ActorSystem` has no stop hook. It only gets terminated by its `CoordinatedShutdown`, which `Application.stop` runs. So an `ActorSystem` that got created before the start failed is still not terminated. That needs a different approach, e.g. in `ActorSystemProvider`, and is left for a separate PR. + +## References + +- #10661 +- #6437 (added stopping the lifecycle before each reload) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f99eb81d26f`. 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/playframework__playframework-14341/solution/patch.diff b/tasks/playframework__playframework-14341/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..01573b2802a4be964e0fc3040d48bd8b51cf45f4 --- /dev/null +++ b/tasks/playframework__playframework-14341/solution/patch.diff @@ -0,0 +1,353 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala +index 4408bdf752..f32cf75f21 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala +@@ -5,8 +5,12 @@ + import java.io.FileWriter + import java.util.Date + ++import scala.concurrent.Future ++ + import com.google.inject.AbstractModule ++import jakarta.inject.Inject + import play.api._ ++import play.api.inject.ApplicationLifecycle + + class Module(environment: Environment, configuration: Configuration) extends AbstractModule { + +@@ -15,8 +19,23 @@ class Module(environment: Environment, configuration: Configuration) extends Abs + writer.write(s"${new Date()} - reloaded\n") + writer.close() + ++ bind(classOf[StopRecorder]).asEagerSingleton() + if (configuration.getOptional[Boolean]("fail").getOrElse(false)) { +- throw new RuntimeException("fail=true") ++ bind(classOf[FailingComponent]).asEagerSingleton() + } + } + } ++ ++class StopRecorder @Inject() (environment: Environment, lifecycle: ApplicationLifecycle) { ++ lifecycle.addStopHook { () => ++ val writer = new FileWriter(environment.getFile("target/stop.log"), true) ++ writer.write(s"${new Date()} - stopped\n") ++ writer.close() ++ Future.unit ++ } ++} ++ ++// Fails to start after the StopRecorder has registered its stop hook ++class FailingComponent @Inject() (stopRecorder: StopRecorder) { ++ throw new RuntimeException("fail=true") ++} +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt +index 36d7f21527..67a4594c9e 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt +@@ -7,7 +7,10 @@ lazy val root = (project in file(".")) + PlayKeys.playInteractionMode := play.sbt.StaticPlayNonBlockingInteractionMode, + PlayKeys.fileWatchService := play.dev.filewatch.FileWatchService.polling(500), + libraryDependencies += guice, +- TaskKey[Unit]("resetReloads") := (baseDirectory.value / "target" / "reload.log").delete(), ++ TaskKey[Unit]("resetReloads") := { ++ (baseDirectory.value / "target" / "reload.log").delete() ++ (baseDirectory.value / "target" / "stop.log").delete() ++ }, + InputKey[Unit]("verifyReloads") := { + val expected = Def.spaceDelimited().parsed.head.toInt + val actual = IO.readLines(baseDirectory.value / "target" / "reload.log").count(_.nonEmpty) +@@ -17,6 +20,16 @@ lazy val root = (project in file(".")) + sys.error(s"Expected $expected reloads but got $actual") + } + }, ++ InputKey[Unit]("verifyStops") := { ++ val expected = Def.spaceDelimited().parsed.head.toInt ++ val stopLog = baseDirectory.value / "target" / "stop.log" ++ val actual = if (stopLog.exists) IO.readLines(stopLog).count(_.nonEmpty) else 0 ++ if (expected == actual) { ++ println(s"Expected and got $expected stops") ++ } else { ++ sys.error(s"Expected $expected stops but got $actual") ++ } ++ }, + InputKey[Unit]("makeRequestWithHeader") := { + val args = Def.spaceDelimited(" ...").parsed + val path :: status :: headers = args +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test +index 9b0681260b..ff26294409 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test +@@ -153,13 +153,18 @@ $ copy-file conf/application.conf conf/application.original + $ copy-file changes/application.conf.1 conf/application.conf + > verifyResourceContains / 500 + > verifyReloads 4 ++# The previous applications got stopped, and the stop hooks of the application that failed to start have run too ++> verifyStops 4 + + # Revert to the original application.conf + $ sleep 1000 + $ copy-file conf/application.original conf/application.conf + > verifyResourceContains / 200 ++# The stop hooks of the application that failed to start don't run again ++> verifyStops 4 + + > playStop ++> verifyStops 5 + + # devSettings tests + # ----------------- +diff --git a/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala b/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala +index 512e5c7c87..62e35d48b5 100644 +--- a/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala ++++ b/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala +@@ -7,9 +7,15 @@ package play.core.server + import java.io.File + import java.net.InetAddress + import java.util.concurrent.atomic.AtomicBoolean ++import java.util.concurrent.TimeoutException + ++import scala.concurrent.duration.DurationInt ++import scala.concurrent.duration.FiniteDuration ++import scala.concurrent.Await + import scala.concurrent.Future ++import scala.concurrent.Promise + import scala.jdk.CollectionConverters._ ++import scala.jdk.DurationConverters._ + import scala.util.control.NonFatal + import scala.util.Failure + import scala.util.Success +@@ -35,6 +41,14 @@ import play.utils.Threads + */ + object DevServerStart { + ++ private val logger = Logger(getClass) ++ ++ /** ++ * How long to wait for the stop hooks of an application that failed to start, if its configuration doesn't tell. ++ * The same as Pekko's default phase timeout. ++ */ ++ private val DefaultFailedApplicationStopTimeout: FiniteDuration = 5.seconds ++ + /** + * Provides an HTTPS-only server for the dev environment. + * +@@ -89,6 +103,57 @@ object DevServerStart { + val devModePekkoConfig = conf.underlying.getConfig("play.pekko.dev-mode").withFallback(conf.underlying) + ActorSystem("play-dev-mode", devModePekkoConfig) + } ++ ++ /** ++ * How long to wait for the stop hooks of an application that failed to start. That's as long as they get when the ++ * application gets stopped, i.e. the timeout of the coordinated shutdown phase that runs them. Falls back to Pekko's ++ * default phase timeout if the configuration doesn't contain a valid timeout, so that this never fails. ++ */ ++ private[server] def failedApplicationStopTimeout(configuration: Configuration): FiniteDuration = ++ Try { ++ val coordinatedShutdown = configuration.underlying.getConfig("pekko.coordinated-shutdown") ++ val phaseTimeout = "phases.service-stop.timeout" ++ coordinatedShutdown ++ .getDuration(if (coordinatedShutdown.hasPath(phaseTimeout)) phaseTimeout else "default-phase-timeout") ++ .toScala ++ }.getOrElse(DefaultFailedApplicationStopTimeout) ++ ++ /** ++ * Stops the lifecycle of an application that failed to start. Components that got created before the failure, ++ * like database connection pools, may have registered stop hooks already. As there is no application that could ++ * be stopped, nothing else would run them. ++ * ++ * The stop hooks run in a separate thread, so that a stop hook that blocks, or whose future never completes, can't ++ * block the dev server. If they don't complete within the timeout, they keep running in the background and the ++ * startup error gets shown anyway. ++ */ ++ private[server] def stopFailedApplication( ++ lifecycle: DefaultApplicationLifecycle, ++ classLoader: ClassLoader, ++ timeout: FiniteDuration ++ ): Unit = { ++ val stopped = Promise[Any]() ++ val thread = new Thread( ++ () => { ++ stopped.completeWith( ++ try lifecycle.stop() ++ catch { case NonFatal(e) => Future.failed(e) } ++ ) ++ () ++ }, ++ "play-dev-mode-failed-application-stop" ++ ) ++ thread.setContextClassLoader(classLoader) ++ thread.setDaemon(true) ++ thread.start() ++ try Await.ready(stopped.future, timeout) ++ catch { ++ case _: TimeoutException => ++ logger.warn( ++ s"The stop hooks of the application that failed to start didn't complete within $timeout, they keep running in the background" ++ ) ++ } ++ } + } + + @InternalApi // Reused by Lagom but otherwise not stable +@@ -206,6 +271,8 @@ final class DevServerStart( + } + } + } ++ // How long to wait for the stop hooks if the application fails to start ++ var stopTimeout = DevServerStart.DefaultFailedApplicationStopTimeout + try { + if (lastState.isSuccess) { + println() +@@ -229,6 +296,7 @@ final class DevServerStart( + lifecycle = lifecycle, + devContext = Some(ApplicationLoader.DevContext(sourceMapper, buildLink)) + ) ++ stopTimeout = DevServerStart.failedApplicationStopTimeout(context.initialConfiguration) + val loader = ApplicationLoader(context) + loader.load(context) + } +@@ -249,16 +317,19 @@ final class DevServerStart( + lastState + } catch { + case e: PlayException => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + lastState = Failure(e) + logExceptionAndGetResult(path, e) + lastState + + case e: LinkageError => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + lastState = Failure(UnexpectedException(unexpected = Some(e))) + logExceptionAndGetResult(path, e) + lastState + + case NonFatal(e) => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + val useful: UsefulException = HttpErrorHandlerExceptions.throwableToUsefulException( + Some(sourceMapper), + isProd = false, +diff --git a/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala b/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala +new file mode 100644 +index 0000000000..4837cfdf0a +--- /dev/null ++++ b/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala +@@ -0,0 +1,119 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.core.server ++ ++import java.net.URLClassLoader ++import java.util.concurrent.CountDownLatch ++import java.util.concurrent.TimeUnit ++ ++import scala.concurrent.duration.DurationInt ++import scala.concurrent.duration.FiniteDuration ++import scala.concurrent.Await ++import scala.concurrent.ExecutionContext ++import scala.concurrent.Future ++import scala.concurrent.Promise ++ ++import org.specs2.mutable.Specification ++import play.api.inject.DefaultApplicationLifecycle ++import play.api.Configuration ++ ++class DevServerStartSpec extends Specification { ++ ++ private val classLoader = new URLClassLoader(Array.empty, getClass.getClassLoader) ++ ++ /** ++ * Stops the lifecycle, and fails instead of hanging if that blocks longer than the timeout. ++ */ ++ private def stopFailedApplication( ++ lifecycle: DefaultApplicationLifecycle, ++ timeout: FiniteDuration = 100.millis ++ ): Unit = ++ Await.result( ++ Future(DevServerStart.stopFailedApplication(lifecycle, classLoader, timeout))(ExecutionContext.global), ++ timeout + 10.seconds ++ ) ++ ++ "DevServerStart.stopFailedApplication" should { ++ ++ "run the stop hooks with the class loader of the application" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val hookClassLoader = Promise[ClassLoader]() ++ lifecycle.addStopHook(() => ++ Future.successful(hookClassLoader.success(Thread.currentThread.getContextClassLoader)) ++ ) ++ ++ stopFailedApplication(lifecycle) ++ hookClassLoader.future.value.map(_.get) must beSome(classLoader) ++ } ++ ++ "wait for the stop hooks to complete" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val completed = new CountDownLatch(1) ++ lifecycle.addStopHook(() => ++ Future { ++ Thread.sleep(50) ++ completed.countDown() ++ }(ExecutionContext.global) ++ ) ++ ++ stopFailedApplication(lifecycle, timeout = 10.seconds) ++ completed.getCount must_== 0 ++ } ++ ++ "not block if the future of a stop hook never completes" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ lifecycle.addStopHook(() => Promise[Unit]().future) ++ ++ stopFailedApplication(lifecycle) must not(throwA[Throwable]) ++ } ++ ++ "not block if a stop hook blocks" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val started = new CountDownLatch(1) ++ val release = new CountDownLatch(1) ++ lifecycle.addStopHook { () => ++ started.countDown() ++ release.await() ++ Future.unit ++ } ++ ++ try { ++ stopFailedApplication(lifecycle) must not(throwA[Throwable]) ++ started.await(10, TimeUnit.SECONDS) must beTrue ++ } finally release.countDown() ++ } ++ } ++ ++ "DevServerStart.failedApplicationStopTimeout" should { ++ ++ def failedApplicationStopTimeout(settings: (String, Any)*) = ++ DevServerStart.failedApplicationStopTimeout( ++ Configuration.from(settings.toMap).withFallback(Configuration.reference) ++ ) ++ ++ "be Pekko's default phase timeout by default" in { ++ failedApplicationStopTimeout() must_== 5.seconds ++ } ++ ++ "be the configured timeout of the service-stop phase" in { ++ failedApplicationStopTimeout( ++ "pekko.coordinated-shutdown.phases.service-stop.timeout" -> "30 s" ++ ) must_== 30.seconds ++ } ++ ++ "be the configured default phase timeout if the service-stop phase has no timeout" in { ++ failedApplicationStopTimeout("pekko.coordinated-shutdown.default-phase-timeout" -> "10 s") must_== 10.seconds ++ } ++ ++ "fall back to Pekko's default phase timeout if the timeout is invalid" in { ++ failedApplicationStopTimeout("pekko.coordinated-shutdown.phases.service-stop.timeout" -> "invalid") must_== ++ 5.seconds ++ } ++ ++ "fall back to Pekko's default phase timeout if the configuration doesn't contain one" in { ++ DevServerStart.failedApplicationStopTimeout(Configuration.empty) must_== 5.seconds ++ } ++ } ++} diff --git a/tasks/playframework__playframework-14341/solution/solve.sh b/tasks/playframework__playframework-14341/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14341/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/playframework__playframework-14341/task.toml b/tasks/playframework__playframework-14341/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f907efbbe1f0005bab4fea6fe3e7ac428a790b07 --- /dev/null +++ b/tasks/playframework__playframework-14341/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14341" +description = "Run the stop hooks of an application that failed to start in dev mode" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "8f99eb81d26f4ce5f97495bf38826a6f61040c60" +reference = "https://github.com/playframework/playframework/pull/14341" +source_access = "auto" +built_at = "2026-11-16T16:09:46.498620+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:172aa989c9d00da8fe408769c2285ccf274a4413cfbb82c96523926429c2ef33" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T09:50:17Z" +diff_format = "unified" +context_files = [ + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test", + "transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala", + "transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 231 +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:02.545975+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2bb0565ec2b756afdbab79ad7e65cfdf228c84dfeda33df9b9c95488439666d6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14341/tests/capture.py b/tasks/playframework__playframework-14341/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14341/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/playframework__playframework-14341/tests/instruction.md b/tasks/playframework__playframework-14341/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..482bc544fe113e31fb4e49a3bcdf587bb2776d54 --- /dev/null +++ b/tasks/playframework__playframework-14341/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Run the stop hooks of an application that failed to start in dev mode + +## Description + +## Purpose + +In DEV mode, when the application fails to start, e.g. because a component throws an exception in its constructor, components that got created before may have registered stop hooks already, like the database connection pools of `play-jdbc`. As there is no application that could be stopped, these stop hooks never ran, so their resources leaked with each failed reload. + +Before #10661, `DevServerStart` stopped the lifecycle of the last application before each reload, "no matter if the last state was a Success", which covered this case. #10661 removed that, as for an application that started successfully, `Play.stop` already runs the stop hooks via the coordinated shutdown. But after a failed start, `lastState` is a `Failure`, so `lastState.foreach(Play.stop)` doesn't stop anything, and `lastLifecycle` has been assigned but never used since. + +This PR stops the lifecycle of an application that failed to start right away, so that its resources get released before the error page is shown and before the next reload. `DefaultApplicationLifecycle.stop()` only runs the hooks once, so nothing runs twice. + +The stop hooks run in a separate thread, and the dev server waits for them at most as long as they get when the application gets stopped: the timeout of the coordinated shutdown phase that runs them, `pekko.coordinated-shutdown.phases.service-stop.timeout`, or `pekko.coordinated-shutdown.default-phase-timeout` if that isn't set (5 seconds by default). It gets read from the configuration of the application that failed to start, on each reload, and falls back to 5 seconds if there is no valid timeout, so that reading it never replaces the startup error. So a stop hook that blocks, or whose future never completes, can't keep the dev server from showing the startup error and from reloading. If they don't complete in time, a warning gets logged, they keep running in the background, and the startup error gets shown as usual. + +The timeout gets read from the configuration that `ApplicationLoader.Context.create` loads. A custom `ApplicationLoader` that changes that configuration before creating the actor system could end up with a different timeout for the application itself, but the wait is bounded either way. + +## Tests + +The new `DevServerStartSpec` checks that the stop hooks run with the class loader of the application, that the dev server waits for them to complete, and that it doesn't block if a stop hook blocks or its future never completes. Without the timeout, the last two examples fail. It also checks which timeout gets used: Pekko's default, a configured `service-stop` timeout, a configured default phase timeout, and the fallback for an invalid or missing one. + +The `dev-mode` scripted test now registers a stop hook in an eager singleton, and lets the startup failure happen in another eager singleton that gets created afterwards, instead of in `Module.configure()`, where nothing has been created yet. It checks that the stop hooks ran once for every stopped application, including the one that failed to start. Without the fix, it fails with `Expected 4 stops but got 3`. + +## Not covered + +The application's `ActorSystem` has no stop hook. It only gets terminated by its `CoordinatedShutdown`, which `Application.stop` runs. So an `ActorSystem` that got created before the start failed is still not terminated. That needs a different approach, e.g. in `ActorSystemProvider`, and is left for a separate PR. + +## References + +- #10661 +- #6437 (added stopping the lifecycle before each reload) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8f99eb81d26f`. 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/playframework__playframework-14341/tests/oracle.patch b/tasks/playframework__playframework-14341/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..01573b2802a4be964e0fc3040d48bd8b51cf45f4 --- /dev/null +++ b/tasks/playframework__playframework-14341/tests/oracle.patch @@ -0,0 +1,353 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala +index 4408bdf752..f32cf75f21 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/app/Module.scala +@@ -5,8 +5,12 @@ + import java.io.FileWriter + import java.util.Date + ++import scala.concurrent.Future ++ + import com.google.inject.AbstractModule ++import jakarta.inject.Inject + import play.api._ ++import play.api.inject.ApplicationLifecycle + + class Module(environment: Environment, configuration: Configuration) extends AbstractModule { + +@@ -15,8 +19,23 @@ class Module(environment: Environment, configuration: Configuration) extends Abs + writer.write(s"${new Date()} - reloaded\n") + writer.close() + ++ bind(classOf[StopRecorder]).asEagerSingleton() + if (configuration.getOptional[Boolean]("fail").getOrElse(false)) { +- throw new RuntimeException("fail=true") ++ bind(classOf[FailingComponent]).asEagerSingleton() + } + } + } ++ ++class StopRecorder @Inject() (environment: Environment, lifecycle: ApplicationLifecycle) { ++ lifecycle.addStopHook { () => ++ val writer = new FileWriter(environment.getFile("target/stop.log"), true) ++ writer.write(s"${new Date()} - stopped\n") ++ writer.close() ++ Future.unit ++ } ++} ++ ++// Fails to start after the StopRecorder has registered its stop hook ++class FailingComponent @Inject() (stopRecorder: StopRecorder) { ++ throw new RuntimeException("fail=true") ++} +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt +index 36d7f21527..67a4594c9e 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/build.sbt +@@ -7,7 +7,10 @@ lazy val root = (project in file(".")) + PlayKeys.playInteractionMode := play.sbt.StaticPlayNonBlockingInteractionMode, + PlayKeys.fileWatchService := play.dev.filewatch.FileWatchService.polling(500), + libraryDependencies += guice, +- TaskKey[Unit]("resetReloads") := (baseDirectory.value / "target" / "reload.log").delete(), ++ TaskKey[Unit]("resetReloads") := { ++ (baseDirectory.value / "target" / "reload.log").delete() ++ (baseDirectory.value / "target" / "stop.log").delete() ++ }, + InputKey[Unit]("verifyReloads") := { + val expected = Def.spaceDelimited().parsed.head.toInt + val actual = IO.readLines(baseDirectory.value / "target" / "reload.log").count(_.nonEmpty) +@@ -17,6 +20,16 @@ lazy val root = (project in file(".")) + sys.error(s"Expected $expected reloads but got $actual") + } + }, ++ InputKey[Unit]("verifyStops") := { ++ val expected = Def.spaceDelimited().parsed.head.toInt ++ val stopLog = baseDirectory.value / "target" / "stop.log" ++ val actual = if (stopLog.exists) IO.readLines(stopLog).count(_.nonEmpty) else 0 ++ if (expected == actual) { ++ println(s"Expected and got $expected stops") ++ } else { ++ sys.error(s"Expected $expected stops but got $actual") ++ } ++ }, + InputKey[Unit]("makeRequestWithHeader") := { + val args = Def.spaceDelimited(" ...").parsed + val path :: status :: headers = args +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test +index 9b0681260b..ff26294409 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/dev-mode/test +@@ -153,13 +153,18 @@ $ copy-file conf/application.conf conf/application.original + $ copy-file changes/application.conf.1 conf/application.conf + > verifyResourceContains / 500 + > verifyReloads 4 ++# The previous applications got stopped, and the stop hooks of the application that failed to start have run too ++> verifyStops 4 + + # Revert to the original application.conf + $ sleep 1000 + $ copy-file conf/application.original conf/application.conf + > verifyResourceContains / 200 ++# The stop hooks of the application that failed to start don't run again ++> verifyStops 4 + + > playStop ++> verifyStops 5 + + # devSettings tests + # ----------------- +diff --git a/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala b/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala +index 512e5c7c87..62e35d48b5 100644 +--- a/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala ++++ b/transport/server/play-server/src/main/scala/play/core/server/DevServerStart.scala +@@ -7,9 +7,15 @@ package play.core.server + import java.io.File + import java.net.InetAddress + import java.util.concurrent.atomic.AtomicBoolean ++import java.util.concurrent.TimeoutException + ++import scala.concurrent.duration.DurationInt ++import scala.concurrent.duration.FiniteDuration ++import scala.concurrent.Await + import scala.concurrent.Future ++import scala.concurrent.Promise + import scala.jdk.CollectionConverters._ ++import scala.jdk.DurationConverters._ + import scala.util.control.NonFatal + import scala.util.Failure + import scala.util.Success +@@ -35,6 +41,14 @@ import play.utils.Threads + */ + object DevServerStart { + ++ private val logger = Logger(getClass) ++ ++ /** ++ * How long to wait for the stop hooks of an application that failed to start, if its configuration doesn't tell. ++ * The same as Pekko's default phase timeout. ++ */ ++ private val DefaultFailedApplicationStopTimeout: FiniteDuration = 5.seconds ++ + /** + * Provides an HTTPS-only server for the dev environment. + * +@@ -89,6 +103,57 @@ object DevServerStart { + val devModePekkoConfig = conf.underlying.getConfig("play.pekko.dev-mode").withFallback(conf.underlying) + ActorSystem("play-dev-mode", devModePekkoConfig) + } ++ ++ /** ++ * How long to wait for the stop hooks of an application that failed to start. That's as long as they get when the ++ * application gets stopped, i.e. the timeout of the coordinated shutdown phase that runs them. Falls back to Pekko's ++ * default phase timeout if the configuration doesn't contain a valid timeout, so that this never fails. ++ */ ++ private[server] def failedApplicationStopTimeout(configuration: Configuration): FiniteDuration = ++ Try { ++ val coordinatedShutdown = configuration.underlying.getConfig("pekko.coordinated-shutdown") ++ val phaseTimeout = "phases.service-stop.timeout" ++ coordinatedShutdown ++ .getDuration(if (coordinatedShutdown.hasPath(phaseTimeout)) phaseTimeout else "default-phase-timeout") ++ .toScala ++ }.getOrElse(DefaultFailedApplicationStopTimeout) ++ ++ /** ++ * Stops the lifecycle of an application that failed to start. Components that got created before the failure, ++ * like database connection pools, may have registered stop hooks already. As there is no application that could ++ * be stopped, nothing else would run them. ++ * ++ * The stop hooks run in a separate thread, so that a stop hook that blocks, or whose future never completes, can't ++ * block the dev server. If they don't complete within the timeout, they keep running in the background and the ++ * startup error gets shown anyway. ++ */ ++ private[server] def stopFailedApplication( ++ lifecycle: DefaultApplicationLifecycle, ++ classLoader: ClassLoader, ++ timeout: FiniteDuration ++ ): Unit = { ++ val stopped = Promise[Any]() ++ val thread = new Thread( ++ () => { ++ stopped.completeWith( ++ try lifecycle.stop() ++ catch { case NonFatal(e) => Future.failed(e) } ++ ) ++ () ++ }, ++ "play-dev-mode-failed-application-stop" ++ ) ++ thread.setContextClassLoader(classLoader) ++ thread.setDaemon(true) ++ thread.start() ++ try Await.ready(stopped.future, timeout) ++ catch { ++ case _: TimeoutException => ++ logger.warn( ++ s"The stop hooks of the application that failed to start didn't complete within $timeout, they keep running in the background" ++ ) ++ } ++ } + } + + @InternalApi // Reused by Lagom but otherwise not stable +@@ -206,6 +271,8 @@ final class DevServerStart( + } + } + } ++ // How long to wait for the stop hooks if the application fails to start ++ var stopTimeout = DevServerStart.DefaultFailedApplicationStopTimeout + try { + if (lastState.isSuccess) { + println() +@@ -229,6 +296,7 @@ final class DevServerStart( + lifecycle = lifecycle, + devContext = Some(ApplicationLoader.DevContext(sourceMapper, buildLink)) + ) ++ stopTimeout = DevServerStart.failedApplicationStopTimeout(context.initialConfiguration) + val loader = ApplicationLoader(context) + loader.load(context) + } +@@ -249,16 +317,19 @@ final class DevServerStart( + lastState + } catch { + case e: PlayException => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + lastState = Failure(e) + logExceptionAndGetResult(path, e) + lastState + + case e: LinkageError => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + lastState = Failure(UnexpectedException(unexpected = Some(e))) + logExceptionAndGetResult(path, e) + lastState + + case NonFatal(e) => ++ lastLifecycle.foreach(DevServerStart.stopFailedApplication(_, projectClassloader, stopTimeout)) + val useful: UsefulException = HttpErrorHandlerExceptions.throwableToUsefulException( + Some(sourceMapper), + isProd = false, +diff --git a/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala b/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala +new file mode 100644 +index 0000000000..4837cfdf0a +--- /dev/null ++++ b/transport/server/play-server/src/test/scala/play/core/server/DevServerStartSpec.scala +@@ -0,0 +1,119 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.core.server ++ ++import java.net.URLClassLoader ++import java.util.concurrent.CountDownLatch ++import java.util.concurrent.TimeUnit ++ ++import scala.concurrent.duration.DurationInt ++import scala.concurrent.duration.FiniteDuration ++import scala.concurrent.Await ++import scala.concurrent.ExecutionContext ++import scala.concurrent.Future ++import scala.concurrent.Promise ++ ++import org.specs2.mutable.Specification ++import play.api.inject.DefaultApplicationLifecycle ++import play.api.Configuration ++ ++class DevServerStartSpec extends Specification { ++ ++ private val classLoader = new URLClassLoader(Array.empty, getClass.getClassLoader) ++ ++ /** ++ * Stops the lifecycle, and fails instead of hanging if that blocks longer than the timeout. ++ */ ++ private def stopFailedApplication( ++ lifecycle: DefaultApplicationLifecycle, ++ timeout: FiniteDuration = 100.millis ++ ): Unit = ++ Await.result( ++ Future(DevServerStart.stopFailedApplication(lifecycle, classLoader, timeout))(ExecutionContext.global), ++ timeout + 10.seconds ++ ) ++ ++ "DevServerStart.stopFailedApplication" should { ++ ++ "run the stop hooks with the class loader of the application" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val hookClassLoader = Promise[ClassLoader]() ++ lifecycle.addStopHook(() => ++ Future.successful(hookClassLoader.success(Thread.currentThread.getContextClassLoader)) ++ ) ++ ++ stopFailedApplication(lifecycle) ++ hookClassLoader.future.value.map(_.get) must beSome(classLoader) ++ } ++ ++ "wait for the stop hooks to complete" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val completed = new CountDownLatch(1) ++ lifecycle.addStopHook(() => ++ Future { ++ Thread.sleep(50) ++ completed.countDown() ++ }(ExecutionContext.global) ++ ) ++ ++ stopFailedApplication(lifecycle, timeout = 10.seconds) ++ completed.getCount must_== 0 ++ } ++ ++ "not block if the future of a stop hook never completes" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ lifecycle.addStopHook(() => Promise[Unit]().future) ++ ++ stopFailedApplication(lifecycle) must not(throwA[Throwable]) ++ } ++ ++ "not block if a stop hook blocks" in { ++ val lifecycle = new DefaultApplicationLifecycle ++ val started = new CountDownLatch(1) ++ val release = new CountDownLatch(1) ++ lifecycle.addStopHook { () => ++ started.countDown() ++ release.await() ++ Future.unit ++ } ++ ++ try { ++ stopFailedApplication(lifecycle) must not(throwA[Throwable]) ++ started.await(10, TimeUnit.SECONDS) must beTrue ++ } finally release.countDown() ++ } ++ } ++ ++ "DevServerStart.failedApplicationStopTimeout" should { ++ ++ def failedApplicationStopTimeout(settings: (String, Any)*) = ++ DevServerStart.failedApplicationStopTimeout( ++ Configuration.from(settings.toMap).withFallback(Configuration.reference) ++ ) ++ ++ "be Pekko's default phase timeout by default" in { ++ failedApplicationStopTimeout() must_== 5.seconds ++ } ++ ++ "be the configured timeout of the service-stop phase" in { ++ failedApplicationStopTimeout( ++ "pekko.coordinated-shutdown.phases.service-stop.timeout" -> "30 s" ++ ) must_== 30.seconds ++ } ++ ++ "be the configured default phase timeout if the service-stop phase has no timeout" in { ++ failedApplicationStopTimeout("pekko.coordinated-shutdown.default-phase-timeout" -> "10 s") must_== 10.seconds ++ } ++ ++ "fall back to Pekko's default phase timeout if the timeout is invalid" in { ++ failedApplicationStopTimeout("pekko.coordinated-shutdown.phases.service-stop.timeout" -> "invalid") must_== ++ 5.seconds ++ } ++ ++ "fall back to Pekko's default phase timeout if the configuration doesn't contain one" in { ++ DevServerStart.failedApplicationStopTimeout(Configuration.empty) must_== 5.seconds ++ } ++ } ++} diff --git a/tasks/playframework__playframework-14341/tests/test.sh b/tasks/playframework__playframework-14341/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..10b25c2e05590b0be5f5720aaf44d1214968d5f8 --- /dev/null +++ b/tasks/playframework__playframework-14341/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 8f99eb81d26f4ce5f97495bf38826a6f61040c60 > "$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/playframework__playframework-14341/tests/verifier.py b/tasks/playframework__playframework-14341/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14341/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/playframework__playframework-14351/environment/Dockerfile b/tasks/playframework__playframework-14351/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a06bfe098d9bf9482bc3310d617b3881c057b6d2 --- /dev/null +++ b/tasks/playframework__playframework-14351/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3968a05259b25a72f14e88f578f5dd4bfe524bea 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3968a05259b25a72f14e88f578f5dd4bfe524bea \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3968a05259b25a72f14e88f578f5dd4bfe524bea \ + && 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/playframework__playframework-14351/instruction.md b/tasks/playframework__playframework-14351/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eea448e8078d6fc96103e5a8b9bf84e8138b96ad --- /dev/null +++ b/tasks/playframework__playframework-14351/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Update Selenide to 7.19.0 and HtmlUnitDriver to 4.51.0 + +## Description + +## Purpose + +Upgrade `selenide-core` from 7.18.2 to [7.19.0](https://github.com/selenide/selenide/releases/tag/v7.19.0), incorporating the update proposed in #14348, and upgrade `htmlunit3-driver` from 4.48.0 to [4.51.0](https://github.com/SeleniumHQ/htmlunit-driver/releases/tag/4.51.0) (HtmlUnit 5.6.0). + +Selenide 7.19.0 already brings `selenium-java` 4.51.0, matching HtmlUnitDriver's Selenium version. Use that transitive dependency and remove the explicit `selenium-java` declaration and `seleniumVersion` value introduced in the earlier revision of this PR. + +Update the Play 3.1 highlights and migration guide to describe Selenium 4.51 and its dependency path through Selenide. + +## Testing + +- Full `Play-Test` and `Play-Specs2` suites, using `testFull`, and MiMa on Scala 2.13.18 and 3.3.8. +- Root and documentation `validateCode` (formatting, headers and documentation validation). +- Generated Scala 2.13 and Scala 3 POMs declare `selenide-core` 7.19.0 and `htmlunit3-driver` 4.51.0, with no direct `selenium-java` dependency. +- Resolved dependency classpaths on both Scala lines contain Selenide 7.19.0 and Selenium 4.51.0 throughout, including Chrome, Firefox, Edge, Safari and remote drivers. + +The complete Play test matrix is covered by PR CI. + +Implemented and tested with Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3968a05259b2`. 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/playframework__playframework-14351/solution/patch.diff b/tasks/playframework__playframework-14351/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f5cb95d6cbda64f355d806efbc409652eb1e7642 --- /dev/null +++ b/tasks/playframework__playframework-14351/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/documentation/manual/releases/release31/Highlights31.md b/documentation/manual/releases/release31/Highlights31.md +index ca0655375c..00e189468f 100644 +--- a/documentation/manual/releases/release31/Highlights31.md ++++ b/documentation/manual/releases/release31/Highlights31.md +@@ -12,7 +12,7 @@ Play WS now supports the [HTTP QUERY method](https://www.rfc-editor.org/rfc/rfc1 + + ### Selenide based test browser + +-Play's test browser (`TestBrowser`, used by `WithBrowser`) is now backed by [Selenide](https://selenide.org) instead of the archived FluentLenium project. This brings current Selenium (4.49) and HtmlUnit (5.x) versions, and with them support for current browsers and a fix for [CVE-2023-26119](https://nvd.nist.gov/vuln/detail/CVE-2023-26119). The commonly used browser methods like `goTo`, `url`, `pageSource`, `el` and `$` (including `$(...).click()` and `$(...).fill().with(...)`) keep working, elements are now Selenide elements which wait until they are ready, and `browser.selenide()` gives access to the complete Selenide API. Next to `HTMLUNIT` and `FIREFOX`, there are now also `CHROME`, `EDGE` and `SAFARI` constants to select the browser, and Chrome, Edge and Firefox run headless with `-Dselenide.headless=true`. See the [[migration guide|Migration31#FluentLenium-has-been-replaced-by-Selenide]] for details. ++Play's test browser (`TestBrowser`, used by `WithBrowser`) is now backed by [Selenide](https://selenide.org) instead of the archived FluentLenium project. This brings current Selenium (4.51) and HtmlUnit (5.x) versions, and with them support for current browsers and a fix for [CVE-2023-26119](https://nvd.nist.gov/vuln/detail/CVE-2023-26119). The commonly used browser methods like `goTo`, `url`, `pageSource`, `el` and `$` (including `$(...).click()` and `$(...).fill().with(...)`) keep working, elements are now Selenide elements which wait until they are ready, and `browser.selenide()` gives access to the complete Selenide API. Next to `HTMLUNIT` and `FIREFOX`, there are now also `CHROME`, `EDGE` and `SAFARI` constants to select the browser, and Chrome, Edge and Firefox run headless with `-Dselenide.headless=true`. See the [[migration guide|Migration31#FluentLenium-has-been-replaced-by-Selenide]] for details. + + ### Splitting evolutions without escaping semicolons + +diff --git a/documentation/manual/releases/release31/migration31/Migration31.md b/documentation/manual/releases/release31/migration31/Migration31.md +index f2d6e0fd07..cef547f8f9 100644 +--- a/documentation/manual/releases/release31/migration31/Migration31.md ++++ b/documentation/manual/releases/release31/migration31/Migration31.md +@@ -95,7 +95,7 @@ Both test browsers are now backed by [Selenide](https://selenide.org), which is + + #### Dependency changes + +-`play-test` now depends on `com.codeborne:selenide-core` (which brings Selenium 4.49 via `selenium-java`) and on `org.seleniumhq.selenium:htmlunit3-driver`, which uses HtmlUnit 5 (group id `org.htmlunit`). The `io.fluentlenium`, `org.seleniumhq.selenium:htmlunit-driver` and `net.sourceforge.htmlunit` dependencies have been removed. ++`play-test` now depends on `com.codeborne:selenide-core` (which brings Selenium 4.51 via `selenium-java`) and on `org.seleniumhq.selenium:htmlunit3-driver`, which uses HtmlUnit 5 (group id `org.htmlunit`). The `io.fluentlenium`, `org.seleniumhq.selenium:htmlunit-driver` and `net.sourceforge.htmlunit` dependencies have been removed. + + * If your build adds FluentLenium itself, remove it: FluentLenium 6.0.0 does not work with Selenium 4.17 or newer. + * If your build pins Selenium or `htmlunit-driver` versions (for example for older [ScalaTest + Play](https://github.com/playframework/scalatestplus-play) versions), remove those pins or upgrade them. Do not mix `htmlunit-driver` and `htmlunit3-driver`: both contain the class `org.openqa.selenium.htmlunit.HtmlUnitDriver`. +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5d71afe9fb..9fd9f0d93c 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -244,9 +244,9 @@ object Dependencies { + "org.apache.pekko" %% "pekko-cluster-sharding-typed" % pekkoVersion + ) + +- val selenideVersion = "7.18.2" ++ val selenideVersion = "7.19.0" + // HtmlUnitDriver is not part of Selenium/Selenide, but it is still the default browser of Play's TestBrowser. +- val htmlunitDriverVersion = "4.48.0" ++ val htmlunitDriverVersion = "4.51.0" + + val testDependencies = Seq(junit, junitInterface, guava, logback) ++ Seq( + // selenide-core contains only the instance based API (SelenideDriver), without the static Selenide/WebDriverRunner diff --git a/tasks/playframework__playframework-14351/solution/solve.sh b/tasks/playframework__playframework-14351/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14351/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/playframework__playframework-14351/task.toml b/tasks/playframework__playframework-14351/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..48df4f2583fa02dc1871e25db63f230ada1bbb25 --- /dev/null +++ b/tasks/playframework__playframework-14351/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14351" +description = "Update Selenide to 7.19.0 and HtmlUnitDriver to 4.51.0" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "3968a05259b25a72f14e88f578f5dd4bfe524bea" +reference = "https://github.com/playframework/playframework/pull/14351" +source_access = "auto" +built_at = "2026-11-16T16:09:46.502417+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a1951532d0a3435c350a8ef0c9387230c398c501960aa819953a2e62a298e69b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-12T17:17:08Z" +diff_format = "unified" +context_files = [ + "documentation/manual/releases/release31/Highlights31.md", + "documentation/manual/releases/release31/migration31/Migration31.md", + "project/Dependencies.scala", +] +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:02.546560+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a607dbd6ec6b13b828a3f4842006f6fb6739547f2d31d756d49060fae8d4887e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14351/tests/capture.py b/tasks/playframework__playframework-14351/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14351/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/playframework__playframework-14351/tests/instruction.md b/tasks/playframework__playframework-14351/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eea448e8078d6fc96103e5a8b9bf84e8138b96ad --- /dev/null +++ b/tasks/playframework__playframework-14351/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Update Selenide to 7.19.0 and HtmlUnitDriver to 4.51.0 + +## Description + +## Purpose + +Upgrade `selenide-core` from 7.18.2 to [7.19.0](https://github.com/selenide/selenide/releases/tag/v7.19.0), incorporating the update proposed in #14348, and upgrade `htmlunit3-driver` from 4.48.0 to [4.51.0](https://github.com/SeleniumHQ/htmlunit-driver/releases/tag/4.51.0) (HtmlUnit 5.6.0). + +Selenide 7.19.0 already brings `selenium-java` 4.51.0, matching HtmlUnitDriver's Selenium version. Use that transitive dependency and remove the explicit `selenium-java` declaration and `seleniumVersion` value introduced in the earlier revision of this PR. + +Update the Play 3.1 highlights and migration guide to describe Selenium 4.51 and its dependency path through Selenide. + +## Testing + +- Full `Play-Test` and `Play-Specs2` suites, using `testFull`, and MiMa on Scala 2.13.18 and 3.3.8. +- Root and documentation `validateCode` (formatting, headers and documentation validation). +- Generated Scala 2.13 and Scala 3 POMs declare `selenide-core` 7.19.0 and `htmlunit3-driver` 4.51.0, with no direct `selenium-java` dependency. +- Resolved dependency classpaths on both Scala lines contain Selenide 7.19.0 and Selenium 4.51.0 throughout, including Chrome, Firefox, Edge, Safari and remote drivers. + +The complete Play test matrix is covered by PR CI. + +Implemented and tested with Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3968a05259b2`. 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/playframework__playframework-14351/tests/oracle.patch b/tasks/playframework__playframework-14351/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f5cb95d6cbda64f355d806efbc409652eb1e7642 --- /dev/null +++ b/tasks/playframework__playframework-14351/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/documentation/manual/releases/release31/Highlights31.md b/documentation/manual/releases/release31/Highlights31.md +index ca0655375c..00e189468f 100644 +--- a/documentation/manual/releases/release31/Highlights31.md ++++ b/documentation/manual/releases/release31/Highlights31.md +@@ -12,7 +12,7 @@ Play WS now supports the [HTTP QUERY method](https://www.rfc-editor.org/rfc/rfc1 + + ### Selenide based test browser + +-Play's test browser (`TestBrowser`, used by `WithBrowser`) is now backed by [Selenide](https://selenide.org) instead of the archived FluentLenium project. This brings current Selenium (4.49) and HtmlUnit (5.x) versions, and with them support for current browsers and a fix for [CVE-2023-26119](https://nvd.nist.gov/vuln/detail/CVE-2023-26119). The commonly used browser methods like `goTo`, `url`, `pageSource`, `el` and `$` (including `$(...).click()` and `$(...).fill().with(...)`) keep working, elements are now Selenide elements which wait until they are ready, and `browser.selenide()` gives access to the complete Selenide API. Next to `HTMLUNIT` and `FIREFOX`, there are now also `CHROME`, `EDGE` and `SAFARI` constants to select the browser, and Chrome, Edge and Firefox run headless with `-Dselenide.headless=true`. See the [[migration guide|Migration31#FluentLenium-has-been-replaced-by-Selenide]] for details. ++Play's test browser (`TestBrowser`, used by `WithBrowser`) is now backed by [Selenide](https://selenide.org) instead of the archived FluentLenium project. This brings current Selenium (4.51) and HtmlUnit (5.x) versions, and with them support for current browsers and a fix for [CVE-2023-26119](https://nvd.nist.gov/vuln/detail/CVE-2023-26119). The commonly used browser methods like `goTo`, `url`, `pageSource`, `el` and `$` (including `$(...).click()` and `$(...).fill().with(...)`) keep working, elements are now Selenide elements which wait until they are ready, and `browser.selenide()` gives access to the complete Selenide API. Next to `HTMLUNIT` and `FIREFOX`, there are now also `CHROME`, `EDGE` and `SAFARI` constants to select the browser, and Chrome, Edge and Firefox run headless with `-Dselenide.headless=true`. See the [[migration guide|Migration31#FluentLenium-has-been-replaced-by-Selenide]] for details. + + ### Splitting evolutions without escaping semicolons + +diff --git a/documentation/manual/releases/release31/migration31/Migration31.md b/documentation/manual/releases/release31/migration31/Migration31.md +index f2d6e0fd07..cef547f8f9 100644 +--- a/documentation/manual/releases/release31/migration31/Migration31.md ++++ b/documentation/manual/releases/release31/migration31/Migration31.md +@@ -95,7 +95,7 @@ Both test browsers are now backed by [Selenide](https://selenide.org), which is + + #### Dependency changes + +-`play-test` now depends on `com.codeborne:selenide-core` (which brings Selenium 4.49 via `selenium-java`) and on `org.seleniumhq.selenium:htmlunit3-driver`, which uses HtmlUnit 5 (group id `org.htmlunit`). The `io.fluentlenium`, `org.seleniumhq.selenium:htmlunit-driver` and `net.sourceforge.htmlunit` dependencies have been removed. ++`play-test` now depends on `com.codeborne:selenide-core` (which brings Selenium 4.51 via `selenium-java`) and on `org.seleniumhq.selenium:htmlunit3-driver`, which uses HtmlUnit 5 (group id `org.htmlunit`). The `io.fluentlenium`, `org.seleniumhq.selenium:htmlunit-driver` and `net.sourceforge.htmlunit` dependencies have been removed. + + * If your build adds FluentLenium itself, remove it: FluentLenium 6.0.0 does not work with Selenium 4.17 or newer. + * If your build pins Selenium or `htmlunit-driver` versions (for example for older [ScalaTest + Play](https://github.com/playframework/scalatestplus-play) versions), remove those pins or upgrade them. Do not mix `htmlunit-driver` and `htmlunit3-driver`: both contain the class `org.openqa.selenium.htmlunit.HtmlUnitDriver`. +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5d71afe9fb..9fd9f0d93c 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -244,9 +244,9 @@ object Dependencies { + "org.apache.pekko" %% "pekko-cluster-sharding-typed" % pekkoVersion + ) + +- val selenideVersion = "7.18.2" ++ val selenideVersion = "7.19.0" + // HtmlUnitDriver is not part of Selenium/Selenide, but it is still the default browser of Play's TestBrowser. +- val htmlunitDriverVersion = "4.48.0" ++ val htmlunitDriverVersion = "4.51.0" + + val testDependencies = Seq(junit, junitInterface, guava, logback) ++ Seq( + // selenide-core contains only the instance based API (SelenideDriver), without the static Selenide/WebDriverRunner diff --git a/tasks/playframework__playframework-14351/tests/test.sh b/tasks/playframework__playframework-14351/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b825e95c58b19cb88b2c983181b616c8e88d3355 --- /dev/null +++ b/tasks/playframework__playframework-14351/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 3968a05259b25a72f14e88f578f5dd4bfe524bea > "$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/playframework__playframework-14351/tests/verifier.py b/tasks/playframework__playframework-14351/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14351/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/playframework__playframework-14353/environment/Dockerfile b/tasks/playframework__playframework-14353/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8b2456b22d14e506e5c714c6f0574ba62549885f --- /dev/null +++ b/tasks/playframework__playframework-14353/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 443dddf08d86dd219881cb0fcc9a70d6c1f03cb9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 443dddf08d86dd219881cb0fcc9a70d6c1f03cb9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 443dddf08d86dd219881cb0fcc9a70d6c1f03cb9 \ + && 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/playframework__playframework-14353/instruction.md b/tasks/playframework__playframework-14353/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf535e416ee251cc1d76b7add5696fa25780ffea --- /dev/null +++ b/tasks/playframework__playframework-14353/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.13.Final (was 7.4.12.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.12.Final` to `7.4.13.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/3a458a7b774ba94011976b8d3f41e6dca859fed1/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `443dddf08d86`. 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/playframework__playframework-14353/solution/patch.diff b/tasks/playframework__playframework-14353/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d16db0dc7cedd216d28c2f35cac19ca6773c8c0e --- /dev/null +++ b/tasks/playframework__playframework-14353/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 9cf5266083..d0f75eacab 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 335ab3a008..4629ebf774 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5322a65198..1ee8e9ea64 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.12.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.13.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14353/solution/solve.sh b/tasks/playframework__playframework-14353/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14353/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/playframework__playframework-14353/task.toml b/tasks/playframework__playframework-14353/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da428b932707602d47dbc4df1b2acf72e20d0135 --- /dev/null +++ b/tasks/playframework__playframework-14353/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14353" +description = "hibernate-core, ... 7.4.13.Final (was 7.4.12.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "443dddf08d86dd219881cb0fcc9a70d6c1f03cb9" +reference = "https://github.com/playframework/playframework/pull/14353" +source_access = "auto" +built_at = "2026-11-16T16:09:46.500641+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:504a723304c3cfaca07d4385f174d3f763d0da3894f154ba05d13f5fd016936f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-12T18:46:14Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.547183+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0c3497bb1a53e81749aa3dfde28914fc4ac3518a4063140f0b4ac46784e7d7a6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14353/tests/capture.py b/tasks/playframework__playframework-14353/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14353/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/playframework__playframework-14353/tests/instruction.md b/tasks/playframework__playframework-14353/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf535e416ee251cc1d76b7add5696fa25780ffea --- /dev/null +++ b/tasks/playframework__playframework-14353/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.13.Final (was 7.4.12.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.12.Final` to `7.4.13.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/3a458a7b774ba94011976b8d3f41e6dca859fed1/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `443dddf08d86`. 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/playframework__playframework-14353/tests/oracle.patch b/tasks/playframework__playframework-14353/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d16db0dc7cedd216d28c2f35cac19ca6773c8c0e --- /dev/null +++ b/tasks/playframework__playframework-14353/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 9cf5266083..d0f75eacab 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 335ab3a008..4629ebf774 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 5322a65198..1ee8e9ea64 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.12.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.12.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.13.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14353/tests/test.sh b/tasks/playframework__playframework-14353/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6a30a04a7bab1e8ab41ede8173044ca4a418162 --- /dev/null +++ b/tasks/playframework__playframework-14353/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 443dddf08d86dd219881cb0fcc9a70d6c1f03cb9 > "$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/playframework__playframework-14353/tests/verifier.py b/tasks/playframework__playframework-14353/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14353/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/playframework__playframework-14361/environment/Dockerfile b/tasks/playframework__playframework-14361/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ee9f5af7db5da9984c3b4b0a889296adac50462 --- /dev/null +++ b/tasks/playframework__playframework-14361/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 75db9ee0e643d188ea5a8ed48b06f1634178a7ec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 75db9ee0e643d188ea5a8ed48b06f1634178a7ec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 75db9ee0e643d188ea5a8ed48b06f1634178a7ec \ + && 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/playframework__playframework-14361/instruction.md b/tasks/playframework__playframework-14361/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a7310e3c558f69890906c926c05490290b00b1 --- /dev/null +++ b/tasks/playframework__playframework-14361/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix writing evolution scripts with `Evolutions.updateEvolutionScript` + +## Description + +`Evolutions.updateEvolutionScript` couldn't write any script: +- It created the script's folder with `Files.createDirectory`, which fails if the folder exists already, or if its parent doesn't exist yet, e.g. `conf/evolutions`. +- Before writing, it read the script to compare it with the new content, which fails if there is no script yet. +- It resolved an absolute evolutions path relative to the application's root folder, while the evolutions reader uses it as it is. + +Now it creates all missing folders, writes a new script, only writes an existing one if its content changes, and resolves the path like the evolutions reader. + +The new `UpdateEvolutionScriptSpec` checks with the evolutions reader that the written scripts are found: for the default path, a folder in `conf`, relative and absolute paths, an update, and an unchanged script (which keeps its modification time). Without the fix, all seven examples fail. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `75db9ee0e643`. 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/playframework__playframework-14361/solution/patch.diff b/tasks/playframework__playframework-14361/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..340f684670872df7c11b4b8618869da6185b1aca --- /dev/null +++ b/tasks/playframework__playframework-14361/solution/patch.diff @@ -0,0 +1,131 @@ +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala +index c103079e5d..89728bd54d 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala +@@ -197,8 +197,8 @@ object Evolutions { + ups: String, + downs: String + )(implicit environment: Environment): Unit = { +- val evolutions = environment.getFile(fileName(db, revision, path)) +- Files.createDirectory(environment.getFile(directoryName(db, path)).toPath) ++ val evolutions = file(fileName(db, revision, path)) ++ Files.createDirectories(file(directoryName(db, path)).toPath) + writeFileIfChanged( + evolutions, + """|-- %s +@@ -213,8 +213,17 @@ object Evolutions { + ) + } + ++ /** ++ * Resolves the location of an evolution script like the evolutions reader does: an absolute path as it is, any other ++ * path relative to the application's root folder. ++ */ ++ private def file(path: String)(implicit environment: Environment): File = { ++ val p = Path.of(path) ++ if (p.isAbsolute) p.toFile else environment.getFile(path) ++ } ++ + private def writeFileIfChanged(path: File, content: String): Unit = { +- if (content != PlayIO.readFileAsString(path.toPath)) { ++ if (!path.exists() || content != PlayIO.readFileAsString(path.toPath)) { + writeFile(path, content) + } + } +diff --git a/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala +new file mode 100644 +index 0000000000..2b69043c08 +--- /dev/null ++++ b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala +@@ -0,0 +1,91 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.api.db.evolutions ++ ++import java.nio.file.attribute.FileTime ++import java.nio.file.Files ++import java.nio.file.Path ++ ++import scala.jdk.CollectionConverters._ ++import scala.util.Using ++ ++import org.specs2.mutable.Specification ++import play.api.Environment ++import play.api.Mode ++ ++class UpdateEvolutionScriptSpec extends Specification { ++ ++ /** ++ * Runs the block with a temporary folder, which contains the application's root folder `app`, and leaves room for ++ * folders next to it. ++ */ ++ private def withFolder[T](block: (Path, Environment) => T): T = { ++ val folder = Files.createTempDirectory("update-evolution-script") ++ try { ++ val root = Files.createDirectories(folder.resolve("app")) ++ block(folder, Environment.simple(root.toFile, Mode.Dev)) ++ } finally { ++ Using.resource(Files.walk(folder))(_.iterator().asScala.toList).reverse.foreach(Files.delete) ++ } ++ } ++ ++ /** The evolution scripts in the folder, relative to it. */ ++ private def scripts(folder: Path): Seq[Path] = ++ Using.resource(Files.walk(folder))( ++ _.iterator().asScala.filter(_.getFileName.toString == "1.sql").map(folder.relativize).toList ++ ) ++ ++ /** The evolutions that Play's evolutions read from the path. */ ++ private def read(path: String)(implicit environment: Environment): Seq[(Int, String, String)] = ++ new EnvironmentEvolutionsReader(environment, path) ++ .evolutions("default") ++ .map(evolution => (evolution.revision, evolution.sql_up.trim, evolution.sql_down.trim)) ++ ++ private def update(path: String, ups: String)(implicit environment: Environment): Unit = ++ Evolutions.updateEvolutionScript(path = path, ups = ups, downs = "drop table a;") ++ ++ private def writes(path: String, script: String) = withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update(path, "create table a (id int);") ++ (read(path) must_== Seq((1, "create table a (id int);", "drop table a;"))) ++ .and(scripts(folder) must_== Seq(Path.of(script))) ++ } ++ ++ "Evolutions.updateEvolutionScript" should { ++ ++ "create the first script, and its folders" in writes("evolutions", "app/conf/evolutions/default/1.sql") ++ ++ "write to a folder in conf" in writes("migrations", "app/conf/migrations/default/1.sql") ++ ++ "write to a folder in the project" in writes("./migrations", "app/migrations/default/1.sql") ++ ++ "write to a folder next to the project" in writes("../migrations", "migrations/default/1.sql") ++ ++ "write to an absolute folder as it is" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ val path = folder.resolve("migrations").toAbsolutePath.toString ++ update(path, "create table a (id int);") ++ (read(path) must_== Seq((1, "create table a (id int);", "drop table a;"))) ++ .and(scripts(folder) must_== Seq(Path.of("migrations/default/1.sql"))) ++ } ++ ++ "update an existing script" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update("evolutions", "create table a (id int);") ++ update("evolutions", "create table a (id bigint);") ++ read("evolutions") must_== Seq((1, "create table a (id bigint);", "drop table a;")) ++ } ++ ++ "keep an unchanged script as it is" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update("evolutions", "create table a (id int);") ++ val script = folder.resolve("app/conf/evolutions/default/1.sql") ++ val modified = FileTime.fromMillis(1000) ++ Files.setLastModifiedTime(script, modified) ++ update("evolutions", "create table a (id int);") ++ Files.getLastModifiedTime(script) must_== modified ++ } ++ } ++} diff --git a/tasks/playframework__playframework-14361/solution/solve.sh b/tasks/playframework__playframework-14361/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14361/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/playframework__playframework-14361/task.toml b/tasks/playframework__playframework-14361/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46a6cd6f9ad48ffff50eb5bd7964a772b34dcae1 --- /dev/null +++ b/tasks/playframework__playframework-14361/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14361" +description = "Fix writing evolution scripts with `Evolutions.updateEvolutionScript`" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "75db9ee0e643d188ea5a8ed48b06f1634178a7ec" +reference = "https://github.com/playframework/playframework/pull/14361" +source_access = "auto" +built_at = "2026-11-16T16:09:46.496403+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:210b0bc567e4c3c355696f6bdd459adef189be58695bf8c0f4a92ded1f29019d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-13T12:00:46Z" +diff_format = "unified" +context_files = [ + "persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala", + "persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 106 +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:02.547725+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5521b8afa53fe641e3742809cb20ce12de3d94ac25606496543fca12c73c8b60" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14361/tests/capture.py b/tasks/playframework__playframework-14361/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14361/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/playframework__playframework-14361/tests/instruction.md b/tasks/playframework__playframework-14361/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a7310e3c558f69890906c926c05490290b00b1 --- /dev/null +++ b/tasks/playframework__playframework-14361/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix writing evolution scripts with `Evolutions.updateEvolutionScript` + +## Description + +`Evolutions.updateEvolutionScript` couldn't write any script: +- It created the script's folder with `Files.createDirectory`, which fails if the folder exists already, or if its parent doesn't exist yet, e.g. `conf/evolutions`. +- Before writing, it read the script to compare it with the new content, which fails if there is no script yet. +- It resolved an absolute evolutions path relative to the application's root folder, while the evolutions reader uses it as it is. + +Now it creates all missing folders, writes a new script, only writes an existing one if its content changes, and resolves the path like the evolutions reader. + +The new `UpdateEvolutionScriptSpec` checks with the evolutions reader that the written scripts are found: for the default path, a folder in `conf`, relative and absolute paths, an update, and an unchanged script (which keeps its modification time). Without the fix, all seven examples fail. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `75db9ee0e643`. 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/playframework__playframework-14361/tests/oracle.patch b/tasks/playframework__playframework-14361/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..340f684670872df7c11b4b8618869da6185b1aca --- /dev/null +++ b/tasks/playframework__playframework-14361/tests/oracle.patch @@ -0,0 +1,131 @@ +diff --git a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala +index c103079e5d..89728bd54d 100644 +--- a/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala ++++ b/persistence/play-jdbc-evolutions/src/main/scala/play/api/db/evolutions/Evolutions.scala +@@ -197,8 +197,8 @@ object Evolutions { + ups: String, + downs: String + )(implicit environment: Environment): Unit = { +- val evolutions = environment.getFile(fileName(db, revision, path)) +- Files.createDirectory(environment.getFile(directoryName(db, path)).toPath) ++ val evolutions = file(fileName(db, revision, path)) ++ Files.createDirectories(file(directoryName(db, path)).toPath) + writeFileIfChanged( + evolutions, + """|-- %s +@@ -213,8 +213,17 @@ object Evolutions { + ) + } + ++ /** ++ * Resolves the location of an evolution script like the evolutions reader does: an absolute path as it is, any other ++ * path relative to the application's root folder. ++ */ ++ private def file(path: String)(implicit environment: Environment): File = { ++ val p = Path.of(path) ++ if (p.isAbsolute) p.toFile else environment.getFile(path) ++ } ++ + private def writeFileIfChanged(path: File, content: String): Unit = { +- if (content != PlayIO.readFileAsString(path.toPath)) { ++ if (!path.exists() || content != PlayIO.readFileAsString(path.toPath)) { + writeFile(path, content) + } + } +diff --git a/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala +new file mode 100644 +index 0000000000..2b69043c08 +--- /dev/null ++++ b/persistence/play-jdbc-evolutions/src/test/scala/play/api/db/evolutions/UpdateEvolutionScriptSpec.scala +@@ -0,0 +1,91 @@ ++/* ++ * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. ++ */ ++ ++package play.api.db.evolutions ++ ++import java.nio.file.attribute.FileTime ++import java.nio.file.Files ++import java.nio.file.Path ++ ++import scala.jdk.CollectionConverters._ ++import scala.util.Using ++ ++import org.specs2.mutable.Specification ++import play.api.Environment ++import play.api.Mode ++ ++class UpdateEvolutionScriptSpec extends Specification { ++ ++ /** ++ * Runs the block with a temporary folder, which contains the application's root folder `app`, and leaves room for ++ * folders next to it. ++ */ ++ private def withFolder[T](block: (Path, Environment) => T): T = { ++ val folder = Files.createTempDirectory("update-evolution-script") ++ try { ++ val root = Files.createDirectories(folder.resolve("app")) ++ block(folder, Environment.simple(root.toFile, Mode.Dev)) ++ } finally { ++ Using.resource(Files.walk(folder))(_.iterator().asScala.toList).reverse.foreach(Files.delete) ++ } ++ } ++ ++ /** The evolution scripts in the folder, relative to it. */ ++ private def scripts(folder: Path): Seq[Path] = ++ Using.resource(Files.walk(folder))( ++ _.iterator().asScala.filter(_.getFileName.toString == "1.sql").map(folder.relativize).toList ++ ) ++ ++ /** The evolutions that Play's evolutions read from the path. */ ++ private def read(path: String)(implicit environment: Environment): Seq[(Int, String, String)] = ++ new EnvironmentEvolutionsReader(environment, path) ++ .evolutions("default") ++ .map(evolution => (evolution.revision, evolution.sql_up.trim, evolution.sql_down.trim)) ++ ++ private def update(path: String, ups: String)(implicit environment: Environment): Unit = ++ Evolutions.updateEvolutionScript(path = path, ups = ups, downs = "drop table a;") ++ ++ private def writes(path: String, script: String) = withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update(path, "create table a (id int);") ++ (read(path) must_== Seq((1, "create table a (id int);", "drop table a;"))) ++ .and(scripts(folder) must_== Seq(Path.of(script))) ++ } ++ ++ "Evolutions.updateEvolutionScript" should { ++ ++ "create the first script, and its folders" in writes("evolutions", "app/conf/evolutions/default/1.sql") ++ ++ "write to a folder in conf" in writes("migrations", "app/conf/migrations/default/1.sql") ++ ++ "write to a folder in the project" in writes("./migrations", "app/migrations/default/1.sql") ++ ++ "write to a folder next to the project" in writes("../migrations", "migrations/default/1.sql") ++ ++ "write to an absolute folder as it is" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ val path = folder.resolve("migrations").toAbsolutePath.toString ++ update(path, "create table a (id int);") ++ (read(path) must_== Seq((1, "create table a (id int);", "drop table a;"))) ++ .and(scripts(folder) must_== Seq(Path.of("migrations/default/1.sql"))) ++ } ++ ++ "update an existing script" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update("evolutions", "create table a (id int);") ++ update("evolutions", "create table a (id bigint);") ++ read("evolutions") must_== Seq((1, "create table a (id bigint);", "drop table a;")) ++ } ++ ++ "keep an unchanged script as it is" in withFolder { (folder, env) => ++ implicit val environment: Environment = env ++ update("evolutions", "create table a (id int);") ++ val script = folder.resolve("app/conf/evolutions/default/1.sql") ++ val modified = FileTime.fromMillis(1000) ++ Files.setLastModifiedTime(script, modified) ++ update("evolutions", "create table a (id int);") ++ Files.getLastModifiedTime(script) must_== modified ++ } ++ } ++} diff --git a/tasks/playframework__playframework-14361/tests/test.sh b/tasks/playframework__playframework-14361/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e852d9fc72702bbe2016c4a41b5a058362726ecf --- /dev/null +++ b/tasks/playframework__playframework-14361/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 75db9ee0e643d188ea5a8ed48b06f1634178a7ec > "$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/playframework__playframework-14361/tests/verifier.py b/tasks/playframework__playframework-14361/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14361/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/playframework__playframework-14365/environment/Dockerfile b/tasks/playframework__playframework-14365/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..69aa4aab4609284a066d9c0d7d6e09ff42372274 --- /dev/null +++ b/tasks/playframework__playframework-14365/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 791df2dd6970c02773f39c6916e70059adf559e5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 791df2dd6970c02773f39c6916e70059adf559e5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 791df2dd6970c02773f39c6916e70059adf559e5 \ + && 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/playframework__playframework-14365/instruction.md b/tasks/playframework__playframework-14365/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3df9c5cc039fcde3aa7fd3715c4b04b9665d0e1d --- /dev/null +++ b/tasks/playframework__playframework-14365/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Restore scripted test coverage of `_root_.`-prefixed routes + +## Description + +- #13230 removed `routes-compiler-injected-routes-compilation` as a duplicate.... + +...everything it covered was moved or is still covered by other scripted tests, with one exception: its assets route was declared as `_root_.controllers.Assets.versioned(...)` with `namespaceReverseRouter` left at its default (`false`), which was the regression test for #10153. The only `_root_.` route left in the scripted tests is in `routes-compiler-namespace-reverse-router`, which sets `namespaceReverseRouter := true`, and the documentation routes are compiled with namespacing enabled as well. + +- Prefix the assets route in `routes-compiler-routes-compilation` with `_root_.`. The existing Scala asset tests exercise this configuration under sbt and Gradle, and the existing JavaScript asset tests exercise it under sbt. +- Add a `_root_.`-prefixed route to a Java controller in `routes-compiler-routes-compilation-java`, with a test that reverse-routes and calls it. This adds a focused regression test for `_root_`-prefixed Java controller loading (the `stripPrefix` in `HandlerInvokerFactory.loadJavaControllerClass` from #10153), which the removed Scala-assets fixture did not exercise. The reverse route also only compiles if the prefixed route ends up in the same reverse router as the unprefixed routes to that controller. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `791df2dd6970`. 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/playframework__playframework-14365/solution/patch.diff b/tasks/playframework__playframework-14365/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3529e079fbb83f9b8f82f1c85b3fbb6ba6da922f --- /dev/null +++ b/tasks/playframework__playframework-14365/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java +index ec9fd3404f..81505ffc3f 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java +@@ -119,4 +119,8 @@ public class Application extends Controller { + public Result sameEscapedJavaIdentifier(String brackets, String percent) { + return ok(brackets + percent); + } ++ ++ public Result rootPrefixedController() { ++ return ok(); ++ } + } +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes +index 58349425d7..7a20d36854 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes +@@ -20,6 +20,7 @@ GET /pattern/$x<\d+> controllers.Application.uriPat + GET /multi-params controllers.Application.multiParams(a: Boolean, b: Character, c, d: java.lang.Short, e: java.lang.Integer, f: java.lang.Long, g: java.lang.Float, h: java.lang.Double, i: java.util.UUID, j: java.util.OptionalInt, k: java.util.OptionalLong, l: java.util.OptionalDouble, m, n, o, p, q, r, s, t, u, v, w, x, y, z) + GET /only-request controllers.Application.onlyRequestParam(request: Request) + GET /same-escaped-java-identifier controllers.Application.sameEscapedJavaIdentifier(`[]`, `%%`) ++GET /root-prefixed-controller _root_.controllers.Application.rootPrefixedController + + ### Boolean + GET /bool-p/:x controllers.BooleanController.path(x: java.lang.Boolean) +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java +index e40f88dfec..cc5d3f29b9 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java +@@ -4,6 +4,7 @@ + + package test; + ++import static controllers.routes.Application; + import static org.assertj.core.api.Assertions.assertThat; + import static play.mvc.Http.HttpVerbs.GET; + import static play.mvc.Http.Status.INTERNAL_SERVER_ERROR; +@@ -46,6 +47,14 @@ public class ApplicationTest extends AbstractRoutesTest { + assertThat(contentAsString(result)).isEqualTo("ab"); + } + ++ @Test ++ public void checkRootPrefixedController() { ++ var url = Application.rootPrefixedController().url(); ++ assertThat(url).isEqualTo("/root-prefixed-controller"); ++ var result = route(app, fakeRequest(GET, url)); ++ assertThat(result.status()).isEqualTo(OK); ++ } ++ + @Test + public void checkWebSocket() { + var server = testServer(); +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes +index a86f4f6901..c60936e717 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes +@@ -139,7 +139,8 @@ GET /routestest controllers.Application.routetest(yi + # Test for default values for scala keywords + GET /routesdefault controllers.Application.routedefault(type ?= "x") + +-GET /public/*file controllers.Assets.versioned(path="/public", file: controllers.Assets.Asset) ++# Prefixed with "_root_." while namespaceReverseRouter keeps its default (false), see #10153 ++GET /public/*file _root_.controllers.Assets.versioned(path="/public", file: controllers.Assets.Asset) + + # Test for fixed values for scala keywords + diff --git a/tasks/playframework__playframework-14365/solution/solve.sh b/tasks/playframework__playframework-14365/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14365/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/playframework__playframework-14365/task.toml b/tasks/playframework__playframework-14365/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..34b5e044d58152832d8b779858e7b941797431f8 --- /dev/null +++ b/tasks/playframework__playframework-14365/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14365" +description = "Restore scripted test coverage of `_root_.`-prefixed routes" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "791df2dd6970c02773f39c6916e70059adf559e5" +reference = "https://github.com/playframework/playframework/pull/14365" +source_access = "auto" +built_at = "2026-11-16T16:09:46.494407+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f63fb9407054a08ee6149f519b32e1f36eee1a413eff6d61b8c737ec4e62e4a0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-14T13:22:22Z" +diff_format = "unified" +context_files = [ + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java", + "dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 17 +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:02.548320+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e74649731483e56e5a26fb8724c28f4e1a755cd491d1e54b58d532a680bf1fff" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14365/tests/capture.py b/tasks/playframework__playframework-14365/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14365/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/playframework__playframework-14365/tests/instruction.md b/tasks/playframework__playframework-14365/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3df9c5cc039fcde3aa7fd3715c4b04b9665d0e1d --- /dev/null +++ b/tasks/playframework__playframework-14365/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** Restore scripted test coverage of `_root_.`-prefixed routes + +## Description + +- #13230 removed `routes-compiler-injected-routes-compilation` as a duplicate.... + +...everything it covered was moved or is still covered by other scripted tests, with one exception: its assets route was declared as `_root_.controllers.Assets.versioned(...)` with `namespaceReverseRouter` left at its default (`false`), which was the regression test for #10153. The only `_root_.` route left in the scripted tests is in `routes-compiler-namespace-reverse-router`, which sets `namespaceReverseRouter := true`, and the documentation routes are compiled with namespacing enabled as well. + +- Prefix the assets route in `routes-compiler-routes-compilation` with `_root_.`. The existing Scala asset tests exercise this configuration under sbt and Gradle, and the existing JavaScript asset tests exercise it under sbt. +- Add a `_root_.`-prefixed route to a Java controller in `routes-compiler-routes-compilation-java`, with a test that reverse-routes and calls it. This adds a focused regression test for `_root_`-prefixed Java controller loading (the `stripPrefix` in `HandlerInvokerFactory.loadJavaControllerClass` from #10153), which the removed Scala-assets fixture did not exercise. The reverse route also only compiles if the prefixed route ends up in the same reverse router as the unprefixed routes to that controller. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `791df2dd6970`. 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/playframework__playframework-14365/tests/oracle.patch b/tasks/playframework__playframework-14365/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3529e079fbb83f9b8f82f1c85b3fbb6ba6da922f --- /dev/null +++ b/tasks/playframework__playframework-14365/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java +index ec9fd3404f..81505ffc3f 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/app/controllers/Application.java +@@ -119,4 +119,8 @@ public class Application extends Controller { + public Result sameEscapedJavaIdentifier(String brackets, String percent) { + return ok(brackets + percent); + } ++ ++ public Result rootPrefixedController() { ++ return ok(); ++ } + } +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes +index 58349425d7..7a20d36854 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/conf/routes +@@ -20,6 +20,7 @@ GET /pattern/$x<\d+> controllers.Application.uriPat + GET /multi-params controllers.Application.multiParams(a: Boolean, b: Character, c, d: java.lang.Short, e: java.lang.Integer, f: java.lang.Long, g: java.lang.Float, h: java.lang.Double, i: java.util.UUID, j: java.util.OptionalInt, k: java.util.OptionalLong, l: java.util.OptionalDouble, m, n, o, p, q, r, s, t, u, v, w, x, y, z) + GET /only-request controllers.Application.onlyRequestParam(request: Request) + GET /same-escaped-java-identifier controllers.Application.sameEscapedJavaIdentifier(`[]`, `%%`) ++GET /root-prefixed-controller _root_.controllers.Application.rootPrefixedController + + ### Boolean + GET /bool-p/:x controllers.BooleanController.path(x: java.lang.Boolean) +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java +index e40f88dfec..cc5d3f29b9 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation-java/tests/test/ApplicationTest.java +@@ -4,6 +4,7 @@ + + package test; + ++import static controllers.routes.Application; + import static org.assertj.core.api.Assertions.assertThat; + import static play.mvc.Http.HttpVerbs.GET; + import static play.mvc.Http.Status.INTERNAL_SERVER_ERROR; +@@ -46,6 +47,14 @@ public class ApplicationTest extends AbstractRoutesTest { + assertThat(contentAsString(result)).isEqualTo("ab"); + } + ++ @Test ++ public void checkRootPrefixedController() { ++ var url = Application.rootPrefixedController().url(); ++ assertThat(url).isEqualTo("/root-prefixed-controller"); ++ var result = route(app, fakeRequest(GET, url)); ++ assertThat(result.status()).isEqualTo(OK); ++ } ++ + @Test + public void checkWebSocket() { + var server = testServer(); +diff --git a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes +index a86f4f6901..c60936e717 100644 +--- a/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes ++++ b/dev-mode/sbt-plugin/src/sbt-test/play-sbt-plugin/routes-compiler-routes-compilation/conf/routes +@@ -139,7 +139,8 @@ GET /routestest controllers.Application.routetest(yi + # Test for default values for scala keywords + GET /routesdefault controllers.Application.routedefault(type ?= "x") + +-GET /public/*file controllers.Assets.versioned(path="/public", file: controllers.Assets.Asset) ++# Prefixed with "_root_." while namespaceReverseRouter keeps its default (false), see #10153 ++GET /public/*file _root_.controllers.Assets.versioned(path="/public", file: controllers.Assets.Asset) + + # Test for fixed values for scala keywords + diff --git a/tasks/playframework__playframework-14365/tests/test.sh b/tasks/playframework__playframework-14365/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..663928e73fbe08e8a10ade36210015ac1a62e5f0 --- /dev/null +++ b/tasks/playframework__playframework-14365/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 791df2dd6970c02773f39c6916e70059adf559e5 > "$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/playframework__playframework-14365/tests/verifier.py b/tasks/playframework__playframework-14365/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14365/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/playframework__playframework-14377/environment/Dockerfile b/tasks/playframework__playframework-14377/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b455ead04d92247baa3efc7e5ac27a4fbf641096 --- /dev/null +++ b/tasks/playframework__playframework-14377/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 03987705f48a18da870c2ad87fa67d008a6f210a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 03987705f48a18da870c2ad87fa67d008a6f210a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 03987705f48a18da870c2ad87fa67d008a6f210a \ + && 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/playframework__playframework-14377/instruction.md b/tasks/playframework__playframework-14377/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf18dd5fd09487566f8c04a75c4b4713f896e790 --- /dev/null +++ b/tasks/playframework__playframework-14377/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [2.9.x] hibernate-core 6.6.59.Final (was 6.6.58.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.58.Final` to `6.6.59.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/66303c6b362ad8ff26961ce60fda2b9968e0eeb9/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03987705f48a`. 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/playframework__playframework-14377/solution/patch.diff b/tasks/playframework__playframework-14377/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f368bd06d74ee89642dff20cecd70c2e57561bf2 --- /dev/null +++ b/tasks/playframework__playframework-14377/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 7b0ae21647..1d46c04a54 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index e3d590999b..789024b3c6 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index c524111793..029359e5a5 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -117,7 +117,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14377/solution/solve.sh b/tasks/playframework__playframework-14377/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14377/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/playframework__playframework-14377/task.toml b/tasks/playframework__playframework-14377/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7c8cf80ee7848c19ccf03f475196185b388fc0a --- /dev/null +++ b/tasks/playframework__playframework-14377/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14377" +description = "[2.9.x] hibernate-core 6.6.59.Final (was 6.6.58.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "03987705f48a18da870c2ad87fa67d008a6f210a" +reference = "https://github.com/playframework/playframework/pull/14377" +source_access = "auto" +built_at = "2026-11-16T16:09:46.492432+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4e5f65fd85c3225b34b120e63d2f22d2cf389b2c093a18310bf60d3db54760ec" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-19T08:10:19Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.548967+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f7751731bd0f057530d52fdcbb6c07ff945c5cad22435a16ca04bbc312a13eae" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14377/tests/capture.py b/tasks/playframework__playframework-14377/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14377/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/playframework__playframework-14377/tests/instruction.md b/tasks/playframework__playframework-14377/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf18dd5fd09487566f8c04a75c4b4713f896e790 --- /dev/null +++ b/tasks/playframework__playframework-14377/tests/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [2.9.x] hibernate-core 6.6.59.Final (was 6.6.58.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.58.Final` to `6.6.59.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/66303c6b362ad8ff26961ce60fda2b9968e0eeb9/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03987705f48a`. 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/playframework__playframework-14377/tests/oracle.patch b/tasks/playframework__playframework-14377/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f368bd06d74ee89642dff20cecd70c2e57561bf2 --- /dev/null +++ b/tasks/playframework__playframework-14377/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 7b0ae21647..1d46c04a54 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index e3d590999b..789024b3c6 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index c524111793..029359e5a5 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -117,7 +117,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14377/tests/test.sh b/tasks/playframework__playframework-14377/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ffc08cfcd1337cb5b13dac433305e327194cbbe4 --- /dev/null +++ b/tasks/playframework__playframework-14377/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 03987705f48a18da870c2ad87fa67d008a6f210a > "$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/playframework__playframework-14377/tests/verifier.py b/tasks/playframework__playframework-14377/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14377/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/playframework__playframework-14379/environment/Dockerfile b/tasks/playframework__playframework-14379/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..953b65b408aadd3eecfff456e587dea3c3ac6676 --- /dev/null +++ b/tasks/playframework__playframework-14379/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7b3c0ff3be7358b25595c2da8af201cefe978399 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7b3c0ff3be7358b25595c2da8af201cefe978399 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7b3c0ff3be7358b25595c2da8af201cefe978399 \ + && 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/playframework__playframework-14379/instruction.md b/tasks/playframework__playframework-14379/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b60ae6206ea14c5013cb2f905f6fa73c7dd4bb02 --- /dev/null +++ b/tasks/playframework__playframework-14379/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [3.0.x] hibernate-core 6.6.59.Final (was 6.6.58.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.58.Final` to `6.6.59.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/66303c6b362ad8ff26961ce60fda2b9968e0eeb9/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b3c0ff3be73`. 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/playframework__playframework-14379/solution/patch.diff b/tasks/playframework__playframework-14379/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..228f47a7b047256ab39d92d59d6247e04dc7636b --- /dev/null +++ b/tasks/playframework__playframework-14379/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 7b0ae21647..1d46c04a54 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index e3d590999b..789024b3c6 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 8d7a92e7c4..75f62f37de 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -101,7 +101,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14379/solution/solve.sh b/tasks/playframework__playframework-14379/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14379/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/playframework__playframework-14379/task.toml b/tasks/playframework__playframework-14379/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b5c290fc4e2f373e45c7a0e4fd49f81a116af87 --- /dev/null +++ b/tasks/playframework__playframework-14379/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14379" +description = "[3.0.x] hibernate-core 6.6.59.Final (was 6.6.58.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "7b3c0ff3be7358b25595c2da8af201cefe978399" +reference = "https://github.com/playframework/playframework/pull/14379" +source_access = "auto" +built_at = "2026-11-16T16:09:46.490733+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fb8d8ba93a4934df7be9283d904dce92883360ff65a90e8647cea41cbb404ddc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-19T08:10:25Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.549514+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1390dcdef9e03396ed3014508a8f09b60e7f192a01973b94b77fce97336bcfee" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14379/tests/capture.py b/tasks/playframework__playframework-14379/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14379/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/playframework__playframework-14379/tests/instruction.md b/tasks/playframework__playframework-14379/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b60ae6206ea14c5013cb2f905f6fa73c7dd4bb02 --- /dev/null +++ b/tasks/playframework__playframework-14379/tests/instruction.md @@ -0,0 +1,72 @@ +# Issue + +**Title:** [3.0.x] hibernate-core 6.6.59.Final (was 6.6.58.Final) + +## Description + +## About this PR +📦 Updates [org.hibernate:hibernate-core](https://github.com/hibernate/hibernate-orm) from `6.6.58.Final` to `6.6.59.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/66303c6b362ad8ff26961ce60fda2b9968e0eeb9/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate", artifactId = "hibernate-core" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate", artifactId = "hibernate-core" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b3c0ff3be73`. 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/playframework__playframework-14379/tests/oracle.patch b/tasks/playframework__playframework-14379/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..228f47a7b047256ab39d92d59d6247e04dc7636b --- /dev/null +++ b/tasks/playframework__playframework-14379/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index 7b0ae21647..1d46c04a54 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index e3d590999b..789024b3c6 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -3,7 +3,7 @@ + //#jpa-sbt-dependencies + libraryDependencies ++= Seq( + javaJpa, +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" // replace by your jpa implementation ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" // replace by your jpa implementation + ) + //#jpa-sbt-dependencies + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 8d7a92e7c4..75f62f37de 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -101,7 +101,7 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.1.0", +- "org.hibernate" % "hibernate-core" % "6.6.58.Final" % "test" ++ "org.hibernate" % "hibernate-core" % "6.6.59.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14379/tests/test.sh b/tasks/playframework__playframework-14379/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..07bca7169a4e2d2e5b8a1006ea3bf00156a3461f --- /dev/null +++ b/tasks/playframework__playframework-14379/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 7b3c0ff3be7358b25595c2da8af201cefe978399 > "$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/playframework__playframework-14379/tests/verifier.py b/tasks/playframework__playframework-14379/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14379/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/playframework__playframework-14382/environment/Dockerfile b/tasks/playframework__playframework-14382/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3d0d19daa2a5df0c22bdfc1967a1833b0e6cab32 --- /dev/null +++ b/tasks/playframework__playframework-14382/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cc20f08e72a8771f3482ef988d5047647b20ef63 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cc20f08e72a8771f3482ef988d5047647b20ef63 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cc20f08e72a8771f3482ef988d5047647b20ef63 \ + && 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/playframework__playframework-14382/instruction.md b/tasks/playframework__playframework-14382/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..376e4f49d375773c325bf39f7f1bc435fc4a0336 --- /dev/null +++ b/tasks/playframework__playframework-14382/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Bumpt sbt 1 line to 1.13.0 + +## 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 `cc20f08e72a8`. 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/playframework__playframework-14382/solution/patch.diff b/tasks/playframework__playframework-14382/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..72605bdc3362ab42fc59ff6db8f13b8dd5c0f896 --- /dev/null +++ b/tasks/playframework__playframework-14382/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 5077a02ee0..8b2386b37c 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -47,7 +47,7 @@ jobs: + sbt +update # Fetches dependencies for published 2.13/3.3 artifacts + sbt "-Dscala.version=3.9.x" update # Fetches dependencies for the Scala 3 LTS test lane + sbt "-Dscala.version=3.next" update # Fetches dependencies for the Scala 3 next test lane +- # sbt --sbt-version 1.12.15 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here ++ # sbt --sbt-version 1.13.0 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here + sbt +mimaPreviousClassfiles # Fetches previous artifacts + cd documentation + sbt +update # Fetches documentation dependencies for published artifacts +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.12.15", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], ++ "sbt": [ "1.13.0", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/project/Versions.scala b/project/Versions.scala +index 68f86f1c79..157badbe9f 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -24,6 +24,6 @@ object ScalaVersions { + } + + object SbtVersions { +- val sbt1 = "1.12.15" ++ val sbt1 = "1.13.0" + val sbt2 = "2.1.0-bin-20261019-4937ade-NIGHTLY" + } diff --git a/tasks/playframework__playframework-14382/solution/solve.sh b/tasks/playframework__playframework-14382/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14382/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/playframework__playframework-14382/task.toml b/tasks/playframework__playframework-14382/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..740b7e8b0f2a36fde07fb89bda2237ab0a6e3a8a --- /dev/null +++ b/tasks/playframework__playframework-14382/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14382" +description = "Bumpt sbt 1 line to 1.13.0" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "cc20f08e72a8771f3482ef988d5047647b20ef63" +reference = "https://github.com/playframework/playframework/pull/14382" +source_access = "auto" +built_at = "2026-11-16T16:09:46.489329+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fc6b96cc41ce0ad78d3122f59a858458a0f871aebfa49f0b1ebd9f2168727c36" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-19T10:37:22Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-test.yml", + "project/Versions.scala", +] +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:02.550081+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:125f5ab3fa6f701fde5286fc3ac698d13b40a5bc3a036472873a1954079d87d1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14382/tests/capture.py b/tasks/playframework__playframework-14382/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14382/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/playframework__playframework-14382/tests/instruction.md b/tasks/playframework__playframework-14382/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..376e4f49d375773c325bf39f7f1bc435fc4a0336 --- /dev/null +++ b/tasks/playframework__playframework-14382/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Bumpt sbt 1 line to 1.13.0 + +## 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 `cc20f08e72a8`. 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/playframework__playframework-14382/tests/oracle.patch b/tasks/playframework__playframework-14382/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..72605bdc3362ab42fc59ff6db8f13b8dd5c0f896 --- /dev/null +++ b/tasks/playframework__playframework-14382/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 5077a02ee0..8b2386b37c 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -47,7 +47,7 @@ jobs: + sbt +update # Fetches dependencies for published 2.13/3.3 artifacts + sbt "-Dscala.version=3.9.x" update # Fetches dependencies for the Scala 3 LTS test lane + sbt "-Dscala.version=3.next" update # Fetches dependencies for the Scala 3 next test lane +- # sbt --sbt-version 1.12.15 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here ++ # sbt --sbt-version 1.13.0 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here + sbt +mimaPreviousClassfiles # Fetches previous artifacts + cd documentation + sbt +update # Fetches documentation dependencies for published artifacts +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.12.15", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], ++ "sbt": [ "1.13.0", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/project/Versions.scala b/project/Versions.scala +index 68f86f1c79..157badbe9f 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -24,6 +24,6 @@ object ScalaVersions { + } + + object SbtVersions { +- val sbt1 = "1.12.15" ++ val sbt1 = "1.13.0" + val sbt2 = "2.1.0-bin-20261019-4937ade-NIGHTLY" + } diff --git a/tasks/playframework__playframework-14382/tests/test.sh b/tasks/playframework__playframework-14382/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f37d673d5711ac5709d74aeec87a3aafbd123519 --- /dev/null +++ b/tasks/playframework__playframework-14382/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 cc20f08e72a8771f3482ef988d5047647b20ef63 > "$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/playframework__playframework-14382/tests/verifier.py b/tasks/playframework__playframework-14382/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14382/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/playframework__playframework-14383/environment/Dockerfile b/tasks/playframework__playframework-14383/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ae5b07fdaa6e97a654aa645c93d287729b19fd9 --- /dev/null +++ b/tasks/playframework__playframework-14383/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && 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/playframework__playframework-14383/instruction.md b/tasks/playframework__playframework-14383/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f939c85ef1816a32b91f9dd38f741e219308302f --- /dev/null +++ b/tasks/playframework__playframework-14383/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** Run scripted CI through the sbt client again + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (No issue to close.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (Build and CI only.) +* [x] Have you updated the documentation for both Scala and Java sections? (Nothing to document.) +* [x] Have you added tests for any changed functionality? (The existing scripted tests cover it.) + +## Purpose + +Revert 371f808b80 from #14368. The scripted job runs `env -u SBT_TERMINAL_PROPS sbt --server` instead of `sbt`, because the sbt 1.x scripted runner passed `SBT_TERMINAL_PROPS` from a server that the thin client started on to every sbt it launches. That sbt then had no console channel, and every `~` command failed with "No channel with name console0". sbt/sbt#9917 (fixing sbt/sbt#9916) removes the variable in the 1.x runner, as the sbt 2 runner already does. sbt 1.13.1 contains it, and sbt/sbt#9902 as well. + +## Background Context + +The scripted runner is loaded at the `scriptedSbt` version, so each lane uses its own runner. The sbt 2 lane has had the fix since 2.1.0-RC1. Only the sbt 1 lane needed 1.13.1. + +`main` builds and tests with sbt 1.13.1 and 2.1.0-RC2 since 432255d621. That replaces this PR's former first commit, which moved the sbt 1 lane to 1.13.1, so after the rebase only the revert is left. + +#14384 removes the `~run` fallback for sbt without sbt/sbt#9901 and sbt/sbt#9902, once Play requires sbt 1.13.1 and 2.1.0. + +## References + +- #14368 (restored `~run`, added the workaround), #9983 +- sbt/sbt#9916, sbt/sbt#9917 + +AI assistance: Claude Code (Claude Opus 5.5) prepared the change and rebased it onto `main`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14383/solution/patch.diff b/tasks/playframework__playframework-14383/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..642f89e97a4869f0515537f8a01df6f5dbe8b344 --- /dev/null +++ b/tasks/playframework__playframework-14383/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 201cf10be8..5288722dd9 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -193,14 +193,12 @@ jobs: + ] + # Match each scripted sbt version with the Scala version used to + # build its plugin variant. +- # The sbt 1.x scripted runner inherits terminal settings from a thin-client parent. +- # Use a foreground parent without those settings so ~ commands have a console channel. + cmd: >- + case "$MATRIX_SBT" in + 1.*) export SBT_PLUGIN_SCALA=2.12.x ;; + *) export SBT_PLUGIN_SCALA=3.9.x ;; + esac; +- env -u SBT_TERMINAL_PROPS sbt --server "${{needs.extra-vars.outputs.pekko_version_opts}}" "${{needs.extra-vars.outputs.pekko_http_version_opts}}" " ++ sbt "${{needs.extra-vars.outputs.pekko_version_opts}}" "${{needs.extra-vars.outputs.pekko_http_version_opts}}" " + project Sbt-Plugin; + ++ $SBT_PLUGIN_SCALA; + set scriptedSbt := \"$MATRIX_SBT\"; diff --git a/tasks/playframework__playframework-14383/solution/solve.sh b/tasks/playframework__playframework-14383/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14383/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/playframework__playframework-14383/task.toml b/tasks/playframework__playframework-14383/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32acc293a120ccd1426eedc8fed3a71573bbcca1 --- /dev/null +++ b/tasks/playframework__playframework-14383/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14383" +description = "Run scripted CI through the sbt client again" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa" +reference = "https://github.com/playframework/playframework/pull/14383" +source_access = "auto" +built_at = "2026-11-16T16:09:46.480555+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:30571e9f3c0c91e4eb013b74d58ca06b9c0eaafae18bf42b71ed572434a505f4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T19:50:10Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-test.yml", +] +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:02.550647+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:034112bcbbeda7d5ff77b9f2a3fe03ad38d60c4215341f745bb759cd234ff9d8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14383/tests/capture.py b/tasks/playframework__playframework-14383/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14383/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/playframework__playframework-14383/tests/instruction.md b/tasks/playframework__playframework-14383/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f939c85ef1816a32b91f9dd38f741e219308302f --- /dev/null +++ b/tasks/playframework__playframework-14383/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** Run scripted CI through the sbt client again + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (No issue to close.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (Build and CI only.) +* [x] Have you updated the documentation for both Scala and Java sections? (Nothing to document.) +* [x] Have you added tests for any changed functionality? (The existing scripted tests cover it.) + +## Purpose + +Revert 371f808b80 from #14368. The scripted job runs `env -u SBT_TERMINAL_PROPS sbt --server` instead of `sbt`, because the sbt 1.x scripted runner passed `SBT_TERMINAL_PROPS` from a server that the thin client started on to every sbt it launches. That sbt then had no console channel, and every `~` command failed with "No channel with name console0". sbt/sbt#9917 (fixing sbt/sbt#9916) removes the variable in the 1.x runner, as the sbt 2 runner already does. sbt 1.13.1 contains it, and sbt/sbt#9902 as well. + +## Background Context + +The scripted runner is loaded at the `scriptedSbt` version, so each lane uses its own runner. The sbt 2 lane has had the fix since 2.1.0-RC1. Only the sbt 1 lane needed 1.13.1. + +`main` builds and tests with sbt 1.13.1 and 2.1.0-RC2 since 432255d621. That replaces this PR's former first commit, which moved the sbt 1 lane to 1.13.1, so after the rebase only the revert is left. + +#14384 removes the `~run` fallback for sbt without sbt/sbt#9901 and sbt/sbt#9902, once Play requires sbt 1.13.1 and 2.1.0. + +## References + +- #14368 (restored `~run`, added the workaround), #9983 +- sbt/sbt#9916, sbt/sbt#9917 + +AI assistance: Claude Code (Claude Opus 5.5) prepared the change and rebased it onto `main`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14383/tests/oracle.patch b/tasks/playframework__playframework-14383/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..642f89e97a4869f0515537f8a01df6f5dbe8b344 --- /dev/null +++ b/tasks/playframework__playframework-14383/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 201cf10be8..5288722dd9 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -193,14 +193,12 @@ jobs: + ] + # Match each scripted sbt version with the Scala version used to + # build its plugin variant. +- # The sbt 1.x scripted runner inherits terminal settings from a thin-client parent. +- # Use a foreground parent without those settings so ~ commands have a console channel. + cmd: >- + case "$MATRIX_SBT" in + 1.*) export SBT_PLUGIN_SCALA=2.12.x ;; + *) export SBT_PLUGIN_SCALA=3.9.x ;; + esac; +- env -u SBT_TERMINAL_PROPS sbt --server "${{needs.extra-vars.outputs.pekko_version_opts}}" "${{needs.extra-vars.outputs.pekko_http_version_opts}}" " ++ sbt "${{needs.extra-vars.outputs.pekko_version_opts}}" "${{needs.extra-vars.outputs.pekko_http_version_opts}}" " + project Sbt-Plugin; + ++ $SBT_PLUGIN_SCALA; + set scriptedSbt := \"$MATRIX_SBT\"; diff --git a/tasks/playframework__playframework-14383/tests/test.sh b/tasks/playframework__playframework-14383/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f76a0fcfa9c0a248441712465356a3422a7f6e87 --- /dev/null +++ b/tasks/playframework__playframework-14383/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 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa > "$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/playframework__playframework-14383/tests/verifier.py b/tasks/playframework__playframework-14383/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14383/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/playframework__playframework-14384/environment/Dockerfile b/tasks/playframework__playframework-14384/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ae5b07fdaa6e97a654aa645c93d287729b19fd9 --- /dev/null +++ b/tasks/playframework__playframework-14384/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && 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/playframework__playframework-14384/instruction.md b/tasks/playframework__playframework-14384/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a46f7cc7a4d51e783584fe6e6e3eec8528d1933f --- /dev/null +++ b/tasks/playframework__playframework-14384/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** Require sbt 1.13.1 and 2.1.0, remove the ~run channel fallback + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (No issue to close.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (Shared sbt development-mode support.) +* [x] Have you updated the documentation for both Scala and Java sections? (Shared migration guide.) +* [x] Have you added tests for any changed functionality? (Removes a fallback; no new behaviour.) + +## Status + +Play builds and tests with sbt 1.13.1 and 2.1.0-RC2 since #14405, and both contain the fixes. This PR changes no sbt version. The migration guide names 2.1.0, which isn't released yet. + +## Purpose + +- Remove `watchChannelName` from `PlayRun`. The `Compile / run / watchOnTermination` hook now reads the channel with `channelName(state)`, like the rest of the continuous run code. +- Document the minimum sbt versions in the "sbt upgrade" section of the Play 3.1 migration guide, which was TBD. The "Minimum required Java and sbt version" section stays TBD because of its Java part. + +## Background Context + +Without sbt/sbt#9901 (sbt 2) and sbt/sbt#9902 (sbt 1.13.x), sbt runs the watch termination callbacks of a cancelled or disconnected watch without the watch's source. `state.source` is then empty, and the hook would use the console channel. #14368 therefore recovers the channel from sbt's internal `__stopWatch ` and `__failWatch ` commands. With sbt 1.13.1 and 2.1.0, `state.source` is the channel of the ending watch. + +On older sbt, without the fallback, a `~run` started from an sbt client leaves the development server running after the watch ends. Watches in the sbt server's own console are not affected. The plugin has no runtime sbt version check, so the migration guide states the requirement. + +sbt/sbt#9902 is in sbt 1.13.1, and sbt/sbt#9901 is in 2.1.0-RC2. + +## References + +- #14368 (restored `~run`, added the fallback), #9983 +- sbt/sbt#9901, sbt/sbt#9902 +- #14405 (sbt 1.13.1 and 2.1.0-RC2), #14383 (scripted CI through the sbt client again) + +AI assistance: Claude Code (Claude Opus 5.5) prepared the change. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14384/solution/patch.diff b/tasks/playframework__playframework-14384/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..53925c4eea6a5f78b693686c184eadef3acc8b99 --- /dev/null +++ b/tasks/playframework__playframework-14384/solution/patch.diff @@ -0,0 +1,54 @@ +diff --git a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +index 108e783c0b..971bdb3d2a 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +@@ -54,27 +54,13 @@ object PlayRun { + val previous = (Compile / run / watchOnTermination).?.value.getOrElse(NioWatch.defaultCommandOnTermination) + (action, command, count, state) => + try previous(action, command, count, state) +- finally PlayContinuousRun.stop(project, watchChannelName(state)) ++ finally PlayContinuousRun.stop(project, channelName(state)) + } + ) + + private def channelName(state: State): String = + state.source.map(_.channelName).getOrElse(ConsoleChannel.defaultName) + +- // This workaround can be removed once Play requires sbt 1.13.1+ and sbt 2.1.0+. +- // See https://github.com/sbt/sbt/pull/9901 and https://github.com/sbt/sbt/pull/9902. +- private def watchChannelName(state: State): String = +- state.currentCommand +- .flatMap { exec => +- // sbt's cancellation and disconnect commands omit CommandSource. The channel +- // being stopped is their argument, even when another channel issued the command. +- Seq(ContinuousCommands.stopWatch, ContinuousCommands.failWatch) +- .map(_ + " ") +- .find(prefix => exec.commandLine.startsWith(prefix)) +- .map(prefix => exec.commandLine.stripPrefix(prefix).trim) +- } +- .getOrElse(channelName(state)) +- + private def isCompileRun(key: ScopedKey[?]): Boolean = + key.key == Keys.run.key && key.scope.config.toOption.exists(_.name == Compile.name) + +diff --git a/documentation/manual/releases/release31/migration31/Migration31.md b/documentation/manual/releases/release31/migration31/Migration31.md +index ae2111ce2d..83e6e53fb0 100644 +--- a/documentation/manual/releases/release31/migration31/Migration31.md ++++ b/documentation/manual/releases/release31/migration31/Migration31.md +@@ -14,7 +14,15 @@ TBD + + ### sbt upgrade + +-TBD ++Play 3.1 supports sbt 1.13.1 or newer in the sbt 1.x family, and sbt 2.1.0 or newer. To update, change your `project/build.properties` so that it reads: ++ ++```properties ++sbt.version=2.1.0 ++``` ++ ++To stay on sbt 1, use `sbt.version=1.13.1` instead. Check the release notes for sbt's [releases](https://github.com/sbt/sbt/releases) for details. ++ ++With older sbt versions, `~run` started from an sbt client (`sbt --client`, the default in sbt 2) does not stop the development server when the watch ends. + + ### Minimum required Java and sbt version + diff --git a/tasks/playframework__playframework-14384/solution/solve.sh b/tasks/playframework__playframework-14384/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14384/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/playframework__playframework-14384/task.toml b/tasks/playframework__playframework-14384/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..89591abe9642f3aa5b92d4264eb24d5e4f3e60cb --- /dev/null +++ b/tasks/playframework__playframework-14384/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14384" +description = "Require sbt 1.13.1 and 2.1.0, remove the ~run channel fallback" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa" +reference = "https://github.com/playframework/playframework/pull/14384" +source_access = "auto" +built_at = "2026-11-16T16:09:46.476164+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cde6f20b36fd68f5431654f2f179d2aecb30b6d3030179791e8da589c6d768e8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T19:50:29Z" +diff_format = "unified" +context_files = [ + "dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala", + "documentation/manual/releases/release31/migration31/Migration31.md", +] +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:02.551182+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:034112bcbbeda7d5ff77b9f2a3fe03ad38d60c4215341f745bb759cd234ff9d8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14384/tests/capture.py b/tasks/playframework__playframework-14384/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14384/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/playframework__playframework-14384/tests/instruction.md b/tasks/playframework__playframework-14384/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a46f7cc7a4d51e783584fe6e6e3eec8528d1933f --- /dev/null +++ b/tasks/playframework__playframework-14384/tests/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** Require sbt 1.13.1 and 2.1.0, remove the ~run channel fallback + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (No issue to close.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (Shared sbt development-mode support.) +* [x] Have you updated the documentation for both Scala and Java sections? (Shared migration guide.) +* [x] Have you added tests for any changed functionality? (Removes a fallback; no new behaviour.) + +## Status + +Play builds and tests with sbt 1.13.1 and 2.1.0-RC2 since #14405, and both contain the fixes. This PR changes no sbt version. The migration guide names 2.1.0, which isn't released yet. + +## Purpose + +- Remove `watchChannelName` from `PlayRun`. The `Compile / run / watchOnTermination` hook now reads the channel with `channelName(state)`, like the rest of the continuous run code. +- Document the minimum sbt versions in the "sbt upgrade" section of the Play 3.1 migration guide, which was TBD. The "Minimum required Java and sbt version" section stays TBD because of its Java part. + +## Background Context + +Without sbt/sbt#9901 (sbt 2) and sbt/sbt#9902 (sbt 1.13.x), sbt runs the watch termination callbacks of a cancelled or disconnected watch without the watch's source. `state.source` is then empty, and the hook would use the console channel. #14368 therefore recovers the channel from sbt's internal `__stopWatch ` and `__failWatch ` commands. With sbt 1.13.1 and 2.1.0, `state.source` is the channel of the ending watch. + +On older sbt, without the fallback, a `~run` started from an sbt client leaves the development server running after the watch ends. Watches in the sbt server's own console are not affected. The plugin has no runtime sbt version check, so the migration guide states the requirement. + +sbt/sbt#9902 is in sbt 1.13.1, and sbt/sbt#9901 is in 2.1.0-RC2. + +## References + +- #14368 (restored `~run`, added the fallback), #9983 +- sbt/sbt#9901, sbt/sbt#9902 +- #14405 (sbt 1.13.1 and 2.1.0-RC2), #14383 (scripted CI through the sbt client again) + +AI assistance: Claude Code (Claude Opus 5.5) prepared the change. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14384/tests/oracle.patch b/tasks/playframework__playframework-14384/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..53925c4eea6a5f78b693686c184eadef3acc8b99 --- /dev/null +++ b/tasks/playframework__playframework-14384/tests/oracle.patch @@ -0,0 +1,54 @@ +diff --git a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +index 108e783c0b..971bdb3d2a 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +@@ -54,27 +54,13 @@ object PlayRun { + val previous = (Compile / run / watchOnTermination).?.value.getOrElse(NioWatch.defaultCommandOnTermination) + (action, command, count, state) => + try previous(action, command, count, state) +- finally PlayContinuousRun.stop(project, watchChannelName(state)) ++ finally PlayContinuousRun.stop(project, channelName(state)) + } + ) + + private def channelName(state: State): String = + state.source.map(_.channelName).getOrElse(ConsoleChannel.defaultName) + +- // This workaround can be removed once Play requires sbt 1.13.1+ and sbt 2.1.0+. +- // See https://github.com/sbt/sbt/pull/9901 and https://github.com/sbt/sbt/pull/9902. +- private def watchChannelName(state: State): String = +- state.currentCommand +- .flatMap { exec => +- // sbt's cancellation and disconnect commands omit CommandSource. The channel +- // being stopped is their argument, even when another channel issued the command. +- Seq(ContinuousCommands.stopWatch, ContinuousCommands.failWatch) +- .map(_ + " ") +- .find(prefix => exec.commandLine.startsWith(prefix)) +- .map(prefix => exec.commandLine.stripPrefix(prefix).trim) +- } +- .getOrElse(channelName(state)) +- + private def isCompileRun(key: ScopedKey[?]): Boolean = + key.key == Keys.run.key && key.scope.config.toOption.exists(_.name == Compile.name) + +diff --git a/documentation/manual/releases/release31/migration31/Migration31.md b/documentation/manual/releases/release31/migration31/Migration31.md +index ae2111ce2d..83e6e53fb0 100644 +--- a/documentation/manual/releases/release31/migration31/Migration31.md ++++ b/documentation/manual/releases/release31/migration31/Migration31.md +@@ -14,7 +14,15 @@ TBD + + ### sbt upgrade + +-TBD ++Play 3.1 supports sbt 1.13.1 or newer in the sbt 1.x family, and sbt 2.1.0 or newer. To update, change your `project/build.properties` so that it reads: ++ ++```properties ++sbt.version=2.1.0 ++``` ++ ++To stay on sbt 1, use `sbt.version=1.13.1` instead. Check the release notes for sbt's [releases](https://github.com/sbt/sbt/releases) for details. ++ ++With older sbt versions, `~run` started from an sbt client (`sbt --client`, the default in sbt 2) does not stop the development server when the watch ends. + + ### Minimum required Java and sbt version + diff --git a/tasks/playframework__playframework-14384/tests/test.sh b/tasks/playframework__playframework-14384/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f76a0fcfa9c0a248441712465356a3422a7f6e87 --- /dev/null +++ b/tasks/playframework__playframework-14384/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 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa > "$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/playframework__playframework-14384/tests/verifier.py b/tasks/playframework__playframework-14384/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14384/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/playframework__playframework-14388/environment/Dockerfile b/tasks/playframework__playframework-14388/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ae5b07fdaa6e97a654aa645c93d287729b19fd9 --- /dev/null +++ b/tasks/playframework__playframework-14388/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa \ + && 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/playframework__playframework-14388/instruction.md b/tasks/playframework__playframework-14388/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..411c14624837061aa2ae93f2ec7a1a888b60e223 --- /dev/null +++ b/tasks/playframework__playframework-14388/instruction.md @@ -0,0 +1,75 @@ +# Issue + +**Title:** Stop `run` with Enter and Ctrl+D from any sbt client + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (The issue is sbt/sbt#6782, which the sbt PR closes.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (sbt plugin only.) +* [x] Have you updated the documentation for both Scala and Java sections? (No change needed: `PlayConsole.md` already says that Enter and Ctrl+D stop the server.) +* [ ] Have you added tests for any changed functionality? (No automated test; the checks below drive real terminals.) + +## Fixes + +- sbt/sbt#6782 + +## Purpose + +Stop `run` with Enter and Ctrl+D from any sbt client. With `sbt --client` in a terminal other than the one that started the sbt server, which with sbt 2 is any further terminal, Enter reaches Play as 10 and Ctrl+D as end of file, so only Ctrl+C stops the development server. The same applies to `runProd` and the deprecated `start` and `testProd`. + +## Background Context + +Play reads the keys with a jline 2 `ConsoleReader`. Its `UnixTerminal` runs `stty` on `/dev/tty` of the sbt server, which is the terminal that started the server, not the terminal of the client that runs the task. The client's terminal stays in canonical mode, where it translates carriage return to line feed and treats Ctrl+D as end of file. + +- **Raw mode of the client's terminal.** `PlayConsoleInteractionMode.waitForCancel(sbt.Terminal)` reads the keys from the terminal that sbt gives the task, inside the new `sbt.Terminal.withRawInput` (sbt/sbt#9948 for sbt 2.1, sbt/sbt#9949 for sbt 1.13). sbt applies it to the terminal of the client that runs the task. Enter (13) and Ctrl+D (4) stop, Ctrl+J (10) still prints an empty line, and Ctrl+K (11) clears the screen. `run` passes the terminal of its task, and `runProd`, `start` and `testProd` run the `terminal` task. Other interaction modes are unchanged. +- **sbt versions.** `sbt.Terminal.withRawInput` is in sbt 1.13.1 and 2.1.0-RC2, which `main` builds against since 432255d621, so Play calls it directly. The sbt plugin therefore needs at least these versions. On sbt 1.13.0, `run` starts the development server, stops it again right away and fails with `NoSuchMethodError: sbt.Terminal.withRawInput`. +- **Ctrl+K.** It no longer checks `Colors.isANSISupported`, which reads the system properties of the sbt server, not the client's. sbt already removes escape sequences for clients without ANSI support, so Play writes `ESC[2J ESC[999A ESC[999D` unconditionally. It moves the cursor to the top left with relative moves, because sbt removes those for such clients, but not absolute positions. The jline 2 fallback still calls `clearScreen()`. +- **End of file.** Both loops pause for 50 ms after a read returns end of file. Before, with redirected input, every read returned at once, so the loop kept a CPU core busy, and because such a read doesn't check for interruption, cancelling might not stop it. End of file still doesn't stop the server, . + +## Validation + +Agent-run on Linux, JDK 17.0.20, with a Play Java application, after the rebase onto `main`. Play from this branch published locally, with the released sbt 2.1.0-RC2 and 1.13.1, driven through pseudo-terminals. The sbt server was started from one terminal and the task from a `sbt --client` in a second one. On both sbt versions: + +- `run`: + - While it waits, the second terminal is in raw mode (`-icanon -icrnl -echo`, `isig` kept) and the first one is unchanged. + - Enter and Ctrl+D stop it, Ctrl+J keeps it running, Ctrl+K writes the clear sequence, and Ctrl+C cancels it before the application has served a request (after one, see below). + - After the client exits, its terminal is in canonical mode with echo again. + - When the client's terminal closes, the client exits and the server stays below 1% CPU. + - With plain `sbt`, Enter and Ctrl+D stop it and Ctrl+J keeps it running. + - With input piped as by IntelliJ's sbt shell, a line feed keeps it running and a carriage return stops it. With input at end of file, it keeps running and the server stays below 1% CPU. +- `runProd --no-exit-sbt`: the second terminal is raw and the first one unchanged while it waits, Ctrl+J keeps it waiting, Ctrl+D returns to the prompt while the production server keeps running, and `stopProd` stops it. +- sbt 1.13.0, which doesn't have the method, with plain `sbt`: `run` fails with `NoSuchMethodError` and stops the development server, and the prompt comes back. +- The plugin compiles for sbt 1 (Scala 2.12) and sbt 2 (Scala 3.9), and `scalafmtCheckAll` and `headerCheckAll` pass for it. + +Before the rebase, the same checks and `validateCode` passed with the reflection lookup and locally built sbt. + +Not tested: Windows, IntelliJ itself, and `start` and `testProd` separately (they share `runProd`'s code). + +Found while testing, in sbt: + +- sbt/sbt#9946: after the application has served a request, Ctrl+C in a thin client exits the client and leaves `run` running, because Play's reload compile is a nested task evaluation. Fixed for sbt 2 by sbt/sbt#9979, which is in 2.1.0-RC2. +- sbt/sbt#9947: on sbt 1, `cancel` can't stop a `run` whose client disconnected, and new clients get no prompt afterwards. Fixed in sbt 1.13.1 by sbt/sbt#9958; with 1.13.1, a new client got a prompt and cancelled the orphaned `run`. + +## References + +- sbt/sbt#6782 +- sbt/sbt#9948, sbt/sbt#9949 +- #11086, #11088 (why end of file doesn't stop the server) + +AI assistance: Claude Code (Claude Opus 5.5) implemented and tested the change. OpenAI Codex (GPT-6) reviewed it and reran the checks. After the rebase, Claude Code replaced the reflection lookup with a direct call and reran the checks with the released sbt versions. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14388/solution/patch.diff b/tasks/playframework__playframework-14388/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..006ab6628f975a8312bbbaa306b3b2d6ef1426e4 --- /dev/null +++ b/tasks/playframework__playframework-14388/solution/patch.diff @@ -0,0 +1,101 @@ +diff --git a/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala b/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala +index 0a3fa6740f..68054d79c9 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala +@@ -97,7 +97,9 @@ object PlayConsoleInteractionMode extends PlayInteractionMode { + case 4 | 13 => // STOP on Ctrl-D or Enter + case 11 => consoleReader.clearScreen(); waitEOF() + case 10 => println(); waitEOF() +- case _ => waitEOF() ++ // EOF, e.g. with redirected input: wait instead of spinning ++ case -1 => Thread.sleep(50); waitEOF() ++ case _ => waitEOF() + } + } + doWithoutEcho(waitEOF()) +@@ -115,6 +117,34 @@ object PlayConsoleInteractionMode extends PlayInteractionMode { + + override def waitForCancel(): Unit = waitForKey() + ++ /** ++ * Like waitForCancel(), but reads the keys from the given sbt terminal, which belongs to the ++ * sbt console or thin client that runs the task. The terminal is put into raw mode, so that ++ * Enter (13) and Ctrl-D (4) stop and Ctrl-J (10) prints a new line, whichever terminal started ++ * the sbt server. ++ */ ++ def waitForCancel(terminal: sbt.Terminal): Unit = terminal.withRawInput(waitForKey(terminal)) ++ ++ private def waitForKey(terminal: sbt.Terminal): Unit = { ++ val out = terminal.printStream ++ @tailrec def waitEOF(): Unit = { ++ terminal.inputStream.read() match { ++ case 4 | 13 => // STOP on Ctrl-D or Enter ++ case 11 => ++ // Clear the screen, then move the cursor to the top left with relative moves, because sbt ++ // removes those for clients without ANSI support, but not absolute cursor positions ++ out.print("\u001b[2J\u001b[999A\u001b[999D") ++ out.flush() ++ waitEOF() ++ case 10 => out.println(); waitEOF() ++ // EOF, e.g. with redirected input: wait instead of spinning ++ case -1 => Thread.sleep(50); waitEOF() ++ case _ => waitEOF() ++ } ++ } ++ waitEOF() ++ } ++ + override def toString = "Console Interaction Mode" + } + +diff --git a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +index 108e783c0b..43f9bb93c3 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +@@ -31,6 +31,7 @@ import play.runsupport.DevServerSettings + import play.runsupport.GeneratedSourceMapping + import play.sbt.run.PlayReload + import play.sbt.Colors ++import play.sbt.PlayConsoleInteractionMode + import play.sbt.PlayImport.* + import play.sbt.PlayImport.PlayKeys.* + import play.sbt.PlayInteractionMode +@@ -83,6 +84,12 @@ object PlayRun { + .channelForName(channel) + .exists(channel => ContinuousCommands.isInWatch(state, channel)) + ++ private def waitForCancel(interaction: PlayInteractionMode, terminal: Option[Terminal]): Unit = ++ (interaction, terminal) match { ++ case (PlayConsoleInteractionMode, Some(term)) => PlayConsoleInteractionMode.waitForCancel(term) ++ case _ => interaction.waitForCancel() ++ } ++ + private class ContinuousInteractionMode(project: ProjectRef, state: State, log: Logger) extends PlayInteractionMode { + override def waitForCancel(): Unit = () + override def doWithoutEcho(f: => Unit): Unit = f +@@ -144,6 +151,7 @@ object PlayRun { + val runKey = resolvedScoped.value + val scope = runKey.scope + val log = streams.value.log ++ val term = terminal.value + val watching = isWatching(state, channelName(state)) + val interaction = interactionMode.getOrElse { + // Play installs its watch termination hook only for Compile / run (playWatchSettings). Other keys built with +@@ -234,7 +242,7 @@ object PlayRun { + + try { + // run mode +- interaction.waitForCancel() ++ waitForCancel(interaction, Some(term)) + } finally { + devModeServer.close() + println() +@@ -350,7 +358,7 @@ object PlayRun { + | """.stripMargin + println(Colors.green(msg)) + +- interaction.waitForCancel() ++ waitForCancel(interaction, PluginCompat.runTask(terminal, state).flatMap(_._2.toEither.toOption)) + println() + + if (noExitSbt) state diff --git a/tasks/playframework__playframework-14388/solution/solve.sh b/tasks/playframework__playframework-14388/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14388/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/playframework__playframework-14388/task.toml b/tasks/playframework__playframework-14388/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4096c0af0d58c9b25e66d635c1399a3052e7f110 --- /dev/null +++ b/tasks/playframework__playframework-14388/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14388" +description = "Stop `run` with Enter and Ctrl+D from any sbt client" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa" +reference = "https://github.com/playframework/playframework/pull/14388" +source_access = "auto" +built_at = "2026-11-16T16:09:46.478338+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:71ead152688eadc2edc1fd4f9180d85c5db0b6cb70be639c81cd9c5ce2e9a456" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T19:50:21Z" +diff_format = "unified" +context_files = [ + "dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala", + "dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala", +] +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:02.551725+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:034112bcbbeda7d5ff77b9f2a3fe03ad38d60c4215341f745bb759cd234ff9d8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14388/tests/capture.py b/tasks/playframework__playframework-14388/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14388/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/playframework__playframework-14388/tests/instruction.md b/tasks/playframework__playframework-14388/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..411c14624837061aa2ae93f2ec7a1a888b60e223 --- /dev/null +++ b/tasks/playframework__playframework-14388/tests/instruction.md @@ -0,0 +1,75 @@ +# Issue + +**Title:** Stop `run` with Enter and Ctrl+D from any sbt client + +## Description + +# Pull Request Checklist + +* [x] Have you read [How to write the perfect pull request](https://github.blog/2015-01-21-how-to-write-the-perfect-pull-request/)? +* [x] Have you read through the [contributor guidelines](https://www.playframework.com/contributing)? +* [x] Have you referenced any issues you're fixing using ? (The issue is sbt/sbt#6782, which the sbt PR closes.) +* [x] Have you added copyright headers to new files? (No new files.) +* [x] Have you checked that both Scala and Java APIs are updated? (sbt plugin only.) +* [x] Have you updated the documentation for both Scala and Java sections? (No change needed: `PlayConsole.md` already says that Enter and Ctrl+D stop the server.) +* [ ] Have you added tests for any changed functionality? (No automated test; the checks below drive real terminals.) + +## Fixes + +- sbt/sbt#6782 + +## Purpose + +Stop `run` with Enter and Ctrl+D from any sbt client. With `sbt --client` in a terminal other than the one that started the sbt server, which with sbt 2 is any further terminal, Enter reaches Play as 10 and Ctrl+D as end of file, so only Ctrl+C stops the development server. The same applies to `runProd` and the deprecated `start` and `testProd`. + +## Background Context + +Play reads the keys with a jline 2 `ConsoleReader`. Its `UnixTerminal` runs `stty` on `/dev/tty` of the sbt server, which is the terminal that started the server, not the terminal of the client that runs the task. The client's terminal stays in canonical mode, where it translates carriage return to line feed and treats Ctrl+D as end of file. + +- **Raw mode of the client's terminal.** `PlayConsoleInteractionMode.waitForCancel(sbt.Terminal)` reads the keys from the terminal that sbt gives the task, inside the new `sbt.Terminal.withRawInput` (sbt/sbt#9948 for sbt 2.1, sbt/sbt#9949 for sbt 1.13). sbt applies it to the terminal of the client that runs the task. Enter (13) and Ctrl+D (4) stop, Ctrl+J (10) still prints an empty line, and Ctrl+K (11) clears the screen. `run` passes the terminal of its task, and `runProd`, `start` and `testProd` run the `terminal` task. Other interaction modes are unchanged. +- **sbt versions.** `sbt.Terminal.withRawInput` is in sbt 1.13.1 and 2.1.0-RC2, which `main` builds against since 432255d621, so Play calls it directly. The sbt plugin therefore needs at least these versions. On sbt 1.13.0, `run` starts the development server, stops it again right away and fails with `NoSuchMethodError: sbt.Terminal.withRawInput`. +- **Ctrl+K.** It no longer checks `Colors.isANSISupported`, which reads the system properties of the sbt server, not the client's. sbt already removes escape sequences for clients without ANSI support, so Play writes `ESC[2J ESC[999A ESC[999D` unconditionally. It moves the cursor to the top left with relative moves, because sbt removes those for such clients, but not absolute positions. The jline 2 fallback still calls `clearScreen()`. +- **End of file.** Both loops pause for 50 ms after a read returns end of file. Before, with redirected input, every read returned at once, so the loop kept a CPU core busy, and because such a read doesn't check for interruption, cancelling might not stop it. End of file still doesn't stop the server, . + +## Validation + +Agent-run on Linux, JDK 17.0.20, with a Play Java application, after the rebase onto `main`. Play from this branch published locally, with the released sbt 2.1.0-RC2 and 1.13.1, driven through pseudo-terminals. The sbt server was started from one terminal and the task from a `sbt --client` in a second one. On both sbt versions: + +- `run`: + - While it waits, the second terminal is in raw mode (`-icanon -icrnl -echo`, `isig` kept) and the first one is unchanged. + - Enter and Ctrl+D stop it, Ctrl+J keeps it running, Ctrl+K writes the clear sequence, and Ctrl+C cancels it before the application has served a request (after one, see below). + - After the client exits, its terminal is in canonical mode with echo again. + - When the client's terminal closes, the client exits and the server stays below 1% CPU. + - With plain `sbt`, Enter and Ctrl+D stop it and Ctrl+J keeps it running. + - With input piped as by IntelliJ's sbt shell, a line feed keeps it running and a carriage return stops it. With input at end of file, it keeps running and the server stays below 1% CPU. +- `runProd --no-exit-sbt`: the second terminal is raw and the first one unchanged while it waits, Ctrl+J keeps it waiting, Ctrl+D returns to the prompt while the production server keeps running, and `stopProd` stops it. +- sbt 1.13.0, which doesn't have the method, with plain `sbt`: `run` fails with `NoSuchMethodError` and stops the development server, and the prompt comes back. +- The plugin compiles for sbt 1 (Scala 2.12) and sbt 2 (Scala 3.9), and `scalafmtCheckAll` and `headerCheckAll` pass for it. + +Before the rebase, the same checks and `validateCode` passed with the reflection lookup and locally built sbt. + +Not tested: Windows, IntelliJ itself, and `start` and `testProd` separately (they share `runProd`'s code). + +Found while testing, in sbt: + +- sbt/sbt#9946: after the application has served a request, Ctrl+C in a thin client exits the client and leaves `run` running, because Play's reload compile is a nested task evaluation. Fixed for sbt 2 by sbt/sbt#9979, which is in 2.1.0-RC2. +- sbt/sbt#9947: on sbt 1, `cancel` can't stop a `run` whose client disconnected, and new clients get no prompt afterwards. Fixed in sbt 1.13.1 by sbt/sbt#9958; with 1.13.1, a new client got a prompt and cancelled the orphaned `run`. + +## References + +- sbt/sbt#6782 +- sbt/sbt#9948, sbt/sbt#9949 +- #11086, #11088 (why end of file doesn't stop the server) + +AI assistance: Claude Code (Claude Opus 5.5) implemented and tested the change. OpenAI Codex (GPT-6) reviewed it and reran the checks. After the rebase, Claude Code replaced the reflection lookup with a direct call and reran the checks with the released sbt versions. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5390961b8eae`. 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/playframework__playframework-14388/tests/oracle.patch b/tasks/playframework__playframework-14388/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..006ab6628f975a8312bbbaa306b3b2d6ef1426e4 --- /dev/null +++ b/tasks/playframework__playframework-14388/tests/oracle.patch @@ -0,0 +1,101 @@ +diff --git a/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala b/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala +index 0a3fa6740f..68054d79c9 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/play/sbt/PlayInteractionMode.scala +@@ -97,7 +97,9 @@ object PlayConsoleInteractionMode extends PlayInteractionMode { + case 4 | 13 => // STOP on Ctrl-D or Enter + case 11 => consoleReader.clearScreen(); waitEOF() + case 10 => println(); waitEOF() +- case _ => waitEOF() ++ // EOF, e.g. with redirected input: wait instead of spinning ++ case -1 => Thread.sleep(50); waitEOF() ++ case _ => waitEOF() + } + } + doWithoutEcho(waitEOF()) +@@ -115,6 +117,34 @@ object PlayConsoleInteractionMode extends PlayInteractionMode { + + override def waitForCancel(): Unit = waitForKey() + ++ /** ++ * Like waitForCancel(), but reads the keys from the given sbt terminal, which belongs to the ++ * sbt console or thin client that runs the task. The terminal is put into raw mode, so that ++ * Enter (13) and Ctrl-D (4) stop and Ctrl-J (10) prints a new line, whichever terminal started ++ * the sbt server. ++ */ ++ def waitForCancel(terminal: sbt.Terminal): Unit = terminal.withRawInput(waitForKey(terminal)) ++ ++ private def waitForKey(terminal: sbt.Terminal): Unit = { ++ val out = terminal.printStream ++ @tailrec def waitEOF(): Unit = { ++ terminal.inputStream.read() match { ++ case 4 | 13 => // STOP on Ctrl-D or Enter ++ case 11 => ++ // Clear the screen, then move the cursor to the top left with relative moves, because sbt ++ // removes those for clients without ANSI support, but not absolute cursor positions ++ out.print("\u001b[2J\u001b[999A\u001b[999D") ++ out.flush() ++ waitEOF() ++ case 10 => out.println(); waitEOF() ++ // EOF, e.g. with redirected input: wait instead of spinning ++ case -1 => Thread.sleep(50); waitEOF() ++ case _ => waitEOF() ++ } ++ } ++ waitEOF() ++ } ++ + override def toString = "Console Interaction Mode" + } + +diff --git a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +index 108e783c0b..43f9bb93c3 100644 +--- a/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala ++++ b/dev-mode/sbt-plugin/src/main/scala/sbt/PlayRun.scala +@@ -31,6 +31,7 @@ import play.runsupport.DevServerSettings + import play.runsupport.GeneratedSourceMapping + import play.sbt.run.PlayReload + import play.sbt.Colors ++import play.sbt.PlayConsoleInteractionMode + import play.sbt.PlayImport.* + import play.sbt.PlayImport.PlayKeys.* + import play.sbt.PlayInteractionMode +@@ -83,6 +84,12 @@ object PlayRun { + .channelForName(channel) + .exists(channel => ContinuousCommands.isInWatch(state, channel)) + ++ private def waitForCancel(interaction: PlayInteractionMode, terminal: Option[Terminal]): Unit = ++ (interaction, terminal) match { ++ case (PlayConsoleInteractionMode, Some(term)) => PlayConsoleInteractionMode.waitForCancel(term) ++ case _ => interaction.waitForCancel() ++ } ++ + private class ContinuousInteractionMode(project: ProjectRef, state: State, log: Logger) extends PlayInteractionMode { + override def waitForCancel(): Unit = () + override def doWithoutEcho(f: => Unit): Unit = f +@@ -144,6 +151,7 @@ object PlayRun { + val runKey = resolvedScoped.value + val scope = runKey.scope + val log = streams.value.log ++ val term = terminal.value + val watching = isWatching(state, channelName(state)) + val interaction = interactionMode.getOrElse { + // Play installs its watch termination hook only for Compile / run (playWatchSettings). Other keys built with +@@ -234,7 +242,7 @@ object PlayRun { + + try { + // run mode +- interaction.waitForCancel() ++ waitForCancel(interaction, Some(term)) + } finally { + devModeServer.close() + println() +@@ -350,7 +358,7 @@ object PlayRun { + | """.stripMargin + println(Colors.green(msg)) + +- interaction.waitForCancel() ++ waitForCancel(interaction, PluginCompat.runTask(terminal, state).flatMap(_._2.toEither.toOption)) + println() + + if (noExitSbt) state diff --git a/tasks/playframework__playframework-14388/tests/test.sh b/tasks/playframework__playframework-14388/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f76a0fcfa9c0a248441712465356a3422a7f6e87 --- /dev/null +++ b/tasks/playframework__playframework-14388/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 5390961b8eaef2f370fdc6a0c9d8a23dd53a05fa > "$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/playframework__playframework-14388/tests/verifier.py b/tasks/playframework__playframework-14388/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14388/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/playframework__playframework-14400/environment/Dockerfile b/tasks/playframework__playframework-14400/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d26243421d37332b9f1e71649f3993377c09e88 --- /dev/null +++ b/tasks/playframework__playframework-14400/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1c384f1be240c3a8834ccdb74cd7507d9fe5527b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && 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/playframework__playframework-14400/instruction.md b/tasks/playframework__playframework-14400/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbfb660adb9c3241d914e8e7adbda9b4cc3e1008 --- /dev/null +++ b/tasks/playframework__playframework-14400/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.14.Final (was 7.4.13.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.13.Final` to `7.4.14.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/add642588a5d962c84e45446eb3c01263b250584/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14400/solution/patch.diff b/tasks/playframework__playframework-14400/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ecfe56e2cfd780bf6c08e23ce5ed0e56861e3cfe --- /dev/null +++ b/tasks/playframework__playframework-14400/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index d0f75eacab..dd64979f0a 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 4629ebf774..fc445a9e7f 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3b1a0a1737..f14c9d0761 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.13.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.14.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14400/solution/solve.sh b/tasks/playframework__playframework-14400/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14400/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/playframework__playframework-14400/task.toml b/tasks/playframework__playframework-14400/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4df57ebf4ba8d77132a597acaa3733b28d85e0c2 --- /dev/null +++ b/tasks/playframework__playframework-14400/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14400" +description = "hibernate-core, ... 7.4.14.Final (was 7.4.13.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "1c384f1be240c3a8834ccdb74cd7507d9fe5527b" +reference = "https://github.com/playframework/playframework/pull/14400" +source_access = "auto" +built_at = "2026-11-16T16:09:46.484165+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4f078b07b340582c61ab27231459e224425a3a275214f996674d159bbba82a3c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T16:30:03Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.552258+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c5ca22c0c383395a930a49ed7a9e4bba8acd861ead6fae617711e3c3548c9e4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14400/tests/capture.py b/tasks/playframework__playframework-14400/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14400/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/playframework__playframework-14400/tests/instruction.md b/tasks/playframework__playframework-14400/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbfb660adb9c3241d914e8e7adbda9b4cc3e1008 --- /dev/null +++ b/tasks/playframework__playframework-14400/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.14.Final (was 7.4.13.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.13.Final` to `7.4.14.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/add642588a5d962c84e45446eb3c01263b250584/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14400/tests/oracle.patch b/tasks/playframework__playframework-14400/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ecfe56e2cfd780bf6c08e23ce5ed0e56861e3cfe --- /dev/null +++ b/tasks/playframework__playframework-14400/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index d0f75eacab..dd64979f0a 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index 4629ebf774..fc445a9e7f 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3b1a0a1737..f14c9d0761 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.13.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.13.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.14.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14400/tests/test.sh b/tasks/playframework__playframework-14400/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a438a16085640c69e9c4069528a36b1d3c82b --- /dev/null +++ b/tasks/playframework__playframework-14400/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 1c384f1be240c3a8834ccdb74cd7507d9fe5527b > "$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/playframework__playframework-14400/tests/verifier.py b/tasks/playframework__playframework-14400/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14400/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/playframework__playframework-14401/environment/Dockerfile b/tasks/playframework__playframework-14401/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d26243421d37332b9f1e71649f3993377c09e88 --- /dev/null +++ b/tasks/playframework__playframework-14401/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1c384f1be240c3a8834ccdb74cd7507d9fe5527b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && 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/playframework__playframework-14401/instruction.md b/tasks/playframework__playframework-14401/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f86284c7bcded77b61c71207d8b01eb531d8e3d2 --- /dev/null +++ b/tasks/playframework__playframework-14401/instruction.md @@ -0,0 +1,128 @@ +# Issue + +**Title:** Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from `1.6.5` to `1.6.6` +* 📦 [com.codeborne:selenide-core](https://github.com/selenide/selenide) from `7.19.0` to `7.19.1` + + 📜 [GitHub Release Notes](https://github.com/selenide/selenide/releases/tag/v7.19.1) - [Version Diff](https://github.com/selenide/selenide/compare/v7.19.0...v7.19.1) + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/add642588a5d962c84e45446eb3c01263b250584/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "ch.qos.logback", artifactId = "logback-classic" }, + { groupId = "com.codeborne", artifactId = "selenide-core" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "ch.qos.logback", artifactId = "logback-classic" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.codeborne", artifactId = "selenide-core" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:2 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14401/solution/patch.diff b/tasks/playframework__playframework-14401/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..db92337d12f92bd0786a2486693ca374dd33c10e --- /dev/null +++ b/tasks/playframework__playframework-14401/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3b1a0a1737..bd3950d77c 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -13,7 +13,7 @@ object Dependencies { + + val playJsonVersion = "3.1.0-M10+90-e2ddbd4c-SNAPSHOT" + +- val logback = "ch.qos.logback" % "logback-classic" % "1.6.5" ++ val logback = "ch.qos.logback" % "logback-classic" % "1.6.6" + + val specs2Version = "4.23.0" + val specs2Deps = Seq( +@@ -244,7 +244,7 @@ object Dependencies { + "org.apache.pekko" %% "pekko-cluster-sharding-typed" % pekkoVersion + ) + +- val selenideVersion = "7.19.0" ++ val selenideVersion = "7.19.1" + // HtmlUnitDriver is not part of Selenium/Selenide, but it is still the default browser of Play's TestBrowser. + val htmlunitDriverVersion = "4.51.0" + diff --git a/tasks/playframework__playframework-14401/solution/solve.sh b/tasks/playframework__playframework-14401/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14401/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/playframework__playframework-14401/task.toml b/tasks/playframework__playframework-14401/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ab2aaeb5da98249ec53cd89a4d4475aaaab1869e --- /dev/null +++ b/tasks/playframework__playframework-14401/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14401" +description = "Patch updates" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "1c384f1be240c3a8834ccdb74cd7507d9fe5527b" +reference = "https://github.com/playframework/playframework/pull/14401" +source_access = "auto" +built_at = "2026-11-16T16:09:46.482344+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a04450a89947e7b46dbce3ca42ca299e970e1dd887d8e9fefb769a115ffb8265" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T16:30:34Z" +diff_format = "unified" +context_files = [ + "project/Dependencies.scala", +] +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:02.552825+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c5ca22c0c383395a930a49ed7a9e4bba8acd861ead6fae617711e3c3548c9e4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14401/tests/capture.py b/tasks/playframework__playframework-14401/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14401/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/playframework__playframework-14401/tests/instruction.md b/tasks/playframework__playframework-14401/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f86284c7bcded77b61c71207d8b01eb531d8e3d2 --- /dev/null +++ b/tasks/playframework__playframework-14401/tests/instruction.md @@ -0,0 +1,128 @@ +# Issue + +**Title:** Patch updates + +## Description + +## About this PR +Updates: + +* 📦 [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from `1.6.5` to `1.6.6` +* 📦 [com.codeborne:selenide-core](https://github.com/selenide/selenide) from `7.19.0` to `7.19.1` + + 📜 [GitHub Release Notes](https://github.com/selenide/selenide/releases/tag/v7.19.1) - [Version Diff](https://github.com/selenide/selenide/compare/v7.19.0...v7.19.1) + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/add642588a5d962c84e45446eb3c01263b250584/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add these to your `.scala-steward.conf` file to ignore future updates of these dependencies: +``` +updates.ignore = [ + { groupId = "ch.qos.logback", artifactId = "logback-classic" }, + { groupId = "com.codeborne", artifactId = "selenide-core" } +] +``` +Or, add these to slow down future updates of these dependencies: +``` +dependencyOverrides = [ + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "ch.qos.logback", artifactId = "logback-classic" } + }, + { + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "com.codeborne", artifactId = "selenide-core" } + } +] +``` +
+ + +labels: library-update, early-semver-patch, semver-spec-patch, commit-count:n:2 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14401/tests/oracle.patch b/tasks/playframework__playframework-14401/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..db92337d12f92bd0786a2486693ca374dd33c10e --- /dev/null +++ b/tasks/playframework__playframework-14401/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3b1a0a1737..bd3950d77c 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -13,7 +13,7 @@ object Dependencies { + + val playJsonVersion = "3.1.0-M10+90-e2ddbd4c-SNAPSHOT" + +- val logback = "ch.qos.logback" % "logback-classic" % "1.6.5" ++ val logback = "ch.qos.logback" % "logback-classic" % "1.6.6" + + val specs2Version = "4.23.0" + val specs2Deps = Seq( +@@ -244,7 +244,7 @@ object Dependencies { + "org.apache.pekko" %% "pekko-cluster-sharding-typed" % pekkoVersion + ) + +- val selenideVersion = "7.19.0" ++ val selenideVersion = "7.19.1" + // HtmlUnitDriver is not part of Selenium/Selenide, but it is still the default browser of Play's TestBrowser. + val htmlunitDriverVersion = "4.51.0" + diff --git a/tasks/playframework__playframework-14401/tests/test.sh b/tasks/playframework__playframework-14401/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a438a16085640c69e9c4069528a36b1d3c82b --- /dev/null +++ b/tasks/playframework__playframework-14401/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 1c384f1be240c3a8834ccdb74cd7507d9fe5527b > "$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/playframework__playframework-14401/tests/verifier.py b/tasks/playframework__playframework-14401/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14401/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/playframework__playframework-14404/environment/Dockerfile b/tasks/playframework__playframework-14404/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d26243421d37332b9f1e71649f3993377c09e88 --- /dev/null +++ b/tasks/playframework__playframework-14404/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1c384f1be240c3a8834ccdb74cd7507d9fe5527b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && 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/playframework__playframework-14404/instruction.md b/tasks/playframework__playframework-14404/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a38d98555d5575db2f0a9d3d38b8bcc06255444 --- /dev/null +++ b/tasks/playframework__playframework-14404/instruction.md @@ -0,0 +1,94 @@ +# Issue + +**Title:** [Gradle] Bump gradle-wrapper from 9.8.1 to 9.8.2 in /dev-mode/gradle-plugin + +## Description + +Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.8.1 to 9.8.2. +
+Release notes +

Sourced from gradle-wrapper's releases.

+
+

9.8.2

+

The Gradle team is excited to announce Gradle 9.8.2.

+

Here are the highlights of this release:

+
    +
  • Java 27 support
  • +
  • Maven mirror settings reuse
  • +
  • Linked problem locations in build output
  • +
+

Read the Release Notes

+

We would like to thank the following community members for their contributions to this release of Gradle: +Aman Gautam, +Björn Kautler, +Eng Zer Jun, +Hashim Khan, +Julian Krannich, +KBS, +Labh R Jethe, +Mark Dodgson, +Maxim, +monkey, +nataphon-ktsystems, +Paul King, +Qiu Tian, +rg_sandesh, +Roberto Perez Alcolea, +Sean, +Zongle Wang.

+

Upgrade instructions

+

Switch your build to use Gradle 9.8.2 by updating your wrapper:

+
./gradlew :wrapper --gradle-version=9.8.2 && ./gradlew :wrapper
+
+

See the Gradle 9.x upgrade guide to learn about deprecations, breaking changes and other considerations when upgrading.

+

For Java, Groovy, Kotlin and Android compatibility, see the full compatibility notes.

+

Reporting problems

+

If you find a problem with this release, please file a bug on GitHub Issues adhering to our issue guidelines. +If you're not sure you're encountering a bug, please use the forum.

+

We hope you will build happiness with Gradle, and we look forward to your feedback via Twitter or on GitHub.

+
+
+
+Commits +
    +
  • 8de7bcf Speed up the AllVersionsCrossVersion flaky quarantine (#39494)
  • +
  • 66805db Run all cross-version targets in flaky quarantine
  • +
  • cdd4c8f Skip empty test tasks in the flaky test quarantine
  • +
  • 6badb77 Split the AllVersionsCrossVersion quarantine across agents
  • +
  • 1655e44 Prepare for 9.8.2 (#39492)
  • +
  • 6702214 Prepare for 9.8.2
  • +
  • 688c0c1 Fix false warning about unstable graph (#39479)
  • +
  • 3601d4f Clarify selector reuse comments in SelectorState
  • +
  • 6e836fd Fix false warning about unstable graph
  • +
  • a0790e5 Fix hidden artifact cleanup pattern in CheckProject (#39451)
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=gradle-wrapper&package-manager=gradle&previous-version=9.8.1&new-version=9.8.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
+Dependabot commands and options +
+ +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14404/solution/patch.diff b/tasks/playframework__playframework-14404/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c2f110c0f8fc7bb7061347e29119235e3cb1a232 --- /dev/null +++ b/tasks/playframework__playframework-14404/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +index 426ec4bd78..bb13f07ba6 100644 +--- a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties ++++ b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +@@ -1,7 +1,7 @@ + distributionBase=GRADLE_USER_HOME + distributionPath=wrapper/dists +-distributionSha256Sum=5ceda8d2425eb2af196dec31b6fc1f38af2fb638fd621f86fa685805f2262224 +-distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-all.zip ++distributionSha256Sum=a1bb7e9651ef09e4cd9a62d471564e0ee23b5757e5f21fd7358d7cfc21018fdf ++distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip + networkTimeout=10000 + validateDistributionUrl=true + zipStoreBase=GRADLE_USER_HOME diff --git a/tasks/playframework__playframework-14404/solution/solve.sh b/tasks/playframework__playframework-14404/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14404/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/playframework__playframework-14404/task.toml b/tasks/playframework__playframework-14404/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5f516ae85a45ef5e148f1b6f0c2054e821f8f99 --- /dev/null +++ b/tasks/playframework__playframework-14404/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14404" +description = "[Gradle] Bump gradle-wrapper from 9.8.1 to 9.8.2 in /dev-mode/gradle-plugin" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "1c384f1be240c3a8834ccdb74cd7507d9fe5527b" +reference = "https://github.com/playframework/playframework/pull/14404" +source_access = "auto" +built_at = "2026-11-16T16:09:46.486214+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:80dae1d0be38401a224b11df710212c8bbd8133e07280e0bb44b0010b0bf29c8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T16:29:06Z" +diff_format = "unified" +context_files = [ + "dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties", +] +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:02.553359+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c5ca22c0c383395a930a49ed7a9e4bba8acd861ead6fae617711e3c3548c9e4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14404/tests/capture.py b/tasks/playframework__playframework-14404/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14404/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/playframework__playframework-14404/tests/instruction.md b/tasks/playframework__playframework-14404/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a38d98555d5575db2f0a9d3d38b8bcc06255444 --- /dev/null +++ b/tasks/playframework__playframework-14404/tests/instruction.md @@ -0,0 +1,94 @@ +# Issue + +**Title:** [Gradle] Bump gradle-wrapper from 9.8.1 to 9.8.2 in /dev-mode/gradle-plugin + +## Description + +Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.8.1 to 9.8.2. +
+Release notes +

Sourced from gradle-wrapper's releases.

+
+

9.8.2

+

The Gradle team is excited to announce Gradle 9.8.2.

+

Here are the highlights of this release:

+
    +
  • Java 27 support
  • +
  • Maven mirror settings reuse
  • +
  • Linked problem locations in build output
  • +
+

Read the Release Notes

+

We would like to thank the following community members for their contributions to this release of Gradle: +Aman Gautam, +Björn Kautler, +Eng Zer Jun, +Hashim Khan, +Julian Krannich, +KBS, +Labh R Jethe, +Mark Dodgson, +Maxim, +monkey, +nataphon-ktsystems, +Paul King, +Qiu Tian, +rg_sandesh, +Roberto Perez Alcolea, +Sean, +Zongle Wang.

+

Upgrade instructions

+

Switch your build to use Gradle 9.8.2 by updating your wrapper:

+
./gradlew :wrapper --gradle-version=9.8.2 && ./gradlew :wrapper
+
+

See the Gradle 9.x upgrade guide to learn about deprecations, breaking changes and other considerations when upgrading.

+

For Java, Groovy, Kotlin and Android compatibility, see the full compatibility notes.

+

Reporting problems

+

If you find a problem with this release, please file a bug on GitHub Issues adhering to our issue guidelines. +If you're not sure you're encountering a bug, please use the forum.

+

We hope you will build happiness with Gradle, and we look forward to your feedback via Twitter or on GitHub.

+
+
+
+Commits +
    +
  • 8de7bcf Speed up the AllVersionsCrossVersion flaky quarantine (#39494)
  • +
  • 66805db Run all cross-version targets in flaky quarantine
  • +
  • cdd4c8f Skip empty test tasks in the flaky test quarantine
  • +
  • 6badb77 Split the AllVersionsCrossVersion quarantine across agents
  • +
  • 1655e44 Prepare for 9.8.2 (#39492)
  • +
  • 6702214 Prepare for 9.8.2
  • +
  • 688c0c1 Fix false warning about unstable graph (#39479)
  • +
  • 3601d4f Clarify selector reuse comments in SelectorState
  • +
  • 6e836fd Fix false warning about unstable graph
  • +
  • a0790e5 Fix hidden artifact cleanup pattern in CheckProject (#39451)
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=gradle-wrapper&package-manager=gradle&previous-version=9.8.1&new-version=9.8.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
+Dependabot commands and options +
+ +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1c384f1be240`. 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/playframework__playframework-14404/tests/oracle.patch b/tasks/playframework__playframework-14404/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c2f110c0f8fc7bb7061347e29119235e3cb1a232 --- /dev/null +++ b/tasks/playframework__playframework-14404/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +index 426ec4bd78..bb13f07ba6 100644 +--- a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties ++++ b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +@@ -1,7 +1,7 @@ + distributionBase=GRADLE_USER_HOME + distributionPath=wrapper/dists +-distributionSha256Sum=5ceda8d2425eb2af196dec31b6fc1f38af2fb638fd621f86fa685805f2262224 +-distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-all.zip ++distributionSha256Sum=a1bb7e9651ef09e4cd9a62d471564e0ee23b5757e5f21fd7358d7cfc21018fdf ++distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip + networkTimeout=10000 + validateDistributionUrl=true + zipStoreBase=GRADLE_USER_HOME diff --git a/tasks/playframework__playframework-14404/tests/test.sh b/tasks/playframework__playframework-14404/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a438a16085640c69e9c4069528a36b1d3c82b --- /dev/null +++ b/tasks/playframework__playframework-14404/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 1c384f1be240c3a8834ccdb74cd7507d9fe5527b > "$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/playframework__playframework-14404/tests/verifier.py b/tasks/playframework__playframework-14404/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14404/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/playframework__playframework-14405/environment/Dockerfile b/tasks/playframework__playframework-14405/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d26243421d37332b9f1e71649f3993377c09e88 --- /dev/null +++ b/tasks/playframework__playframework-14405/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1c384f1be240c3a8834ccdb74cd7507d9fe5527b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1c384f1be240c3a8834ccdb74cd7507d9fe5527b \ + && 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/playframework__playframework-14405/instruction.md b/tasks/playframework__playframework-14405/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7940276a811cf7e6dbd89ff55d3ddcfcd892e8a0 --- /dev/null +++ b/tasks/playframework__playframework-14405/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** sbt 1.13.1 + 2.1.0-RC2 with lots of fixes needed for Play + +## 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 `1c384f1be240`. 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/playframework__playframework-14405/solution/patch.diff b/tasks/playframework__playframework-14405/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..59326a890d4f48331fc267dcaf8ae2d8a42ea4ee --- /dev/null +++ b/tasks/playframework__playframework-14405/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 5385fdd3b3..201cf10be8 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -47,7 +47,7 @@ jobs: + sbt +update # Fetches dependencies for published 2.13/3.3 artifacts + sbt "-Dscala.version=3.9.x" update # Fetches dependencies for the Scala 3 LTS test lane + sbt "-Dscala.version=3.next" update # Fetches dependencies for the Scala 3 next test lane +- # sbt --sbt-version 1.13.0 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here ++ # sbt --sbt-version 1.13.1 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here + sbt +mimaPreviousClassfiles # Fetches previous artifacts + cd documentation + sbt +update # Fetches documentation dependencies for published artifacts +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.13.0", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], ++ "sbt": [ "1.13.1", "2.1.0-RC2" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index 4afdcf1b29..db0b5eac92 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-bin-20261019-4937ade-NIGHTLY ++sbt.version=2.1.0-RC2 +diff --git a/project/Versions.scala b/project/Versions.scala +index 157badbe9f..51c4ab8e6a 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -24,6 +24,6 @@ object ScalaVersions { + } + + object SbtVersions { +- val sbt1 = "1.13.0" +- val sbt2 = "2.1.0-bin-20261019-4937ade-NIGHTLY" ++ val sbt1 = "1.13.1" ++ val sbt2 = "2.1.0-RC2" + } +diff --git a/project/build.properties b/project/build.properties +index 66aa96210f..12c305d3bb 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-bin-20261019-4937ade-NIGHTLY ++sbt.version=2.1.0-RC2 diff --git a/tasks/playframework__playframework-14405/solution/solve.sh b/tasks/playframework__playframework-14405/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14405/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/playframework__playframework-14405/task.toml b/tasks/playframework__playframework-14405/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b53d2fa0c9ba58b6a9a29c1f6cfea765c942f51f --- /dev/null +++ b/tasks/playframework__playframework-14405/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14405" +description = "sbt 1.13.1 + 2.1.0-RC2 with lots of fixes needed for Play" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "1c384f1be240c3a8834ccdb74cd7507d9fe5527b" +reference = "https://github.com/playframework/playframework/pull/14405" +source_access = "auto" +built_at = "2026-11-16T16:09:46.488010+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d5dad1c218ce70a84372937c207e6ebd4528f445756ecb9eba1fd1795de7a42d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-28T16:28:04Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-test.yml", + "documentation/project/build.properties", + "project/Versions.scala", + "project/build.properties", +] +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:02.553904+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c5ca22c0c383395a930a49ed7a9e4bba8acd861ead6fae617711e3c3548c9e4d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14405/tests/capture.py b/tasks/playframework__playframework-14405/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14405/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/playframework__playframework-14405/tests/instruction.md b/tasks/playframework__playframework-14405/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7940276a811cf7e6dbd89ff55d3ddcfcd892e8a0 --- /dev/null +++ b/tasks/playframework__playframework-14405/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** sbt 1.13.1 + 2.1.0-RC2 with lots of fixes needed for Play + +## 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 `1c384f1be240`. 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/playframework__playframework-14405/tests/oracle.patch b/tasks/playframework__playframework-14405/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..59326a890d4f48331fc267dcaf8ae2d8a42ea4ee --- /dev/null +++ b/tasks/playframework__playframework-14405/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index 5385fdd3b3..201cf10be8 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -47,7 +47,7 @@ jobs: + sbt +update # Fetches dependencies for published 2.13/3.3 artifacts + sbt "-Dscala.version=3.9.x" update # Fetches dependencies for the Scala 3 LTS test lane + sbt "-Dscala.version=3.next" update # Fetches dependencies for the Scala 3 next test lane +- # sbt --sbt-version 1.13.0 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here ++ # sbt --sbt-version 1.13.1 +update # If we run scripted tests with multiple sbt versions, we could init that sbt installs here + sbt +mimaPreviousClassfiles # Fetches previous artifacts + cd documentation + sbt +update # Fetches documentation dependencies for published artifacts +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.13.0", "2.1.0-bin-20261019-4937ade-NIGHTLY" ], ++ "sbt": [ "1.13.1", "2.1.0-RC2" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index 4afdcf1b29..db0b5eac92 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-bin-20261019-4937ade-NIGHTLY ++sbt.version=2.1.0-RC2 +diff --git a/project/Versions.scala b/project/Versions.scala +index 157badbe9f..51c4ab8e6a 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -24,6 +24,6 @@ object ScalaVersions { + } + + object SbtVersions { +- val sbt1 = "1.13.0" +- val sbt2 = "2.1.0-bin-20261019-4937ade-NIGHTLY" ++ val sbt1 = "1.13.1" ++ val sbt2 = "2.1.0-RC2" + } +diff --git a/project/build.properties b/project/build.properties +index 66aa96210f..12c305d3bb 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-bin-20261019-4937ade-NIGHTLY ++sbt.version=2.1.0-RC2 diff --git a/tasks/playframework__playframework-14405/tests/test.sh b/tasks/playframework__playframework-14405/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a438a16085640c69e9c4069528a36b1d3c82b --- /dev/null +++ b/tasks/playframework__playframework-14405/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 1c384f1be240c3a8834ccdb74cd7507d9fe5527b > "$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/playframework__playframework-14405/tests/verifier.py b/tasks/playframework__playframework-14405/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14405/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/playframework__playframework-14417/environment/Dockerfile b/tasks/playframework__playframework-14417/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c14add0b66a7f54934dbe224b478cf5e55eba1cc --- /dev/null +++ b/tasks/playframework__playframework-14417/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fe2b0b287eb14a6794fed0646c002c6d65faacf6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fe2b0b287eb14a6794fed0646c002c6d65faacf6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fe2b0b287eb14a6794fed0646c002c6d65faacf6 \ + && 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/playframework__playframework-14417/instruction.md b/tasks/playframework__playframework-14417/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7021a832f1cc0484e7f5ee41c5aac55f8b6a5ef --- /dev/null +++ b/tasks/playframework__playframework-14417/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Use Play's Twirl version in the Gradle plugin build + +## Description + +## Purpose + +The Gradle plugin integrates with the Twirl Gradle plugin, but its build compiled against `gradle-twirl` 2.0.3 from `gradle/libs.versions.toml`. That version never changed since the plugin was added, while Play itself uses Twirl 2.1. + +With this change, the Gradle plugin build uses the Twirl version that Play uses: + +- `sbt savePlayVersion` now also writes `twirl.version` to `version.properties`, taken from the sbt-twirl version of Play's build. +- The Gradle plugin build reads `twirl.version` from there, or from the `twirl.version` system property, the same way as `play.version`. +- `twirl` is removed from the version catalog, so there is only one place for the Twirl version: `project/plugins.sbt`. + +## Background Context + +The plugin should be built against the Twirl Gradle plugin of the same Twirl version that the Play release uses, because users combine the Play Gradle plugin with the Twirl Gradle plugin that matches their Play release. + +All CI jobs that run Gradle already run `sbt savePlayVersion` first. A `version.properties` written before this change has no `twirl.version`, so local Gradle builds fail with a message to run `sbt savePlayVersion` again. + +`gradle-twirl` is a `compileOnly` dependency, so it doesn't appear in the published POM. + +## Testing + +`./gradlew check` in `dev-mode/gradle-plugin` passes with `-Pscala.version=2.13`, and `./gradlew test` passes with `-Pscala.version=3.3.9`, with the plugin compiled against `gradle-twirl:2.1.0-M9+129-bab5ac69-SNAPSHOT`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe2b0b287eb1`. 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/playframework__playframework-14417/solution/patch.diff b/tasks/playframework__playframework-14417/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c1813dac849734cbfcb64bede43d30361dda2ed2 --- /dev/null +++ b/tasks/playframework__playframework-14417/solution/patch.diff @@ -0,0 +1,71 @@ +diff --git a/build.sbt b/build.sbt +index 2d7b8460aa..8c53fb9430 100644 +--- a/build.sbt ++++ b/build.sbt +@@ -542,6 +542,8 @@ savePlayVersion := Def.uncached { + val writer = new StringWriter() + val file = baseDirectory.value / "version.properties" + props.setProperty("play.version", version.value) ++ // The Gradle plugin integrates with the Twirl Gradle plugin of the Twirl version that Play uses ++ props.setProperty("twirl.version", playbuildinfo.BuildInfo.sbtTwirlVersion) + props.store(writer, "") + IO.write(file, writer.getBuffer.toString) + } +diff --git a/dev-mode/gradle-plugin/build.gradle.kts b/dev-mode/gradle-plugin/build.gradle.kts +index b8aa3e019e..a26004c37f 100644 +--- a/dev-mode/gradle-plugin/build.gradle.kts ++++ b/dev-mode/gradle-plugin/build.gradle.kts +@@ -14,15 +14,24 @@ plugins { + signing + } + +-val playVersionKey = "play.version" +-val playVersion: String = System.getProperty(playVersionKey) ?: Properties().apply { +- val file = file("$projectDir/../../version.properties") +- if (!file.exists()) throw GradleException("Generate Play version file by `sbt savePlayVersion` command") +- file.inputStream().use { load(it) } +- if (this.getProperty(playVersionKey).isNullOrEmpty()) { +- throw GradleException("`$playVersionKey` key didn't find in ${file.absolutePath}") ++val versionFile = file("$projectDir/../../version.properties") ++val savedVersions: Properties by lazy { ++ Properties().apply { ++ if (!versionFile.exists()) throw GradleException("Generate Play version file by `sbt savePlayVersion` command") ++ versionFile.inputStream().use { load(it) } + } +-}.getProperty(playVersionKey) ++} ++ ++/** A version from a system property, or else from the version file of `sbt savePlayVersion`. */ ++fun savedVersion(key: String): String = System.getProperty(key) ?: savedVersions.getProperty(key).also { ++ if (it.isNullOrEmpty()) { ++ throw GradleException("`$key` key didn't find in ${versionFile.absolutePath}, regenerate it by `sbt savePlayVersion`") ++ } ++} ++ ++val playVersion: String = savedVersion("play.version") ++// The Twirl version that Play uses, so that the plugin integrates with the matching Twirl Gradle plugin ++val twirlVersion: String = savedVersion("twirl.version") + + val isRelease = !playVersion.endsWith("SNAPSHOT") + +@@ -38,7 +47,7 @@ repositories { + + dependencies { + compileOnly("org.playframework:play-routes-compiler_2.13:$playVersion") +- compileOnly("org.playframework.twirl:gradle-twirl:${libs.versions.twirl.get()}") ++ compileOnly("org.playframework.twirl:gradle-twirl:$twirlVersion") + implementation("org.playframework:play-run-support:$playVersion") + testImplementation(libs.assertj) + testImplementation(libs.commons.io) +diff --git a/dev-mode/gradle-plugin/gradle/libs.versions.toml b/dev-mode/gradle-plugin/gradle/libs.versions.toml +index c54476b2c0..bb6549eb19 100644 +--- a/dev-mode/gradle-plugin/gradle/libs.versions.toml ++++ b/dev-mode/gradle-plugin/gradle/libs.versions.toml +@@ -5,7 +5,6 @@ spotless = "8.10.4" + assertj = "3.27.7" + commons-io = "2.22.0" + freemarker = "2.3.35" +-twirl = "2.0.3" + mockito = "5.24.0" + kotlin-plugin = "2.4.21" + diff --git a/tasks/playframework__playframework-14417/solution/solve.sh b/tasks/playframework__playframework-14417/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14417/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/playframework__playframework-14417/task.toml b/tasks/playframework__playframework-14417/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf3c46dd5f0b243081d4df5656018d75ed62d132 --- /dev/null +++ b/tasks/playframework__playframework-14417/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14417" +description = "Use Play's Twirl version in the Gradle plugin build" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "fe2b0b287eb14a6794fed0646c002c6d65faacf6" +reference = "https://github.com/playframework/playframework/pull/14417" +source_access = "auto" +built_at = "2026-11-16T16:09:46.472969+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:685254b09f610d21b93ee37ebb5a63a8bba17a11735327ffaa7d6edfebf48a35" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-04T20:32:45Z" +diff_format = "unified" +context_files = [ + "build.sbt", + "dev-mode/gradle-plugin/build.gradle.kts", + "dev-mode/gradle-plugin/gradle/libs.versions.toml", +] +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:02.554432+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e47823a95c54bac1b79660d2dd15159659215978df607d26a4808dc465f82dbd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14417/tests/capture.py b/tasks/playframework__playframework-14417/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14417/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/playframework__playframework-14417/tests/instruction.md b/tasks/playframework__playframework-14417/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7021a832f1cc0484e7f5ee41c5aac55f8b6a5ef --- /dev/null +++ b/tasks/playframework__playframework-14417/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Use Play's Twirl version in the Gradle plugin build + +## Description + +## Purpose + +The Gradle plugin integrates with the Twirl Gradle plugin, but its build compiled against `gradle-twirl` 2.0.3 from `gradle/libs.versions.toml`. That version never changed since the plugin was added, while Play itself uses Twirl 2.1. + +With this change, the Gradle plugin build uses the Twirl version that Play uses: + +- `sbt savePlayVersion` now also writes `twirl.version` to `version.properties`, taken from the sbt-twirl version of Play's build. +- The Gradle plugin build reads `twirl.version` from there, or from the `twirl.version` system property, the same way as `play.version`. +- `twirl` is removed from the version catalog, so there is only one place for the Twirl version: `project/plugins.sbt`. + +## Background Context + +The plugin should be built against the Twirl Gradle plugin of the same Twirl version that the Play release uses, because users combine the Play Gradle plugin with the Twirl Gradle plugin that matches their Play release. + +All CI jobs that run Gradle already run `sbt savePlayVersion` first. A `version.properties` written before this change has no `twirl.version`, so local Gradle builds fail with a message to run `sbt savePlayVersion` again. + +`gradle-twirl` is a `compileOnly` dependency, so it doesn't appear in the published POM. + +## Testing + +`./gradlew check` in `dev-mode/gradle-plugin` passes with `-Pscala.version=2.13`, and `./gradlew test` passes with `-Pscala.version=3.3.9`, with the plugin compiled against `gradle-twirl:2.1.0-M9+129-bab5ac69-SNAPSHOT`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fe2b0b287eb1`. 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/playframework__playframework-14417/tests/oracle.patch b/tasks/playframework__playframework-14417/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c1813dac849734cbfcb64bede43d30361dda2ed2 --- /dev/null +++ b/tasks/playframework__playframework-14417/tests/oracle.patch @@ -0,0 +1,71 @@ +diff --git a/build.sbt b/build.sbt +index 2d7b8460aa..8c53fb9430 100644 +--- a/build.sbt ++++ b/build.sbt +@@ -542,6 +542,8 @@ savePlayVersion := Def.uncached { + val writer = new StringWriter() + val file = baseDirectory.value / "version.properties" + props.setProperty("play.version", version.value) ++ // The Gradle plugin integrates with the Twirl Gradle plugin of the Twirl version that Play uses ++ props.setProperty("twirl.version", playbuildinfo.BuildInfo.sbtTwirlVersion) + props.store(writer, "") + IO.write(file, writer.getBuffer.toString) + } +diff --git a/dev-mode/gradle-plugin/build.gradle.kts b/dev-mode/gradle-plugin/build.gradle.kts +index b8aa3e019e..a26004c37f 100644 +--- a/dev-mode/gradle-plugin/build.gradle.kts ++++ b/dev-mode/gradle-plugin/build.gradle.kts +@@ -14,15 +14,24 @@ plugins { + signing + } + +-val playVersionKey = "play.version" +-val playVersion: String = System.getProperty(playVersionKey) ?: Properties().apply { +- val file = file("$projectDir/../../version.properties") +- if (!file.exists()) throw GradleException("Generate Play version file by `sbt savePlayVersion` command") +- file.inputStream().use { load(it) } +- if (this.getProperty(playVersionKey).isNullOrEmpty()) { +- throw GradleException("`$playVersionKey` key didn't find in ${file.absolutePath}") ++val versionFile = file("$projectDir/../../version.properties") ++val savedVersions: Properties by lazy { ++ Properties().apply { ++ if (!versionFile.exists()) throw GradleException("Generate Play version file by `sbt savePlayVersion` command") ++ versionFile.inputStream().use { load(it) } + } +-}.getProperty(playVersionKey) ++} ++ ++/** A version from a system property, or else from the version file of `sbt savePlayVersion`. */ ++fun savedVersion(key: String): String = System.getProperty(key) ?: savedVersions.getProperty(key).also { ++ if (it.isNullOrEmpty()) { ++ throw GradleException("`$key` key didn't find in ${versionFile.absolutePath}, regenerate it by `sbt savePlayVersion`") ++ } ++} ++ ++val playVersion: String = savedVersion("play.version") ++// The Twirl version that Play uses, so that the plugin integrates with the matching Twirl Gradle plugin ++val twirlVersion: String = savedVersion("twirl.version") + + val isRelease = !playVersion.endsWith("SNAPSHOT") + +@@ -38,7 +47,7 @@ repositories { + + dependencies { + compileOnly("org.playframework:play-routes-compiler_2.13:$playVersion") +- compileOnly("org.playframework.twirl:gradle-twirl:${libs.versions.twirl.get()}") ++ compileOnly("org.playframework.twirl:gradle-twirl:$twirlVersion") + implementation("org.playframework:play-run-support:$playVersion") + testImplementation(libs.assertj) + testImplementation(libs.commons.io) +diff --git a/dev-mode/gradle-plugin/gradle/libs.versions.toml b/dev-mode/gradle-plugin/gradle/libs.versions.toml +index c54476b2c0..bb6549eb19 100644 +--- a/dev-mode/gradle-plugin/gradle/libs.versions.toml ++++ b/dev-mode/gradle-plugin/gradle/libs.versions.toml +@@ -5,7 +5,6 @@ spotless = "8.10.4" + assertj = "3.27.7" + commons-io = "2.22.0" + freemarker = "2.3.35" +-twirl = "2.0.3" + mockito = "5.24.0" + kotlin-plugin = "2.4.21" + diff --git a/tasks/playframework__playframework-14417/tests/test.sh b/tasks/playframework__playframework-14417/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77b12f03ec62e6c624c8ccf0725fcb2d6dc79bad --- /dev/null +++ b/tasks/playframework__playframework-14417/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 fe2b0b287eb14a6794fed0646c002c6d65faacf6 > "$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/playframework__playframework-14417/tests/verifier.py b/tasks/playframework__playframework-14417/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14417/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/playframework__playframework-14418/environment/Dockerfile b/tasks/playframework__playframework-14418/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c22175ceb11f0bf3a1830468d1ddc0f295537927 --- /dev/null +++ b/tasks/playframework__playframework-14418/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 53c13d176fab94958a02f3ac9b2985c0070c40b4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 53c13d176fab94958a02f3ac9b2985c0070c40b4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 53c13d176fab94958a02f3ac9b2985c0070c40b4 \ + && 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/playframework__playframework-14418/instruction.md b/tasks/playframework__playframework-14418/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5babfbf3d02090c1a8d430514f8765680ed5992 --- /dev/null +++ b/tasks/playframework__playframework-14418/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Update Pekko to 2.0.0 + +## Description + +# Purpose + +~Test Play with Pekko 2.0.0, which is currently staged and not yet on Maven Central.~ + +- Updates `pekkoVersion` to `2.0.0`; Pekko HTTP also to `2.0.0`. +- ~Adds the Apache staging repository to the build, the scripted tests and the Gradle scripted fixtures. This should be removed once Pekko 2.0.0 is on Maven Central.~ + +# References + +Follows on from #14211, which could not be reopened. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53c13d176fab`. 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/playframework__playframework-14418/solution/patch.diff b/tasks/playframework__playframework-14418/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1b3dc01ea34711d5283b87a9e61db33abff5fbea --- /dev/null +++ b/tasks/playframework__playframework-14418/solution/patch.diff @@ -0,0 +1,104 @@ +diff --git a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java +index 4998976ca0..011bca0c88 100644 +--- a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java ++++ b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java +@@ -30,8 +30,8 @@ public class Standalone { + AsyncHttpClientConfig asyncHttpClientConfig = + new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build(); + AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig); + +diff --git a/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala b/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala +index 6266ec9f6a..45059e06ac 100644 +--- a/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala ++++ b/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala +@@ -24,8 +24,8 @@ object Main { + + val asyncHttpClientConfig = new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build + val asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig) + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index f8d8510b99..50aeb6c73b 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -8,8 +8,8 @@ import playbuildinfo.BuildInfo + import Keys._ + + object Dependencies { +- val pekkoVersion: String = sys.props.getOrElse("pekko.version", "2.0.0-M4") +- val pekkoHttpVersion = sys.props.getOrElse("pekko.http.version", "2.0.0-M2+47-c525ae28-SNAPSHOT") ++ val pekkoVersion: String = sys.props.getOrElse("pekko.version", "2.0.0") ++ val pekkoHttpVersion = sys.props.getOrElse("pekko.http.version", "2.0.0") + + val playJsonVersion = "3.1.0-M10+90-e2ddbd4c-SNAPSHOT" + +@@ -273,7 +273,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi ++ Seq(assertj % Test) + +- val playWsStandaloneVersion = "3.1.0-M14+18-e10c553c-SNAPSHOT" ++ val playWsStandaloneVersion = "3.1.0-M14+81-d2d3ccd9-SNAPSHOT" + val playWsDeps = Seq( + "org.playframework" %% "play-ws-standalone" % playWsStandaloneVersion, + "org.playframework" %% "play-ws-standalone-xml" % playWsStandaloneVersion, +diff --git a/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java b/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java +index 9adca080a4..69f2b6f05f 100644 +--- a/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java ++++ b/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java +@@ -44,8 +44,8 @@ public class WSTestClient { + AsyncHttpClientConfig config = + new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build(); + + String name = "ws-test-client-" + instanceNumber.getAndIncrement(); +diff --git a/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala b/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala +index de6a2d20ed..1ebc7270a3 100644 +--- a/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala ++++ b/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala +@@ -271,7 +271,7 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .asInstanceOf[AhcWSRequest] + .underlying + .buildRequest() +- (req.getRequestTimeout must be).equalTo(1000) ++ (req.getRequestTimeout must be).equalTo(java.time.Duration.ofMillis(1000)) + } + + "support infinite timeout" in { +@@ -280,7 +280,7 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .asInstanceOf[AhcWSRequest] + .underlying + .buildRequest() +- (req.getRequestTimeout must be).equalTo(-1) ++ (req.getRequestTimeout must be).equalTo(java.time.Duration.ofMillis(-1)) + } + + "not support negative timeout" in { +@@ -631,9 +631,9 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .build() + ahcConfig.isCompressionEnforced must beFalse + ahcConfig.isFollowRedirect must beFalse +- ahcConfig.getConnectTimeout must_== 120000 +- ahcConfig.getRequestTimeout must_== 120000 +- ahcConfig.getReadTimeout must_== 120000 ++ ahcConfig.getConnectTimeout must_== java.time.Duration.ofMinutes(2) ++ ahcConfig.getRequestTimeout must_== java.time.Duration.ofMinutes(2) ++ ahcConfig.getReadTimeout must_== java.time.Duration.ofMinutes(2) + } + } + } diff --git a/tasks/playframework__playframework-14418/solution/solve.sh b/tasks/playframework__playframework-14418/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14418/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/playframework__playframework-14418/task.toml b/tasks/playframework__playframework-14418/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..134346aa94a8a6665fa828b1de17c87a063b6b4b --- /dev/null +++ b/tasks/playframework__playframework-14418/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14418" +description = "Update Pekko to 2.0.0" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "53c13d176fab94958a02f3ac9b2985c0070c40b4" +reference = "https://github.com/playframework/playframework/pull/14418" +source_access = "auto" +built_at = "2026-11-16T16:09:46.464418+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2a0889114348069e4bfc0f0ce8206c0963e6e23748a31c9b2722b30cc0e04ef2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-16T13:15:30Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java", + "documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala", + "project/Dependencies.scala", + "transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java", + "transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 28 +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:02.554980+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a270aca6ea4e6ef1c31187a7ed3f4030e338a48274322b199dc7e32f2d445f8a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14418/tests/capture.py b/tasks/playframework__playframework-14418/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14418/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/playframework__playframework-14418/tests/instruction.md b/tasks/playframework__playframework-14418/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5babfbf3d02090c1a8d430514f8765680ed5992 --- /dev/null +++ b/tasks/playframework__playframework-14418/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Update Pekko to 2.0.0 + +## Description + +# Purpose + +~Test Play with Pekko 2.0.0, which is currently staged and not yet on Maven Central.~ + +- Updates `pekkoVersion` to `2.0.0`; Pekko HTTP also to `2.0.0`. +- ~Adds the Apache staging repository to the build, the scripted tests and the Gradle scripted fixtures. This should be removed once Pekko 2.0.0 is on Maven Central.~ + +# References + +Follows on from #14211, which could not be reopened. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53c13d176fab`. 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/playframework__playframework-14418/tests/oracle.patch b/tasks/playframework__playframework-14418/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1b3dc01ea34711d5283b87a9e61db33abff5fbea --- /dev/null +++ b/tasks/playframework__playframework-14418/tests/oracle.patch @@ -0,0 +1,104 @@ +diff --git a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java +index 4998976ca0..011bca0c88 100644 +--- a/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java ++++ b/documentation/manual/working/javaGuide/main/ws/code/javaguide/ws/Standalone.java +@@ -30,8 +30,8 @@ public class Standalone { + AsyncHttpClientConfig asyncHttpClientConfig = + new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build(); + AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig); + +diff --git a/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala b/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala +index 6266ec9f6a..45059e06ac 100644 +--- a/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala ++++ b/documentation/manual/working/scalaGuide/main/ws/code/ScalaWSStandalone.scala +@@ -24,8 +24,8 @@ object Main { + + val asyncHttpClientConfig = new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build + val asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig) + +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index f8d8510b99..50aeb6c73b 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -8,8 +8,8 @@ import playbuildinfo.BuildInfo + import Keys._ + + object Dependencies { +- val pekkoVersion: String = sys.props.getOrElse("pekko.version", "2.0.0-M4") +- val pekkoHttpVersion = sys.props.getOrElse("pekko.http.version", "2.0.0-M2+47-c525ae28-SNAPSHOT") ++ val pekkoVersion: String = sys.props.getOrElse("pekko.version", "2.0.0") ++ val pekkoHttpVersion = sys.props.getOrElse("pekko.http.version", "2.0.0") + + val playJsonVersion = "3.1.0-M10+90-e2ddbd4c-SNAPSHOT" + +@@ -273,7 +273,7 @@ object Dependencies { + "com.github.ben-manes.caffeine" % "jcache" % caffeineVersion + ) ++ jcacheApi ++ Seq(assertj % Test) + +- val playWsStandaloneVersion = "3.1.0-M14+18-e10c553c-SNAPSHOT" ++ val playWsStandaloneVersion = "3.1.0-M14+81-d2d3ccd9-SNAPSHOT" + val playWsDeps = Seq( + "org.playframework" %% "play-ws-standalone" % playWsStandaloneVersion, + "org.playframework" %% "play-ws-standalone-xml" % playWsStandaloneVersion, +diff --git a/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java b/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java +index 9adca080a4..69f2b6f05f 100644 +--- a/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java ++++ b/transport/client/play-ahc-ws/src/main/java/play/test/WSTestClient.java +@@ -44,8 +44,8 @@ public class WSTestClient { + AsyncHttpClientConfig config = + new DefaultAsyncHttpClientConfig.Builder() + .setMaxRequestRetry(0) +- .setShutdownQuietPeriod(0) +- .setShutdownTimeout(0) ++ .setShutdownQuietPeriod(java.time.Duration.ZERO) ++ .setShutdownTimeout(java.time.Duration.ZERO) + .build(); + + String name = "ws-test-client-" + instanceNumber.getAndIncrement(); +diff --git a/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala b/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala +index de6a2d20ed..1ebc7270a3 100644 +--- a/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala ++++ b/transport/client/play-ahc-ws/src/test/scala/play/api/libs/ws/ahc/AhcWSSpec.scala +@@ -271,7 +271,7 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .asInstanceOf[AhcWSRequest] + .underlying + .buildRequest() +- (req.getRequestTimeout must be).equalTo(1000) ++ (req.getRequestTimeout must be).equalTo(java.time.Duration.ofMillis(1000)) + } + + "support infinite timeout" in { +@@ -280,7 +280,7 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .asInstanceOf[AhcWSRequest] + .underlying + .buildRequest() +- (req.getRequestTimeout must be).equalTo(-1) ++ (req.getRequestTimeout must be).equalTo(java.time.Duration.ofMillis(-1)) + } + + "not support negative timeout" in { +@@ -631,9 +631,9 @@ class AhcWSSpec(implicit ee: ExecutionEnv) + .build() + ahcConfig.isCompressionEnforced must beFalse + ahcConfig.isFollowRedirect must beFalse +- ahcConfig.getConnectTimeout must_== 120000 +- ahcConfig.getRequestTimeout must_== 120000 +- ahcConfig.getReadTimeout must_== 120000 ++ ahcConfig.getConnectTimeout must_== java.time.Duration.ofMinutes(2) ++ ahcConfig.getRequestTimeout must_== java.time.Duration.ofMinutes(2) ++ ahcConfig.getReadTimeout must_== java.time.Duration.ofMinutes(2) + } + } + } diff --git a/tasks/playframework__playframework-14418/tests/test.sh b/tasks/playframework__playframework-14418/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b0de90c0f06e55c412c91716927eb6de641947d --- /dev/null +++ b/tasks/playframework__playframework-14418/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 53c13d176fab94958a02f3ac9b2985c0070c40b4 > "$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/playframework__playframework-14418/tests/verifier.py b/tasks/playframework__playframework-14418/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14418/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/playframework__playframework-14421/environment/Dockerfile b/tasks/playframework__playframework-14421/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df110145d5fa61be8182c64c051441b46b308517 --- /dev/null +++ b/tasks/playframework__playframework-14421/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0a5f8e0c87d9f4d7579514f400b379a8a5e16125 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0a5f8e0c87d9f4d7579514f400b379a8a5e16125 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0a5f8e0c87d9f4d7579514f400b379a8a5e16125 \ + && 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/playframework__playframework-14421/instruction.md b/tasks/playframework__playframework-14421/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b59ebf096f37e97c07dee57ceffdcf59da000be2 --- /dev/null +++ b/tasks/playframework__playframework-14421/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix Mockito matcher imports in documentation tests + +## Description + +Use explicit `ArgumentMatchers` imports to avoid ambiguity with `Mockito._` when Scala exposes inherited Java static methods. + +- See - Fixes for Java inherited statics () + - This made `Mockito._` also expose the inherited matchers from `ArgumentMatchers`. + +Tested locally. + +- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a5f8e0c87d9`. 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/playframework__playframework-14421/solution/patch.diff b/tasks/playframework__playframework-14421/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3ddd36a3b0936027a63a3c73c22333bf3a9e7a8 --- /dev/null +++ b/tasks/playframework__playframework-14421/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala b/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala +index e1f09daff5..788a52dabf 100644 +--- a/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala ++++ b/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala +@@ -9,7 +9,8 @@ import scala.concurrent.Future + + import jakarta.inject.Inject + import org.junit.runner.RunWith +-import org.mockito.ArgumentMatchers._ ++import org.mockito.ArgumentMatchers.any ++import org.mockito.ArgumentMatchers.anyString + import org.mockito.Mockito + import org.mockito.Mockito._ + import org.slf4j._ +diff --git a/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala b/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala +index b7f8366420..cda1671d57 100644 +--- a/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala ++++ b/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala +@@ -4,7 +4,7 @@ + + package scalaguide.tests.specs2 + +-import org.mockito.ArgumentMatchers._ ++import org.mockito.ArgumentMatchers.any + // #import-mockito + import org.mockito.Mockito._ + // #import-mockito diff --git a/tasks/playframework__playframework-14421/solution/solve.sh b/tasks/playframework__playframework-14421/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14421/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/playframework__playframework-14421/task.toml b/tasks/playframework__playframework-14421/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..60c0a07ab13933d8bff9c6b3ecb34d543da86d8f --- /dev/null +++ b/tasks/playframework__playframework-14421/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14421" +description = "Fix Mockito matcher imports in documentation tests" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "0a5f8e0c87d9f4d7579514f400b379a8a5e16125" +reference = "https://github.com/playframework/playframework/pull/14421" +source_access = "auto" +built_at = "2026-11-16T16:09:46.474428+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ee537acd885838eac58aedcffc0d11c35a21ba1d8bcb4316e6fff97641395c73" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-05T09:48:29Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala", + "documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala", +] +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:02.555546+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7c277a6cf0d9f29b77ce75a79bc1b6f4fc63ad8a186d3a5993d3cf6d75b72ba0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14421/tests/capture.py b/tasks/playframework__playframework-14421/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14421/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/playframework__playframework-14421/tests/instruction.md b/tasks/playframework__playframework-14421/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b59ebf096f37e97c07dee57ceffdcf59da000be2 --- /dev/null +++ b/tasks/playframework__playframework-14421/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Fix Mockito matcher imports in documentation tests + +## Description + +Use explicit `ArgumentMatchers` imports to avoid ambiguity with `Mockito._` when Scala exposes inherited Java static methods. + +- See - Fixes for Java inherited statics () + - This made `Mockito._` also expose the inherited matchers from `ArgumentMatchers`. + +Tested locally. + +- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0a5f8e0c87d9`. 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/playframework__playframework-14421/tests/oracle.patch b/tasks/playframework__playframework-14421/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a3ddd36a3b0936027a63a3c73c22333bf3a9e7a8 --- /dev/null +++ b/tasks/playframework__playframework-14421/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala b/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala +index e1f09daff5..788a52dabf 100644 +--- a/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala ++++ b/documentation/manual/working/scalaGuide/main/logging/code/ScalaLoggingSpec.scala +@@ -9,7 +9,8 @@ import scala.concurrent.Future + + import jakarta.inject.Inject + import org.junit.runner.RunWith +-import org.mockito.ArgumentMatchers._ ++import org.mockito.ArgumentMatchers.any ++import org.mockito.ArgumentMatchers.anyString + import org.mockito.Mockito + import org.mockito.Mockito._ + import org.slf4j._ +diff --git a/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala b/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala +index b7f8366420..cda1671d57 100644 +--- a/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala ++++ b/documentation/manual/working/scalaGuide/main/tests/code/specs2/UserServiceSpec.scala +@@ -4,7 +4,7 @@ + + package scalaguide.tests.specs2 + +-import org.mockito.ArgumentMatchers._ ++import org.mockito.ArgumentMatchers.any + // #import-mockito + import org.mockito.Mockito._ + // #import-mockito diff --git a/tasks/playframework__playframework-14421/tests/test.sh b/tasks/playframework__playframework-14421/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..02ade1bb907581b92886976af9fbf0a32509f607 --- /dev/null +++ b/tasks/playframework__playframework-14421/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 0a5f8e0c87d9f4d7579514f400b379a8a5e16125 > "$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/playframework__playframework-14421/tests/verifier.py b/tasks/playframework__playframework-14421/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14421/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/playframework__playframework-14425/environment/Dockerfile b/tasks/playframework__playframework-14425/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..235ff33f5d588ef82869172c9a7f1b5e509fbcc1 --- /dev/null +++ b/tasks/playframework__playframework-14425/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c7741739585dddbeeb8bad867aeaf95f6561746e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c7741739585dddbeeb8bad867aeaf95f6561746e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c7741739585dddbeeb8bad867aeaf95f6561746e \ + && 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/playframework__playframework-14425/instruction.md b/tasks/playframework__playframework-14425/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9729066f09fcc56d4bacfc6bc3db9214ba48e584 --- /dev/null +++ b/tasks/playframework__playframework-14425/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.15.Final (was 7.4.14.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.14.Final` to `7.4.15.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/957428de4691ae6f42991e3d63d6a721c25bc886/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c7741739585d`. 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/playframework__playframework-14425/solution/patch.diff b/tasks/playframework__playframework-14425/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..88b4c45ec3ee1b162ab9583142f7c342b4b5f4ac --- /dev/null +++ b/tasks/playframework__playframework-14425/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index dd64979f0a..f48c898321 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index fc445a9e7f..c71df81cf0 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3f5ed5d46c..10ac6de584 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.14.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.15.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14425/solution/solve.sh b/tasks/playframework__playframework-14425/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14425/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/playframework__playframework-14425/task.toml b/tasks/playframework__playframework-14425/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef9bd254f1d8ceb9358bf1eb3dfd57be25bd60bd --- /dev/null +++ b/tasks/playframework__playframework-14425/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14425" +description = "hibernate-core, ... 7.4.15.Final (was 7.4.14.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "c7741739585dddbeeb8bad867aeaf95f6561746e" +reference = "https://github.com/playframework/playframework/pull/14425" +source_access = "auto" +built_at = "2026-11-16T16:09:46.471261+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:707cb7750740541c49d2f093a671538d825a084f603967550a409883fd032265" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-09T23:02:14Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.556115+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b18a350cd9e1f903b659268baf3bc756f0ebe3369728a198c14d8cf586009d71" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14425/tests/capture.py b/tasks/playframework__playframework-14425/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14425/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/playframework__playframework-14425/tests/instruction.md b/tasks/playframework__playframework-14425/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9729066f09fcc56d4bacfc6bc3db9214ba48e584 --- /dev/null +++ b/tasks/playframework__playframework-14425/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.15.Final (was 7.4.14.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.14.Final` to `7.4.15.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/957428de4691ae6f42991e3d63d6a721c25bc886/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c7741739585d`. 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/playframework__playframework-14425/tests/oracle.patch b/tasks/playframework__playframework-14425/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..88b4c45ec3ee1b162ab9583142f7c342b4b5f4ac --- /dev/null +++ b/tasks/playframework__playframework-14425/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index dd64979f0a..f48c898321 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index fc445a9e7f..c71df81cf0 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 3f5ed5d46c..10ac6de584 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.14.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.14.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.15.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14425/tests/test.sh b/tasks/playframework__playframework-14425/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9091d042a83eea62c8e9425c575b669d4f06ea4c --- /dev/null +++ b/tasks/playframework__playframework-14425/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 c7741739585dddbeeb8bad867aeaf95f6561746e > "$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/playframework__playframework-14425/tests/verifier.py b/tasks/playframework__playframework-14425/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14425/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/playframework__playframework-14434/environment/Dockerfile b/tasks/playframework__playframework-14434/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..235ff33f5d588ef82869172c9a7f1b5e509fbcc1 --- /dev/null +++ b/tasks/playframework__playframework-14434/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c7741739585dddbeeb8bad867aeaf95f6561746e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c7741739585dddbeeb8bad867aeaf95f6561746e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c7741739585dddbeeb8bad867aeaf95f6561746e \ + && 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/playframework__playframework-14434/instruction.md b/tasks/playframework__playframework-14434/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48d349b31e1948c67a35f51bb2b3456bef7ec917 --- /dev/null +++ b/tasks/playframework__playframework-14434/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** [Gradle] Bump gradle-wrapper from 9.8.2 to 9.9.0 in /dev-mode/gradle-plugin + +## Description + +Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.8.2 to 9.9.0. +
+Release notes +

Sourced from gradle-wrapper's releases.

+
+

9.9.0

+

The Gradle team is excited to announce Gradle 9.9.0.

+

Here are the highlights of this release:

+
    +
  • Performance improvements for Kotlin DSL compilation
  • +
  • Test filtering for non-method JUnit Platform tests
  • +
  • Wrapper settings preserved on upgrade
  • +
  • Predefined groups in the Problems API
  • +
+

Read the Release Notes

+

We would like to thank the following community members for their contributions to this release of Gradle: +Aurimas, +devareddy05, +DragonFSKY, +fru1tworld, +Ivan Khanas, +Jeremy Schoemaker, +John Burns, +Labh R Jethe, +Marcin Mycek, +monkey, +Nelson Osacky, +Roberto Perez Alcolea, +Róbert Papp, +SeungTaek Lim, +Stefan Oehme, +万彬宇, +한의준.

+

Upgrade instructions

+

Switch your build to use Gradle 9.9.0 by updating your wrapper:

+
./gradlew :wrapper --gradle-version=9.9.0 && ./gradlew :wrapper
+
+

See the Gradle 9.x upgrade guide to learn about deprecations, breaking changes and other considerations when upgrading.

+

For Java, Groovy, Kotlin and Android compatibility, see the full compatibility notes.

+

Reporting problems

+

If you find a problem with this release, please file a bug on GitHub Issues adhering to our issue guidelines. +If you're not sure you're encountering a bug, please use the forum.

+

We hope you will build happiness with Gradle, and we look forward to your feedback via Twitter or on GitHub.

+

9.9.0 RC1

+

The Gradle team is excited to announce Gradle 9.9.0 RC1.

+ +
+

... (truncated)

+
+
+Commits +
    +
  • dabfe84 Document Groovy 6.0.0 as tested upper bound (#39723)
  • +
  • 122555d Document Groovy 6.0.0 as tested upper bound
  • +
  • 74ee0c8 Update Documentation: Link Build Scan and Develocity from docs pages (#39646)
  • +
  • 62c24fb Address review feedback on troubleshooting page
  • +
  • 8ecd0d6 Stop closing linked issues for PRs merged into release7x (#39703)
  • +
  • f2cb6ca Address review feedback on troubleshooting page
  • +
  • 6c04b55 Upgrade Documentation: Mention the Security Subscription on dependency, wrapp...
  • +
  • cb7f22d Stop closing linked issues for PRs merged into release7x
  • +
  • 8630de3 Use a task-not-found failure on troubleshooting
  • +
  • 1ae7701 Restore Extended Security Support section title
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=gradle-wrapper&package-manager=gradle&previous-version=9.8.2&new-version=9.9.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
+Dependabot commands and options +
+ +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c7741739585d`. 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/playframework__playframework-14434/solution/patch.diff b/tasks/playframework__playframework-14434/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..271a7fd6e90cfe1bce741a2f6a6babd624d6bf8f --- /dev/null +++ b/tasks/playframework__playframework-14434/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar +index 9fa7f28828..51cbd2a6f8 100644 +Binary files a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar and b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar differ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +index bb13f07ba6..33835eab21 100644 +--- a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties ++++ b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +@@ -1,7 +1,7 @@ + distributionBase=GRADLE_USER_HOME + distributionPath=wrapper/dists +-distributionSha256Sum=a1bb7e9651ef09e4cd9a62d471564e0ee23b5757e5f21fd7358d7cfc21018fdf +-distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip ++distributionSha256Sum=7aaba33a6aa7d03e0c7890869da1f1b5e1765c4d71db981a9d5db5cc47a10a6d ++distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-all.zip + networkTimeout=10000 + validateDistributionUrl=true + zipStoreBase=GRADLE_USER_HOME diff --git a/tasks/playframework__playframework-14434/solution/solve.sh b/tasks/playframework__playframework-14434/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14434/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/playframework__playframework-14434/task.toml b/tasks/playframework__playframework-14434/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a9d875cf879e1abb6a6b17c12475b10b70a9fc6e --- /dev/null +++ b/tasks/playframework__playframework-14434/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14434" +description = "[Gradle] Bump gradle-wrapper from 9.8.2 to 9.9.0 in /dev-mode/gradle-plugin" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "c7741739585dddbeeb8bad867aeaf95f6561746e" +reference = "https://github.com/playframework/playframework/pull/14434" +source_access = "auto" +built_at = "2026-11-16T16:09:46.466780+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eed801a9662114fda4aeeaf560b2c2cdd685febb0520f38e5ce850d375946bb8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-16T09:10:45Z" +diff_format = "unified" +context_files = [ + "dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar", + "dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties", +] +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:02.556680+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b18a350cd9e1f903b659268baf3bc756f0ebe3369728a198c14d8cf586009d71" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14434/tests/capture.py b/tasks/playframework__playframework-14434/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14434/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/playframework__playframework-14434/tests/instruction.md b/tasks/playframework__playframework-14434/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48d349b31e1948c67a35f51bb2b3456bef7ec917 --- /dev/null +++ b/tasks/playframework__playframework-14434/tests/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** [Gradle] Bump gradle-wrapper from 9.8.2 to 9.9.0 in /dev-mode/gradle-plugin + +## Description + +Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.8.2 to 9.9.0. +
+Release notes +

Sourced from gradle-wrapper's releases.

+
+

9.9.0

+

The Gradle team is excited to announce Gradle 9.9.0.

+

Here are the highlights of this release:

+
    +
  • Performance improvements for Kotlin DSL compilation
  • +
  • Test filtering for non-method JUnit Platform tests
  • +
  • Wrapper settings preserved on upgrade
  • +
  • Predefined groups in the Problems API
  • +
+

Read the Release Notes

+

We would like to thank the following community members for their contributions to this release of Gradle: +Aurimas, +devareddy05, +DragonFSKY, +fru1tworld, +Ivan Khanas, +Jeremy Schoemaker, +John Burns, +Labh R Jethe, +Marcin Mycek, +monkey, +Nelson Osacky, +Roberto Perez Alcolea, +Róbert Papp, +SeungTaek Lim, +Stefan Oehme, +万彬宇, +한의준.

+

Upgrade instructions

+

Switch your build to use Gradle 9.9.0 by updating your wrapper:

+
./gradlew :wrapper --gradle-version=9.9.0 && ./gradlew :wrapper
+
+

See the Gradle 9.x upgrade guide to learn about deprecations, breaking changes and other considerations when upgrading.

+

For Java, Groovy, Kotlin and Android compatibility, see the full compatibility notes.

+

Reporting problems

+

If you find a problem with this release, please file a bug on GitHub Issues adhering to our issue guidelines. +If you're not sure you're encountering a bug, please use the forum.

+

We hope you will build happiness with Gradle, and we look forward to your feedback via Twitter or on GitHub.

+

9.9.0 RC1

+

The Gradle team is excited to announce Gradle 9.9.0 RC1.

+ +
+

... (truncated)

+
+
+Commits +
    +
  • dabfe84 Document Groovy 6.0.0 as tested upper bound (#39723)
  • +
  • 122555d Document Groovy 6.0.0 as tested upper bound
  • +
  • 74ee0c8 Update Documentation: Link Build Scan and Develocity from docs pages (#39646)
  • +
  • 62c24fb Address review feedback on troubleshooting page
  • +
  • 8ecd0d6 Stop closing linked issues for PRs merged into release7x (#39703)
  • +
  • f2cb6ca Address review feedback on troubleshooting page
  • +
  • 6c04b55 Upgrade Documentation: Mention the Security Subscription on dependency, wrapp...
  • +
  • cb7f22d Stop closing linked issues for PRs merged into release7x
  • +
  • 8630de3 Use a task-not-found failure on troubleshooting
  • +
  • 1ae7701 Restore Extended Security Support section title
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=gradle-wrapper&package-manager=gradle&previous-version=9.8.2&new-version=9.9.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
+Dependabot commands and options +
+ +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c7741739585d`. 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/playframework__playframework-14434/tests/oracle.patch b/tasks/playframework__playframework-14434/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..271a7fd6e90cfe1bce741a2f6a6babd624d6bf8f --- /dev/null +++ b/tasks/playframework__playframework-14434/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar +index 9fa7f28828..51cbd2a6f8 100644 +Binary files a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar and b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.jar differ +diff --git a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +index bb13f07ba6..33835eab21 100644 +--- a/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties ++++ b/dev-mode/gradle-plugin/gradle/wrapper/gradle-wrapper.properties +@@ -1,7 +1,7 @@ + distributionBase=GRADLE_USER_HOME + distributionPath=wrapper/dists +-distributionSha256Sum=a1bb7e9651ef09e4cd9a62d471564e0ee23b5757e5f21fd7358d7cfc21018fdf +-distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip ++distributionSha256Sum=7aaba33a6aa7d03e0c7890869da1f1b5e1765c4d71db981a9d5db5cc47a10a6d ++distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-all.zip + networkTimeout=10000 + validateDistributionUrl=true + zipStoreBase=GRADLE_USER_HOME diff --git a/tasks/playframework__playframework-14434/tests/test.sh b/tasks/playframework__playframework-14434/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9091d042a83eea62c8e9425c575b669d4f06ea4c --- /dev/null +++ b/tasks/playframework__playframework-14434/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 c7741739585dddbeeb8bad867aeaf95f6561746e > "$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/playframework__playframework-14434/tests/verifier.py b/tasks/playframework__playframework-14434/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14434/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/playframework__playframework-14444/environment/Dockerfile b/tasks/playframework__playframework-14444/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4dd76480cea76e104085e8ffeddd67244d05db9c --- /dev/null +++ b/tasks/playframework__playframework-14444/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a794d51966cb20eaa98daf6d7ec8b3bad2407f15 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a794d51966cb20eaa98daf6d7ec8b3bad2407f15 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a794d51966cb20eaa98daf6d7ec8b3bad2407f15 \ + && 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/playframework__playframework-14444/instruction.md b/tasks/playframework__playframework-14444/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07c0690ce9914c131d2357fd1354dd62e735756d --- /dev/null +++ b/tasks/playframework__playframework-14444/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.16.Final (was 7.4.15.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.15.Final` to `7.4.16.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/189c05fe74677dd7c06499f1fbaa5deed21236e5/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a794d51966cb`. 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/playframework__playframework-14444/solution/patch.diff b/tasks/playframework__playframework-14444/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..55a6c3d76af88b7bc33696a130df3a7e1c35dc11 --- /dev/null +++ b/tasks/playframework__playframework-14444/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index f48c898321..d579a8474d 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index c71df81cf0..259debdf58 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 0bf6074a47..56ff721026 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.15.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.16.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14444/solution/solve.sh b/tasks/playframework__playframework-14444/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14444/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/playframework__playframework-14444/task.toml b/tasks/playframework__playframework-14444/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c325ea64f27ef731a979075934d4c71915722e9f --- /dev/null +++ b/tasks/playframework__playframework-14444/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14444" +description = "hibernate-core, ... 7.4.16.Final (was 7.4.15.Final)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "a794d51966cb20eaa98daf6d7ec8b3bad2407f15" +reference = "https://github.com/playframework/playframework/pull/14444" +source_access = "auto" +built_at = "2026-11-16T16:09:46.468995+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:46dde30154ee1bb0d01caa2248283936082787a4352b498317f9cdf2d0f53adc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-16T08:24:22Z" +diff_format = "unified" +context_files = [ + "documentation/manual/working/commonGuide/build/code/dependencies.sbt", + "documentation/manual/working/javaGuide/main/sql/code/jpa.sbt", + "project/Dependencies.scala", +] +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:02.557223+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f34bd0a7be489d38a51c4cb1087fd8081d314635ac083891db0b1143a4c3db5f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14444/tests/capture.py b/tasks/playframework__playframework-14444/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14444/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/playframework__playframework-14444/tests/instruction.md b/tasks/playframework__playframework-14444/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07c0690ce9914c131d2357fd1354dd62e735756d --- /dev/null +++ b/tasks/playframework__playframework-14444/tests/instruction.md @@ -0,0 +1,104 @@ +# Issue + +**Title:** hibernate-core, ... 7.4.16.Final (was 7.4.15.Final) + +## Description + +## About this PR +📦 Updates +* [org.hibernate.orm:hibernate-core](https://github.com/hibernate/hibernate-orm) +* [org.hibernate.orm:hibernate-scan-jandex](https://github.com/hibernate/hibernate-orm) + + from `7.4.15.Final` to `7.4.16.Final` + +## Usage +✅ **Please merge!** + +I'll automatically update this PR to resolve conflicts as long as you don't change it yourself. + +If you'd like to skip this version, you can just close this PR. If you have any feedback, just mention me in the comments below. + +Configure Scala Steward for your repository with a [`.scala-steward.conf`](https://github.com/scala-steward-org/scala-steward/blob/189c05fe74677dd7c06499f1fbaa5deed21236e5/docs/repo-specific-configuration.md) file. + +_Have a fantastic day writing Scala!_ + +
+⚙ Adjust future updates + +Add this to your `.scala-steward.conf` file to ignore future updates of this dependency: +``` +updates.ignore = [ { groupId = "org.hibernate.orm" } ] +``` +Or, add this to slow down future updates of this dependency: +``` +dependencyOverrides = [{ + pullRequests = { frequency = "30 days" }, + dependency = { groupId = "org.hibernate.orm" } +}] +``` +
+ + +labels: test-library-update, commit-count:1 + + + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a794d51966cb`. 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/playframework__playframework-14444/tests/oracle.patch b/tasks/playframework__playframework-14444/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..55a6c3d76af88b7bc33696a130df3a7e1c35dc11 --- /dev/null +++ b/tasks/playframework__playframework-14444/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/documentation/manual/working/commonGuide/build/code/dependencies.sbt b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +index f48c898321..d579a8474d 100644 +--- a/documentation/manual/working/commonGuide/build/code/dependencies.sbt ++++ b/documentation/manual/working/commonGuide/build/code/dependencies.sbt +@@ -11,7 +11,7 @@ libraryDependencies += "org.apache.derby" % "derby" % "10.16.1.1" % "test" + //#multi-deps + libraryDependencies ++= Seq( + "org.apache.derby" % "derby" % "10.16.1.1", +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" + ) + //#multi-deps + +diff --git a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +index c71df81cf0..259debdf58 100644 +--- a/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt ++++ b/documentation/manual/working/javaGuide/main/sql/code/jpa.sbt +@@ -5,7 +5,7 @@ libraryDependencies ++= Seq( + // With Hibernate ORM 7+, list your entities explicitly in persistence.xml. + // If you prefer automatic entity discovery, add org.hibernate.orm:hibernate-scan-jandex. + javaJpa, +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" // replace by your jpa implementation ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" // replace by your jpa implementation + // If you enable Hibernate Validator, also add a Jakarta EL implementation. + ) + //#jpa-sbt-dependencies +diff --git a/project/Dependencies.scala b/project/Dependencies.scala +index 0bf6074a47..56ff721026 100644 +--- a/project/Dependencies.scala ++++ b/project/Dependencies.scala +@@ -86,8 +86,8 @@ object Dependencies { + + val jpaDeps = Seq( + "jakarta.persistence" % "jakarta.persistence-api" % "3.2.0", +- "org.hibernate.orm" % "hibernate-core" % "7.4.15.Final" % "test", +- "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.15.Final" % "test" ++ "org.hibernate.orm" % "hibernate-core" % "7.4.16.Final" % "test", ++ "org.hibernate.orm" % "hibernate-scan-jandex" % "7.4.16.Final" % "test" + ) + + def scalaReflect(scalaVersion: String) = CrossVersion.partialVersion(scalaVersion) match { diff --git a/tasks/playframework__playframework-14444/tests/test.sh b/tasks/playframework__playframework-14444/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7a77c98290da1148296d066f2b4ad7abe21754a --- /dev/null +++ b/tasks/playframework__playframework-14444/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 a794d51966cb20eaa98daf6d7ec8b3bad2407f15 > "$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/playframework__playframework-14444/tests/verifier.py b/tasks/playframework__playframework-14444/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14444/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/playframework__playframework-14448/environment/Dockerfile b/tasks/playframework__playframework-14448/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c22175ceb11f0bf3a1830468d1ddc0f295537927 --- /dev/null +++ b/tasks/playframework__playframework-14448/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/playframework/playframework.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/playframework/playframework.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/playframework/playframework.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 53c13d176fab94958a02f3ac9b2985c0070c40b4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 53c13d176fab94958a02f3ac9b2985c0070c40b4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 53c13d176fab94958a02f3ac9b2985c0070c40b4 \ + && 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/playframework__playframework-14448/instruction.md b/tasks/playframework__playframework-14448/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbd95bbf0a21536f55a0f766d841ceee5037812d --- /dev/null +++ b/tasks/playframework__playframework-14448/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Upgrade sbt to 2.1.0 and Scala 3.10.1 + +## Description + +## Summary +- Upgrade sbt from 2.1.0-RC3 to 2.1.0. +- Run the `3.next` test lane with Scala 3.10.1 instead of 3.10.1-RC2; published Scala versions remain unchanged. +- Update the sbt 2 plugin baseline and CI sbt matrix; align the root Twirl plugin snapshot with the newer snapshot already used by the documentation build. The sbt 2 plugin compiler remains Scala 3.9.0. + +## Verification +- `git diff --check` passed. +- Local builds and tests were not run; CI will exercise the updated versions. + +Prepared with OpenAI Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53c13d176fab`. 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/playframework__playframework-14448/solution/patch.diff b/tasks/playframework__playframework-14448/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..964a2bb5de7f654bef75e15d1daec735762eea5b --- /dev/null +++ b/tasks/playframework__playframework-14448/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index d536a46ec1..0906e30105 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.13.1", "2.1.0-RC3" ], ++ "sbt": [ "1.13.1", "2.1.0" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index a8c854d1b0..2b0d06921b 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-RC3 ++sbt.version=2.1.0 +diff --git a/project/Versions.scala b/project/Versions.scala +index 31cd871bce..8b18784006 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -7,7 +7,7 @@ object ScalaVersions { + val scala213Version = "2.13.18" + val scala33LTSVersion = "3.3.9" + val scala39LTSVersion = "3.9.0" +- val scala3NextVersion = "3.10.1-RC2" ++ val scala3NextVersion = "3.10.1" + + val publishedScalaVersions = Seq(scala213Version, scala33LTSVersion) + val testedScalaVersions = +@@ -25,5 +25,5 @@ object ScalaVersions { + + object SbtVersions { + val sbt1 = "1.13.1" +- val sbt2 = "2.1.0-RC3" ++ val sbt2 = "2.1.0" + } +diff --git a/project/build.properties b/project/build.properties +index eee83be418..5ccc319dde 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-RC3 ++sbt.version=2.1.0 +diff --git a/project/plugins.sbt b/project/plugins.sbt +index 2d6fd44ca8..d82462dbaa 100644 +--- a/project/plugins.sbt ++++ b/project/plugins.sbt +@@ -14,7 +14,7 @@ val webjarsLocatorCore = "0.59" + val sbtHeader = "5.11.0" + val scalafmt = "2.5.6" + val sbtTwirl: String = +- sys.props.getOrElse("twirl.version", "2.1.0-M9+166-35397d5a-SNAPSHOT") // sync with documentation/project/plugins.sbt ++ sys.props.getOrElse("twirl.version", "2.1.0-M9+168-53e6024d-SNAPSHOT") // sync with documentation/project/plugins.sbt + + buildInfoPackage := "playbuildinfo" + buildInfoKeys := Seq[BuildInfoKey]( diff --git a/tasks/playframework__playframework-14448/solution/solve.sh b/tasks/playframework__playframework-14448/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/playframework__playframework-14448/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/playframework__playframework-14448/task.toml b/tasks/playframework__playframework-14448/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d14ac1aae0ca1f273975567a63841197d418ef2f --- /dev/null +++ b/tasks/playframework__playframework-14448/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/playframework__playframework-14448" +description = "Upgrade sbt to 2.1.0 and Scala 3.10.1" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "playframework", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "playframework/playframework" +ref = "53c13d176fab94958a02f3ac9b2985c0070c40b4" +reference = "https://github.com/playframework/playframework/pull/14448" +source_access = "auto" +built_at = "2026-11-16T16:09:46.462418+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:74b54ffc218db93f89c228c43183d9920aa4ae197add958fd5dbe86e3cdc4b40" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-16T13:15:41Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-test.yml", + "documentation/project/build.properties", + "project/Versions.scala", + "project/build.properties", + "project/plugins.sbt", +] +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:02.557756+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a270aca6ea4e6ef1c31187a7ed3f4030e338a48274322b199dc7e32f2d445f8a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/playframework__playframework-14448/tests/capture.py b/tasks/playframework__playframework-14448/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/playframework__playframework-14448/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/playframework__playframework-14448/tests/instruction.md b/tasks/playframework__playframework-14448/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bbd95bbf0a21536f55a0f766d841ceee5037812d --- /dev/null +++ b/tasks/playframework__playframework-14448/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Upgrade sbt to 2.1.0 and Scala 3.10.1 + +## Description + +## Summary +- Upgrade sbt from 2.1.0-RC3 to 2.1.0. +- Run the `3.next` test lane with Scala 3.10.1 instead of 3.10.1-RC2; published Scala versions remain unchanged. +- Update the sbt 2 plugin baseline and CI sbt matrix; align the root Twirl plugin snapshot with the newer snapshot already used by the documentation build. The sbt 2 plugin compiler remains Scala 3.9.0. + +## Verification +- `git diff --check` passed. +- Local builds and tests were not run; CI will exercise the updated versions. + +Prepared with OpenAI Codex. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `53c13d176fab`. 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/playframework__playframework-14448/tests/oracle.patch b/tasks/playframework__playframework-14448/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..964a2bb5de7f654bef75e15d1daec735762eea5b --- /dev/null +++ b/tasks/playframework__playframework-14448/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml +index d536a46ec1..0906e30105 100644 +--- a/.github/workflows/build-test.yml ++++ b/.github/workflows/build-test.yml +@@ -184,7 +184,7 @@ jobs: + scala: 2.13.x, 3.3.x, 3.9.x, 3.next + add-dimensions: >- + { +- "sbt": [ "1.13.1", "2.1.0-RC3" ], ++ "sbt": [ "1.13.1", "2.1.0" ], + "sbt_steps": [ "*1of3", "*2of3", "*3of3" ] + } + exclude: >- +diff --git a/documentation/project/build.properties b/documentation/project/build.properties +index a8c854d1b0..2b0d06921b 100644 +--- a/documentation/project/build.properties ++++ b/documentation/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with project/build.properties +-sbt.version=2.1.0-RC3 ++sbt.version=2.1.0 +diff --git a/project/Versions.scala b/project/Versions.scala +index 31cd871bce..8b18784006 100644 +--- a/project/Versions.scala ++++ b/project/Versions.scala +@@ -7,7 +7,7 @@ object ScalaVersions { + val scala213Version = "2.13.18" + val scala33LTSVersion = "3.3.9" + val scala39LTSVersion = "3.9.0" +- val scala3NextVersion = "3.10.1-RC2" ++ val scala3NextVersion = "3.10.1" + + val publishedScalaVersions = Seq(scala213Version, scala33LTSVersion) + val testedScalaVersions = +@@ -25,5 +25,5 @@ object ScalaVersions { + + object SbtVersions { + val sbt1 = "1.13.1" +- val sbt2 = "2.1.0-RC3" ++ val sbt2 = "2.1.0" + } +diff --git a/project/build.properties b/project/build.properties +index eee83be418..5ccc319dde 100644 +--- a/project/build.properties ++++ b/project/build.properties +@@ -1,4 +1,4 @@ + # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. + + # sync with documentation/project/build.properties +-sbt.version=2.1.0-RC3 ++sbt.version=2.1.0 +diff --git a/project/plugins.sbt b/project/plugins.sbt +index 2d6fd44ca8..d82462dbaa 100644 +--- a/project/plugins.sbt ++++ b/project/plugins.sbt +@@ -14,7 +14,7 @@ val webjarsLocatorCore = "0.59" + val sbtHeader = "5.11.0" + val scalafmt = "2.5.6" + val sbtTwirl: String = +- sys.props.getOrElse("twirl.version", "2.1.0-M9+166-35397d5a-SNAPSHOT") // sync with documentation/project/plugins.sbt ++ sys.props.getOrElse("twirl.version", "2.1.0-M9+168-53e6024d-SNAPSHOT") // sync with documentation/project/plugins.sbt + + buildInfoPackage := "playbuildinfo" + buildInfoKeys := Seq[BuildInfoKey]( diff --git a/tasks/playframework__playframework-14448/tests/test.sh b/tasks/playframework__playframework-14448/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b0de90c0f06e55c412c91716927eb6de641947d --- /dev/null +++ b/tasks/playframework__playframework-14448/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 53c13d176fab94958a02f3ac9b2985c0070c40b4 > "$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/playframework__playframework-14448/tests/verifier.py b/tasks/playframework__playframework-14448/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/playframework__playframework-14448/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/preservim__nerdtree-1001/environment/Dockerfile b/tasks/preservim__nerdtree-1001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acaf1f32c5a97bbb495a1f031bf7092244ccc5fe --- /dev/null +++ b/tasks/preservim__nerdtree-1001/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae \ + && 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/preservim__nerdtree-1001/instruction.md b/tasks/preservim__nerdtree-1001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc1378ac46891828d2bd25620b904e9407c0656f --- /dev/null +++ b/tasks/preservim__nerdtree-1001/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Enable root refresh on "vim ." a different way than #999. + +## Description + +. +Reverts #999. +Fixes a different way. + +Instead of assigning a value to t:NERDTreeBufName for a window tree, +which is used to determine if NERDTree is open, simply also look at the +current buffer's name to see if it matches the NERDTree pattern. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28eb47e2678c`. 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/preservim__nerdtree-1001/solution/patch.diff b/tasks/preservim__nerdtree-1001/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4590be768be06e2799011b80373d286e2a8c7a62 --- /dev/null +++ b/tasks/preservim__nerdtree-1001/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index a893c17..5eac168 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -96,8 +96,7 @@ function! s:Creator.createWindowTree(dir) + + "we need a unique name for each window tree buffer to ensure they are + "all independent +- let t:NERDTreeBufName = self._nextBufferName() +- exec g:NERDTreeCreatePrefix . " edit " . t:NERDTreeBufName ++ exec g:NERDTreeCreatePrefix . " edit " . self._nextBufferName() + + call self._createNERDTree(path, "window") + let b:NERDTree._previousBuf = bufnr(previousBuf) +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index c1ce5ed..e5ba0b5 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -153,7 +153,7 @@ endfunction + + "FUNCTION: s:NERDTree.IsOpen() {{{1 + function! s:NERDTree.IsOpen() +- return s:NERDTree.GetWinNum() != -1 ++ return s:NERDTree.GetWinNum() != -1 || bufname('%') =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' + endfunction + + "FUNCTION: s:NERDTree.isTabTree() {{{1 diff --git a/tasks/preservim__nerdtree-1001/solution/solve.sh b/tasks/preservim__nerdtree-1001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1001/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/preservim__nerdtree-1001/task.toml b/tasks/preservim__nerdtree-1001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a5981a90bd231d3caae8f4fdf9d8da5f2ed8ffa --- /dev/null +++ b/tasks/preservim__nerdtree-1001/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1001" +description = "Enable root refresh on \"vim .\" a different way than #999." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "28eb47e2678cf629d92b4f1f00dd56cba22fc4ae" +reference = "https://github.com/preservim/nerdtree/pull/1001" +source_access = "auto" +built_at = "2026-11-16T16:10:02.478161+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:53bbb097118d891eef49d3416dac5d4195c2d34be374a613c60b8af24fb16972" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-13T13:16:56Z" +diff_format = "unified" +context_files = [ + "lib/nerdtree/creator.vim", + "lib/nerdtree/nerdtree.vim", +] +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:02.558315+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6bac9fd7ca2ffaaf5d34274178c65f09a4c2ef931667d47b7c5b3c00b094d71c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1001/tests/capture.py b/tasks/preservim__nerdtree-1001/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1001/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/preservim__nerdtree-1001/tests/instruction.md b/tasks/preservim__nerdtree-1001/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc1378ac46891828d2bd25620b904e9407c0656f --- /dev/null +++ b/tasks/preservim__nerdtree-1001/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Enable root refresh on "vim ." a different way than #999. + +## Description + +. +Reverts #999. +Fixes a different way. + +Instead of assigning a value to t:NERDTreeBufName for a window tree, +which is used to determine if NERDTree is open, simply also look at the +current buffer's name to see if it matches the NERDTree pattern. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28eb47e2678c`. 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/preservim__nerdtree-1001/tests/oracle.patch b/tasks/preservim__nerdtree-1001/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4590be768be06e2799011b80373d286e2a8c7a62 --- /dev/null +++ b/tasks/preservim__nerdtree-1001/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index a893c17..5eac168 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -96,8 +96,7 @@ function! s:Creator.createWindowTree(dir) + + "we need a unique name for each window tree buffer to ensure they are + "all independent +- let t:NERDTreeBufName = self._nextBufferName() +- exec g:NERDTreeCreatePrefix . " edit " . t:NERDTreeBufName ++ exec g:NERDTreeCreatePrefix . " edit " . self._nextBufferName() + + call self._createNERDTree(path, "window") + let b:NERDTree._previousBuf = bufnr(previousBuf) +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index c1ce5ed..e5ba0b5 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -153,7 +153,7 @@ endfunction + + "FUNCTION: s:NERDTree.IsOpen() {{{1 + function! s:NERDTree.IsOpen() +- return s:NERDTree.GetWinNum() != -1 ++ return s:NERDTree.GetWinNum() != -1 || bufname('%') =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' + endfunction + + "FUNCTION: s:NERDTree.isTabTree() {{{1 diff --git a/tasks/preservim__nerdtree-1001/tests/test.sh b/tasks/preservim__nerdtree-1001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba3c4bd947288b487254f59aeede05774cc40af9 --- /dev/null +++ b/tasks/preservim__nerdtree-1001/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 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae > "$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/preservim__nerdtree-1001/tests/verifier.py b/tasks/preservim__nerdtree-1001/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1001/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/preservim__nerdtree-1002/environment/Dockerfile b/tasks/preservim__nerdtree-1002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acaf1f32c5a97bbb495a1f031bf7092244ccc5fe --- /dev/null +++ b/tasks/preservim__nerdtree-1002/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae \ + && 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/preservim__nerdtree-1002/instruction.md b/tasks/preservim__nerdtree-1002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8dc69cf209491f156cbb928aedb8b6425da3d1ff --- /dev/null +++ b/tasks/preservim__nerdtree-1002/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add a "copy path to clipboard" menu option + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28eb47e2678c`. 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/preservim__nerdtree-1002/solution/patch.diff b/tasks/preservim__nerdtree-1002/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..78c7313bc6bef03e2b0e7f6e0989f89a99d216a2 --- /dev/null +++ b/tasks/preservim__nerdtree-1002/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 3eef517..5c37e4d 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -37,6 +37,7 @@ endif + if g:NERDTreePath.CopyingSupported() + call NERDTreeAddMenuItem({'text': '(c)opy the current node', 'shortcut': 'c', 'callback': 'NERDTreeCopyNode'}) + endif ++call NERDTreeAddMenuItem({'text': (has("clipboard")?'copy (p)ath to clipboard':'print (p)ath to screen'), 'shortcut': 'p', 'callback': 'NERDTreeCopyPath'}) + + if has("unix") || has("osx") + call NERDTreeAddMenuItem({'text': '(l)ist the current node', 'shortcut': 'l', 'callback': 'NERDTreeListNode'}) +@@ -364,6 +365,17 @@ function! NERDTreeCopyNode() + redraw! + endfunction + ++" FUNCTION: NERDTreeCopyPath() {{{1 ++function! NERDTreeCopyPath() ++ let l:nodePath = g:NERDTreeFileNode.GetSelected().path.str() ++ if has("clipboard") ++ let @* = l:nodePath ++ call nerdtree#echo("The path [" . l:nodePath . "] was copied to your clipboard.") ++ else ++ call nerdtree#echo("The full path is: " . l:nodePath) ++ endif ++endfunction ++ + " FUNCTION: NERDTreeQuickLook() {{{1 + function! NERDTreeQuickLook() + let treenode = g:NERDTreeFileNode.GetSelected() diff --git a/tasks/preservim__nerdtree-1002/solution/solve.sh b/tasks/preservim__nerdtree-1002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1002/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/preservim__nerdtree-1002/task.toml b/tasks/preservim__nerdtree-1002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b42cf7651c7ae2e41993460d86de00042a3f64b8 --- /dev/null +++ b/tasks/preservim__nerdtree-1002/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1002" +description = "Add a \"copy path to clipboard\" menu option" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "28eb47e2678cf629d92b4f1f00dd56cba22fc4ae" +reference = "https://github.com/preservim/nerdtree/pull/1002" +source_access = "auto" +built_at = "2026-11-16T16:10:02.476911+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d9741fb35b076a1fd9cca9e439d414029a5f0b2c8b3d95e8a376f09510c1a4ec" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-13T13:17:19Z" +diff_format = "unified" +context_files = [ + "nerdtree_plugin/fs_menu.vim", +] +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:02.558829+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6bac9fd7ca2ffaaf5d34274178c65f09a4c2ef931667d47b7c5b3c00b094d71c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1002/tests/capture.py b/tasks/preservim__nerdtree-1002/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1002/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/preservim__nerdtree-1002/tests/instruction.md b/tasks/preservim__nerdtree-1002/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8dc69cf209491f156cbb928aedb8b6425da3d1ff --- /dev/null +++ b/tasks/preservim__nerdtree-1002/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add a "copy path to clipboard" menu option + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `28eb47e2678c`. 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/preservim__nerdtree-1002/tests/oracle.patch b/tasks/preservim__nerdtree-1002/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..78c7313bc6bef03e2b0e7f6e0989f89a99d216a2 --- /dev/null +++ b/tasks/preservim__nerdtree-1002/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 3eef517..5c37e4d 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -37,6 +37,7 @@ endif + if g:NERDTreePath.CopyingSupported() + call NERDTreeAddMenuItem({'text': '(c)opy the current node', 'shortcut': 'c', 'callback': 'NERDTreeCopyNode'}) + endif ++call NERDTreeAddMenuItem({'text': (has("clipboard")?'copy (p)ath to clipboard':'print (p)ath to screen'), 'shortcut': 'p', 'callback': 'NERDTreeCopyPath'}) + + if has("unix") || has("osx") + call NERDTreeAddMenuItem({'text': '(l)ist the current node', 'shortcut': 'l', 'callback': 'NERDTreeListNode'}) +@@ -364,6 +365,17 @@ function! NERDTreeCopyNode() + redraw! + endfunction + ++" FUNCTION: NERDTreeCopyPath() {{{1 ++function! NERDTreeCopyPath() ++ let l:nodePath = g:NERDTreeFileNode.GetSelected().path.str() ++ if has("clipboard") ++ let @* = l:nodePath ++ call nerdtree#echo("The path [" . l:nodePath . "] was copied to your clipboard.") ++ else ++ call nerdtree#echo("The full path is: " . l:nodePath) ++ endif ++endfunction ++ + " FUNCTION: NERDTreeQuickLook() {{{1 + function! NERDTreeQuickLook() + let treenode = g:NERDTreeFileNode.GetSelected() diff --git a/tasks/preservim__nerdtree-1002/tests/test.sh b/tasks/preservim__nerdtree-1002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba3c4bd947288b487254f59aeede05774cc40af9 --- /dev/null +++ b/tasks/preservim__nerdtree-1002/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 28eb47e2678cf629d92b4f1f00dd56cba22fc4ae > "$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/preservim__nerdtree-1002/tests/verifier.py b/tasks/preservim__nerdtree-1002/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1002/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/preservim__nerdtree-1005/environment/Dockerfile b/tasks/preservim__nerdtree-1005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eabaf52c1a5596b176c33b27a6d87935cfb027ab --- /dev/null +++ b/tasks/preservim__nerdtree-1005/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 12dea6ccb2381a2b6b8ae0bf17b4078699bbfec3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 12dea6ccb2381a2b6b8ae0bf17b4078699bbfec3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 12dea6ccb2381a2b6b8ae0bf17b4078699bbfec3 \ + && 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/preservim__nerdtree-1005/instruction.md b/tasks/preservim__nerdtree-1005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9610119c651ad79ce5938f4d1b343806f2a9e028 --- /dev/null +++ b/tasks/preservim__nerdtree-1005/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Refresh a dir_node if the file wasn't found in it, and look once more. + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `12dea6ccb238`. 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/preservim__nerdtree-1005/solution/patch.diff b/tasks/preservim__nerdtree-1005/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..32d4b35eb7b6765c95cd5d70d9bd94b499ba60b2 --- /dev/null +++ b/tasks/preservim__nerdtree-1005/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index a834e7c..aa9dea6 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -620,6 +620,11 @@ function! s:TreeDirNode.reveal(path, ...) + + if self.path.equals(a:path.getParent()) + let n = self.findNode(a:path) ++ " We may be looking for a newly-saved file that isn't in the tree yet. ++ if n == {} ++ call self.refresh() ++ let n = self.findNode(a:path) ++ endif + if has_key(opts, "open") + call n.open() + endif diff --git a/tasks/preservim__nerdtree-1005/solution/solve.sh b/tasks/preservim__nerdtree-1005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1005/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/preservim__nerdtree-1005/task.toml b/tasks/preservim__nerdtree-1005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a19a88030d5da00f05da1b70490f82e809f2bca --- /dev/null +++ b/tasks/preservim__nerdtree-1005/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1005" +description = "Refresh a dir_node if the file wasn't found in it, and look once more." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "12dea6ccb2381a2b6b8ae0bf17b4078699bbfec3" +reference = "https://github.com/preservim/nerdtree/pull/1005" +source_access = "auto" +built_at = "2026-11-16T16:10:02.475644+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f1fc6e37037ebdf80ce1792096a47a19a7a2465f69c905b3b6feacb4f53f211b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-18T14:27:00Z" +diff_format = "unified" +context_files = [ + "lib/nerdtree/tree_dir_node.vim", +] +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:02.559349+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ee406791930d6ebd3fcbcbfac71d8f47ca83790abb1d769beb5434a9c81dd472" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1005/tests/capture.py b/tasks/preservim__nerdtree-1005/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1005/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/preservim__nerdtree-1005/tests/instruction.md b/tasks/preservim__nerdtree-1005/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9610119c651ad79ce5938f4d1b343806f2a9e028 --- /dev/null +++ b/tasks/preservim__nerdtree-1005/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Refresh a dir_node if the file wasn't found in it, and look once more. + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `12dea6ccb238`. 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/preservim__nerdtree-1005/tests/oracle.patch b/tasks/preservim__nerdtree-1005/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..32d4b35eb7b6765c95cd5d70d9bd94b499ba60b2 --- /dev/null +++ b/tasks/preservim__nerdtree-1005/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index a834e7c..aa9dea6 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -620,6 +620,11 @@ function! s:TreeDirNode.reveal(path, ...) + + if self.path.equals(a:path.getParent()) + let n = self.findNode(a:path) ++ " We may be looking for a newly-saved file that isn't in the tree yet. ++ if n == {} ++ call self.refresh() ++ let n = self.findNode(a:path) ++ endif + if has_key(opts, "open") + call n.open() + endif diff --git a/tasks/preservim__nerdtree-1005/tests/test.sh b/tasks/preservim__nerdtree-1005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a78f24b6340b6aa9de0f177521f6043fa9f5d5eb --- /dev/null +++ b/tasks/preservim__nerdtree-1005/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 12dea6ccb2381a2b6b8ae0bf17b4078699bbfec3 > "$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/preservim__nerdtree-1005/tests/verifier.py b/tasks/preservim__nerdtree-1005/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1005/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/preservim__nerdtree-1007/environment/Dockerfile b/tasks/preservim__nerdtree-1007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b6d126c39c9088a41531d9c7f119f52d8d167a9f --- /dev/null +++ b/tasks/preservim__nerdtree-1007/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 33fe2fdf16a95c12e8284364c780ed405dbaad17 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 33fe2fdf16a95c12e8284364c780ed405dbaad17 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 33fe2fdf16a95c12e8284364c780ed405dbaad17 \ + && 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/preservim__nerdtree-1007/instruction.md b/tasks/preservim__nerdtree-1007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c6ee112c5a255953a249dd264fddb1937fcc6b7 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update Changelog and create PR Template + +## 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 `33fe2fdf16a9`. 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/preservim__nerdtree-1007/solution/patch.diff b/tasks/preservim__nerdtree-1007/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d1194a8aaa0f0c8212044e580fa0308dcff1c9d0 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/solution/patch.diff @@ -0,0 +1,473 @@ +diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md +new file mode 100644 +index 0000000..a60d1d4 +--- /dev/null ++++ b/.github/PULL_REQUEST_TEMPLATE.md +@@ -0,0 +1,22 @@ ++ ++### Description of Changes ++ ++Closes # ++ ++--- ++### New Version Info ++ ++- [ ] Derive a new version number. Increment the: ++ - [ ] `MAJOR` version when you make incompatible API changes, ++ - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and ++ - [ ] `PATCH` version when you make backwards-compatible bug fixes. ++- [ ] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) ++- [ ] Update the ChangeLog, following this format/example: ++ ``` ++ MAJOR.MINOR... ++ - **.PATCH**: PR Title (Author) #PR Number ++ ++ ### 5.1... ++ - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++ - **.0**: Too many changes for one patch... ++ ``` +diff --git a/CHANGELOG b/CHANGELOG +deleted file mode 100644 +index 6dac46d..0000000 +--- a/CHANGELOG ++++ /dev/null +@@ -1,179 +0,0 @@ +-Next +- - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) #759 +- - Update doc with already existing mapping variables (asnr) #699 +- - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) #696 +- - Correct NERDTreeIgnore pattern in doc (cntoplolicon) #648 +- - Remove empty segments when splitting path (sooth-sayer) #574 +- - Suppress autocmds less agressively (wincent) #578 #691 +- - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (josephfrazier) #676 +- - Don't touch @o and @h registers when rendering +- - Fix bug with files and directories with dollar signs (alegen) #649 +- - Reuse/reopen existing window trees where possible #244 +- - Remove NERDTree.previousBuf() +- - Change color of arrow (Leeiio) #630 +- - Improved a tip in README.markdown (ggicci) #628 +- - Shorten delete confimration of empty directory to 'y' (mikeperri) #530 +- - Fix API call to open directory tree in window (devm33) #533 +- - Change default arrows on non-Windows platforms (gwilk) #546 +- - Update to README - combine cd and git clone (zwhitchcox) #584 +- - Update to README - Tip: start NERDTree when vim starts (therealplato) #593 +- - Escape filename when moving an open buffer (zacharyvoase) #595 +- - Fixed incorrect :helptags command in README (curran) #619 +- - Fixed incomplete escaping of folder arrows (adityanatraj) #548 +- - Added NERDTreeCascadeSingleChildDir option (juanibiapina) #558 +- - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (SkylerLipthay) #231 +- - Fixed typo in README.markdown - :Helptags -> :helptags +- - Rename "primary" and "secondary" trees to "tab" and "window" trees. +- - Move a bunch of buffer level variables into the NERDTree and UI classes. +- - Display cascading dirs on one line to save vertical/horizontal space (@matt-gardner: brainstorming/testing) +- - Remove the old style UI - Remove 'NERDTreeDirArrows' option. +- - On windows default to + and ~ for expand/collapse directory symbols. +- - Lots more refactoring. Move a bunch of b: level vars into b:NERDTree and friends. +- +-5.0.0 +- - Refactor the code significantly: +- * Break the classes out into their own files. +- * Make the majority of the code OO - previously large parts were +- effectively a tangle of "global" methods. +- - Add an API to assign flags to nodes. This allows VCS plugins like +- https://github.com/Xuyuanp/nerdtree-git-plugin to exist. Thanks to +- Xuyuanp for helping design/test/build said API. +- - add 'scope' argument to the key map API see :help NERDTreeAddKeyMap() +- - add magic [[dir]] and [[file]] flags to NERDTreeIgnore +- - add support for custom path filters. See :help NERDTreeAddPathFilter() +- - add path listener API. See :help NERDTreePathListenerAPI. +- - expand the fs menu functionality to list file properties (PhilRunninger, +- apbarrero, JESii) +- - make bookmarks work with `~` home shortcuts (hiberabyss) +- - show OSX specific fsmenu options in regular vim on mac (evindor) +- - make dir arrow icons configurable (PickRelated) +- - optimise node sorting performance when opening large dirs (vtsang) +- - make the root note render prettier by truncating it at a path slash (gcmt) +- - remove NERDChristmasTree option - its always christmas now +- - add "cascade" open and closing for dirs containing only another single +- dir. See :help NERDTreeCascadeOpenSingleChildDir (pendulm) +- +- Many other fixes, doc updates and contributions from: +- actionshrimp +- SchDen +- egalpin +- cperl82 - many small fixes +- toiffel +- WoLpH +- handcraftedbits +- devmanhinton +- xiaodili +- zhangoose +- gastropoda +- mixvin +- alvan +- lucascaton +- kelaban +- shanesmith +- staeff +- pendulm +- stephenprater +- franksort +- agrussellknives +- AndrewRadev +- Twinside +- +-4.2.0 +- - Add NERDTreeDirArrows option to make the UI use pretty arrow chars +- instead of the old +~| chars to define the tree structure (sickill) +- - shift the syntax highlighting out into its own syntax file (gnap) +- - add some mac specific options to the filesystem menu - for macvim +- only (andersonfreitas) +- - Add NERDTreeMinimalUI option to remove some non functional parts of the +- nerdtree ui (camthompson) +- - tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the +- new behaviour (benjamingeiger) +- - if no name is given to :Bookmark, make it default to the name of the +- target file/dir (minyoung) +- - use 'file' completion when doing copying, create, and move +- operations (EvanDotPro) +- - lots of misc bug fixes (paddyoloughlin, sdewald, camthompson, Vitaly +- Bogdanov, AndrewRadev, mathias, scottstvnsn, kml, wycats, me RAWR!) +- +-4.1.0 +- features: +- - NERDTreeFind to reveal the node for the current buffer in the tree, +- see |NERDTreeFind|. This effectively merges the FindInNERDTree plugin (by +- Doug McInnes) into the script. +- - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan +- Ritter and Rémi Prévost. +- - truncate the root node if wider than the tree window. Thanks to Victor +- Gonzalez. +- +- bugfixes: +- - really fix window state restoring +- - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, +- jfilip1024, and Chris Chambers +- +-4.0.0 +- - add a new programmable menu system (see :help NERDTreeMenu). +- - add new APIs to add menus/menu-items to the menu system as well as +- custom key mappings to the NERD tree buffer (see :help NERDTreeAPI). +- - removed the old API functions +- - added a mapping to maximize/restore the size of nerd tree window, thanks +- to Guillaume Duranceau for the patch. See :help NERDTree-A for details. +- +- - fix a bug where secondary nerd trees (netrw hijacked trees) and +- NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. +- - fix a bug where the script ignored directories whose name ended in a dot, +- thanks to Aggelos Orfanakos for the patch. +- - fix a bug when using the x mapping on the tree root, thanks to Bryan +- Venteicher for the patch. +- - fix a bug where the cursor position/window size of the nerd tree buffer +- wasnt being stored on closing the window, thanks to Richard Hart. +- - fix a bug where NERDTreeMirror would mirror the wrong tree +- +-3.1.1 +- - fix a bug where a non-listed no-name buffer was getting created every +- time the tree windows was created, thanks to Derek Wyatt and owen1 +- - make behave the same as the 'o' mapping +- - some helptag fixes in the doc, thanks strull +- - fix a bug when using :set nohidden and opening a file where the previous +- buf was modified. Thanks iElectric +- - other minor fixes +- +-3.1.0 +- New features: +- - add mappings to open files in a vsplit, see :help NERDTree-s and :help +- NERDTree-gs +- - make the statusline for the nerd tree window default to something +- hopefully more useful. See :help 'NERDTreeStatusline' +- Bugfixes: +- - make the hijack netrw functionality work when vim is started with "vim +- " (thanks to Alf Mikula for the patch). +- - fix a bug where the CWD wasnt being changed for some operations even when +- NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) +- - add -bar to all the nerd tree :commands so they can chain with other +- :commands (thanks to tpope) +- - fix bugs when ignorecase was set (thanks to nach) +- - fix a bug with the relative path code (thanks to nach) +- - fix a bug where doing a :cd would cause :NERDTreeToggle to fail (thanks nach) +- +- +-3.0.1 +- Bugfixes: +- - fix bugs with :NERDTreeToggle and :NERDTreeMirror when 'hidden +- was not set +- - fix a bug where :NERDTree would fail if was relative and +- didnt start with a ./ or ../ Thanks to James Kanze. +- - make the q mapping work with secondary (:e style) trees, +- thanks to jamessan +- - fix a bunch of small bugs with secondary trees +- +- More insane refactoring. +- +-3.0.0 +- - hijack netrw so that doing an :edit will put a NERD tree in +- the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' +- - allow sharing of trees across tabs, see :help :NERDTreeMirror +- - remove "top" and "bottom" as valid settings for NERDTreeWinPos +- - change the '' mapping to 'i' +- - change the 'H' mapping to 'I' +- - lots of refactoring +diff --git a/CHANGELOG.md b/CHANGELOG.md +new file mode 100644 +index 0000000..ec6b35d +--- /dev/null ++++ b/CHANGELOG.md +@@ -0,0 +1,241 @@ ++# Change Log ++ ++### 5.1... ++- **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++- **`.0`**: Too many changes for one patch... ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 ++ - Add a "copy path to clipboard" menu option (@PhilRunninger) #1002 ++ - Enable root refresh on "vim ." a different way than #999. (@PhilRunninger) #1001 ++ - Fix refreshroot (@PhilRunninger) #999 ++ - Change version check to look for 703 not 730 (@vhalis) #994 ++ - Change minimum vim (@PhilRunninger) #991 ++ - Allow multi-character DirArrows (@PhilRunninger) #985 ++ - Remove redraw! while still clearing last message empty string. (@PhilRunninger) #979 ++ - fix _initChildren function value set to numChildrenCached error (@terryding77) #969 ++ - On Windows, do a case-insensitive comparison of paths. (@PhilRunninger) #967 ++ - Remove the "Please wait... DONE" messages. (@PhilRunninger) #966 ++ - Smarter delimiter default (@PhilRunninger) #963 ++ - Update directory .vimdc readme example (@spencerdcarlson) #961 ++ - Preview bookmarks (@PhilRunninger) #956 ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (@PhilRunninger) #955 ++ - Add an :EditBookmarks command to edit the bookmarks file (@PhilRunninger) #954 ++ - Before copying, turn off &shellslash. Restore after copy is finished. (@PhilRunninger) #952 ++ - Set a maximum window size when zooming. (@PhilRunninger) #950 ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (@PhilRunninger) #949 ++ - Escape a backslash so it can be used in a key mapping. (@PhilRunninger) #948 ++ - Add a NERDTreeMinimalMenu feature (@tuzz) #938 ++ - fixed root path error for windows (@zcodes) #935 ++ - Restore getDirChildren for use in nerdtree-project-plugin. (@PhilRunninger) #929 ++ - Document NERDTreeNodeDelimiter #912 (@PhilRunninger) #926 ++ - Allow modification of menu keybindings (@Leandros) #923 ++ - Add two more disqualifications for isCascadable(). (@PhilRunninger) #914 ++ - Allow highlighting more than one flag. (@kristijanhusak) #908 ++ - Support sorting files and directories by modification time. (@PhilRunninger) #901 ++ - Parse . and .. from path string with trailing slash. (@PhilRunninger) #899 ++ - Force sort to recalculate the cached sortKey. (@PhilRunninger) #898 ++ - Add NERDTreeRefreshRoot command (@wgfm) #897 ++ - Call Resolve on the file's path when calling :NERDTreeFind. (@PhilRunninger) #896 ++ - Catch all errors, not just NERDTree errors. (@PhilRunninger) #894 ++ - Fix typo in help file (@lvoisin) #892 ++ - Make NERDTreeCreator set the `'nolist'` option (@lifecrisis) #889 ++ - Refresh buffers after `m`, `m` operation on a folder (@PhilRunninger) #888 ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (@PhilRunninger) #887 ++ - Fix the / motions, which currently fail with cascades (@lifecrisis) #886 ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (@lifecrisis) #882 ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (@PhilRunninger) #878 ++ - Use tabnext instead of gt to allow users to remap gt. (@PhilRunninger) #877 ++ - Do a case sensitive comparison of new/existing buffers. (@PhilRunninger) #875 ++ - Fix opening sub-directories that have commas in their name. (@PhilRunninger) #873 ++ - Add new command to open NERDTree in the root of a VCS repository. (@PhilRunninger) #872 ++ - Make sure the path to the bookmarks file exists before writing it. (@PhilRunninger) #871 ++ - Unzoom NERDTree when opening a file (@PhilRunninger) #870 ++ - Support unusual characters in file and directory names (@PhilRunninger) #868 ++ - Reword renamed-buffer prompt to be more clear (@aflock) #867 ++ - Default to placing cursor on root when closing bookmark table (@lifecrisis) #866 ++ - Fix issues with sorting of nodes (@PhilRunninger) #856 ++ - Better OSX detection (@bubba-h57) #853 ++ - Bugfix - ensure keymaps dictionary exists before using it (@mnussbaum) #852 ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (@mnussbaum) #851 ++ - Add code to sort mappings in quickhelp (@lifecrisis) #849 ++ - Use ":clearjumps" in new NERDTree windows (@lifecrisis) #844 ++ - Like m-c did before, create parent directories if needed on m-m. (@PhilRunninger) #840 ++ - BUGFIX: Repair a problem with the `'u'` mapping. (@lifecrisis) #838 ++ - Make the NERDTree buffer writable when rendering it. (@PhilRunninger) #837 ++ - Code cleanup: Remove unsupported bookmark table mappings (@lifecrisis) #835 ++ - Replace strcharpart() with substitute() for backward compatibility (@bravestarr) #834 ++ - Fixed error `unknown function strcharpart` for older versions of Vim (@hav4ik) #833 ++ - Clear output when NERDTree menu is aborted (@lifecrisis) #832 ++ - Display a path with multi-byte characters correctly when it is truncated (@bravestarr) #830 ++ - Support revealing file and executing file with xdg-open for Linux (@ngnmhieu) #824 ++ - If node isn't open, count children on disk before deleting. (@PhilRunninger) #822 ++ - Add new variable g:NERDTreeRemoveFileCmd (@kutsan) #816 ++ - Use a better check for existence of the NERDTree buffer. (@PhilRunninger) #814 ++ - Fix focussing previous buffer when closing NERDTree (@mrubli) #801 ++ - Update the docs for "NERDTreeStatusline" (@lifecrisis) #796 ++ - BUGFIX: Unstable behavior in the "getPath()" method (@lifecrisis) #795 ++ - Revert the bugfix from pull request #785 (@lifecrisis) #794 ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (@lifecrisis) #786 ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (@lifecrisis) #785 ++ - Add modelines (@lifecrisis) #782 ++ - Change the type of completion used by NERDTreeFind (@lifecrisis) #781 ++ - change NERDTreeFind with args (@zhenyangze) #778 ++ - Style Choice: Using confirm() when deleting a bookmark (@lifecrisis) #777 ++ - remove useless substitute when `file =~# "/$"` (@skyblueee) #773 ++ - remove useless removeLeadingSpaces in _stripMarkup (@skyblueee) #772 ++ - Make the "o" mapping consistent with "x" (@lifecrisis) #769 ++ - Fix a problem with the "x" handler (@lifecrisis) #768 ++ - Clean up the handler for the "x" mapping (@lifecrisis) #767 ++ - Revert change to tab opening method (@lifecrisis) #766 ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (@lifecrisis) #765 ++ - Fix broken "t" and "T" mappings, tabs now open at end (@lifecrisis) #759 ++ - Update doc with already existing mapping variables (@asnr) #699 ++ - Fix the broken g:NERDTreeBookmarksSort setting (@lifecrisis) #696 ++ - Correct NERDTreeIgnore pattern in doc (@cntoplolicon) #648 ++ - Remove empty segments when splitting path (@sooth-sayer) #574 ++ - Suppress autocmds less agressively (@wincent) #578 #691 ++ - Add an Issues template to ask for more info initially. ++ - Fix markdown headers in readme (@josephfrazier) #676 ++ - Don't touch @o and @h registers when rendering ++ - Fix bug with files and directories with dollar signs (@alegen) #649 ++ - Reuse/reopen existing window trees where possible #244 ++ - Remove NERDTree.previousBuf() ++ - Change color of arrow (@Leeiio) #630 ++ - Improved a tip in README.markdown (@ggicci) #628 ++ - Shorten delete confimration of empty directory to `y` (@mikeperri) #530 ++ - Fix API call to open directory tree in window (@devm33) #533 ++ - Change default arrows on non-Windows platforms (@gwilk) #546 ++ - Update to README - combine cd and git clone (@zwhitchcox) #584 ++ - Update to README - Tip: start NERDTree when vim starts (@therealplato) #593 ++ - Escape filename when moving an open buffer (@zacharyvoase) #595 ++ - Fixed incorrect :helptags command in README (@curran) #619 ++ - Fixed incomplete escaping of folder arrows (@adityanatraj) #548 ++ - Added NERDTreeCascadeSingleChildDir option (@juanibiapina) #558 ++ - Replace strchars() with backward compatible workaround. ++ - Add support for copy command in Windows (@SkylerLipthay) #231 ++ - Fixed typo in README.markdown - :Helptags -> :helptags ++ - Rename "primary" and "secondary" trees to "tab" and "window" trees. ++ - Move a bunch of buffer level variables into the NERDTree and UI classes. ++ - Display cascading dirs on one line to save vertical/horizontal space (@matt-gardner: brainstorming/testing) ++ - Remove the old style UI - Remove `NERDTreeDirArrows` option. ++ - On windows default to + and ~ for expand/collapse directory symbols. ++ - Lots more refactoring. Move a bunch of b: level vars into b:NERDTree and friends. ++ ++### 5.0.0 ++- Refactor the code significantly: ++ * Break the classes out into their own files. ++ * Make the majority of the code OO - previously large parts were effectively a tangle of "global" methods. ++- Add an API to assign flags to nodes. This allows VCS plugins like https://github.com/Xuyuanp/nerdtree-git-plugin to exist. Thanks to @Xuyuanp for helping design/test/build said API. ++- add `scope` argument to the key map API see :help NERDTreeAddKeyMap() ++- add magic [[dir]] and [[file]] flags to NERDTreeIgnore ++- add support for custom path filters. See :help NERDTreeAddPathFilter() ++- add path listener API. See :help NERDTreePathListenerAPI. ++- expand the fs menu functionality to list file properties (@PhilRunninger, @apbarrero, @JESii) ++- make bookmarks work with `~` home shortcuts (@hiberabyss) ++- show OSX specific fsmenu options in regular vim on mac (@evindor) ++- make dir arrow icons configurable (@PickRelated) ++- optimise node sorting performance when opening large dirs (@vtsang) ++- make the root note render prettier by truncating it at a path slash (@gcmt) ++- remove NERDChristmasTree option - its always christmas now ++- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (@pendulm) ++- Many other fixes, doc updates and contributions from: ++ - @actionshrimp ++ - @SchDen ++ - @egalpin ++ - @cperl82 - many small fixes ++ - @toiffel ++ - @WoLpH ++ - @handcraftedbits ++ - @devmanhinton ++ - @xiaodili ++ - @zhangoose ++ - @gastropoda ++ - @mixvin ++ - @alvan ++ - @lucascaton ++ - @kelaban ++ - @shanesmith ++ - @staeff ++ - @pendulm ++ - @stephenprater ++ - @franksort ++ - @agrussellknives ++ - @AndrewRadev ++ - @Twinside ++ ++### 4.2.0 ++- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (@sickill) ++- shift the syntax highlighting out into its own syntax file (@gnap) ++- add some mac specific options to the filesystem menu - for macvim only (@andersonfreitas) ++- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (@camthompson) ++- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (@benjamingeiger) ++- if no name is given to :Bookmark, make it default to the name of the target file/dir (@minyoung) ++- use `file` completion when doing copying, create, and move operations (@EvanDotPro) ++- lots of misc bug fixes from: ++ - @paddyoloughlin ++ - @sdewald ++ - @camthompson ++ - @Vitaly ++ - @Bogdanov ++ - @AndrewRadev ++ - @mathias ++ - @scottstvnsn ++ - @kml ++ - @wycats ++ - me RAWR! ++ ++### 4.1.0 ++- features: ++ - NERDTreeFind to reveal the node for the current buffer in the tree, see `|NERDTreeFind|`. This effectively merges the FindInNERDTree plugin (by Doug McInnes) into the script. ++ - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan Ritter and Rémi Prévost. ++ - truncate the root node if wider than the tree window. Thanks to Victor Gonzalez. ++ ++- bugfixes: ++ - really fix window state restoring ++ - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, jfilip1024, and Chris Chambers ++ ++### 4.0.0 ++- add a new programmable menu system (see `:help NERDTreeMenu`). ++- add new APIs to add menus/menu-items to the menu system as well as custom key mappings to the NERD tree buffer (see `:help NERDTreeAPI`). ++- removed the old API functions ++- added a mapping to maximize/restore the size of nerd tree window, thanks to Guillaume Duranceau for the patch. See :help NERDTree-A for details. ++- fix a bug where secondary nerd trees (netrw hijacked trees) and NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. ++- fix a bug where the script ignored directories whose name ended in a dot, thanks to Aggelos Orfanakos for the patch. ++- fix a bug when using the x mapping on the tree root, thanks to Bryan Venteicher for the patch. ++- fix a bug where the cursor position/window size of the nerd tree buffer wasnt being stored on closing the window, thanks to Richard Hart. ++- fix a bug where NERDTreeMirror would mirror the wrong tree ++ ++### 3.1.1 ++- fix a bug where a non-listed no-name buffer was getting created every time the tree windows was created, thanks to Derek Wyatt and owen1 ++- make `` behave the same as the `o` mapping ++- some helptag fixes in the doc, thanks @strull ++- fix a bug when using `:set nohidden` and opening a file where the previous buf was modified. Thanks @iElectric ++- other minor fixes ++ ++### 3.1.0 ++- New features: ++ - add mappings to open files in a vsplit, see `:help NERDTree-s` and `:help NERDTree-gs` ++ - make the statusline for the nerd tree window default to something hopefully more useful. See `:help 'NERDTreeStatusline'` ++- Bugfixes: ++ - make the hijack netrw functionality work when vim is started with `vim ` (thanks to Alf Mikula for the patch). ++ - fix a bug where the CWD wasnt being changed for some operations even when NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) ++ - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to @tpope) ++ - fix bugs when ignorecase was set (thanks to @nach) ++ - fix a bug with the relative path code (thanks to @nach) ++ - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks @nach) ++ ++ ++### 3.0.1 ++- Bugfixes: ++ - fix bugs with :NERDTreeToggle and :NERDTreeMirror when `'hidden'` was not set ++ - fix a bug where `:NERDTree ` would fail if `` was relative and didnt start with a `./` or `../` Thanks to James Kanze. ++ - make the `q` mapping work with secondary (`:e ` style) trees, thanks to @jamessan ++ - fix a bunch of small bugs with secondary trees ++- More insane refactoring. ++ ++### 3.0.0 ++- hijack netrw so that doing an `:edit ` will put a NERD tree in the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' ++- allow sharing of trees across tabs, see `:help :NERDTreeMirror` ++- remove "top" and "bottom" as valid settings for NERDTreeWinPos ++- change the `''` mapping to `'i'` ++- change the `'H'` mapping to `'I'` ++- lots of refactoring +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index fd19282..d7d428d 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.0.0' ++ return '5.1.1' + endfunction + + " SECTION: General Functions {{{1 diff --git a/tasks/preservim__nerdtree-1007/solution/solve.sh b/tasks/preservim__nerdtree-1007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1007/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/preservim__nerdtree-1007/task.toml b/tasks/preservim__nerdtree-1007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fece1571f5f4962095acf34368b3ea376f05c874 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1007" +description = "Update Changelog and create PR Template" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "33fe2fdf16a95c12e8284364c780ed405dbaad17" +reference = "https://github.com/preservim/nerdtree/pull/1007" +source_access = "auto" +built_at = "2026-11-16T16:10:02.473843+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3e0e06690582359dcdaabe637e1fd8ed37749cbbfe28bf88955b71814d735f95" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-27T05:28:46Z" +diff_format = "unified" +context_files = [ + ".github/PULL_REQUEST_TEMPLATE.md", + "CHANGELOG", + "CHANGELOG.md", + "autoload/nerdtree.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 444 +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:02.559866+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2f80bcd29f6d31360888e73363bf787a294e0183b15018c71788e1c1533ba52f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1007/tests/capture.py b/tasks/preservim__nerdtree-1007/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1007/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/preservim__nerdtree-1007/tests/instruction.md b/tasks/preservim__nerdtree-1007/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c6ee112c5a255953a249dd264fddb1937fcc6b7 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update Changelog and create PR Template + +## 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 `33fe2fdf16a9`. 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/preservim__nerdtree-1007/tests/oracle.patch b/tasks/preservim__nerdtree-1007/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d1194a8aaa0f0c8212044e580fa0308dcff1c9d0 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/tests/oracle.patch @@ -0,0 +1,473 @@ +diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md +new file mode 100644 +index 0000000..a60d1d4 +--- /dev/null ++++ b/.github/PULL_REQUEST_TEMPLATE.md +@@ -0,0 +1,22 @@ ++ ++### Description of Changes ++ ++Closes # ++ ++--- ++### New Version Info ++ ++- [ ] Derive a new version number. Increment the: ++ - [ ] `MAJOR` version when you make incompatible API changes, ++ - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and ++ - [ ] `PATCH` version when you make backwards-compatible bug fixes. ++- [ ] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) ++- [ ] Update the ChangeLog, following this format/example: ++ ``` ++ MAJOR.MINOR... ++ - **.PATCH**: PR Title (Author) #PR Number ++ ++ ### 5.1... ++ - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++ - **.0**: Too many changes for one patch... ++ ``` +diff --git a/CHANGELOG b/CHANGELOG +deleted file mode 100644 +index 6dac46d..0000000 +--- a/CHANGELOG ++++ /dev/null +@@ -1,179 +0,0 @@ +-Next +- - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) #759 +- - Update doc with already existing mapping variables (asnr) #699 +- - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) #696 +- - Correct NERDTreeIgnore pattern in doc (cntoplolicon) #648 +- - Remove empty segments when splitting path (sooth-sayer) #574 +- - Suppress autocmds less agressively (wincent) #578 #691 +- - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (josephfrazier) #676 +- - Don't touch @o and @h registers when rendering +- - Fix bug with files and directories with dollar signs (alegen) #649 +- - Reuse/reopen existing window trees where possible #244 +- - Remove NERDTree.previousBuf() +- - Change color of arrow (Leeiio) #630 +- - Improved a tip in README.markdown (ggicci) #628 +- - Shorten delete confimration of empty directory to 'y' (mikeperri) #530 +- - Fix API call to open directory tree in window (devm33) #533 +- - Change default arrows on non-Windows platforms (gwilk) #546 +- - Update to README - combine cd and git clone (zwhitchcox) #584 +- - Update to README - Tip: start NERDTree when vim starts (therealplato) #593 +- - Escape filename when moving an open buffer (zacharyvoase) #595 +- - Fixed incorrect :helptags command in README (curran) #619 +- - Fixed incomplete escaping of folder arrows (adityanatraj) #548 +- - Added NERDTreeCascadeSingleChildDir option (juanibiapina) #558 +- - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (SkylerLipthay) #231 +- - Fixed typo in README.markdown - :Helptags -> :helptags +- - Rename "primary" and "secondary" trees to "tab" and "window" trees. +- - Move a bunch of buffer level variables into the NERDTree and UI classes. +- - Display cascading dirs on one line to save vertical/horizontal space (@matt-gardner: brainstorming/testing) +- - Remove the old style UI - Remove 'NERDTreeDirArrows' option. +- - On windows default to + and ~ for expand/collapse directory symbols. +- - Lots more refactoring. Move a bunch of b: level vars into b:NERDTree and friends. +- +-5.0.0 +- - Refactor the code significantly: +- * Break the classes out into their own files. +- * Make the majority of the code OO - previously large parts were +- effectively a tangle of "global" methods. +- - Add an API to assign flags to nodes. This allows VCS plugins like +- https://github.com/Xuyuanp/nerdtree-git-plugin to exist. Thanks to +- Xuyuanp for helping design/test/build said API. +- - add 'scope' argument to the key map API see :help NERDTreeAddKeyMap() +- - add magic [[dir]] and [[file]] flags to NERDTreeIgnore +- - add support for custom path filters. See :help NERDTreeAddPathFilter() +- - add path listener API. See :help NERDTreePathListenerAPI. +- - expand the fs menu functionality to list file properties (PhilRunninger, +- apbarrero, JESii) +- - make bookmarks work with `~` home shortcuts (hiberabyss) +- - show OSX specific fsmenu options in regular vim on mac (evindor) +- - make dir arrow icons configurable (PickRelated) +- - optimise node sorting performance when opening large dirs (vtsang) +- - make the root note render prettier by truncating it at a path slash (gcmt) +- - remove NERDChristmasTree option - its always christmas now +- - add "cascade" open and closing for dirs containing only another single +- dir. See :help NERDTreeCascadeOpenSingleChildDir (pendulm) +- +- Many other fixes, doc updates and contributions from: +- actionshrimp +- SchDen +- egalpin +- cperl82 - many small fixes +- toiffel +- WoLpH +- handcraftedbits +- devmanhinton +- xiaodili +- zhangoose +- gastropoda +- mixvin +- alvan +- lucascaton +- kelaban +- shanesmith +- staeff +- pendulm +- stephenprater +- franksort +- agrussellknives +- AndrewRadev +- Twinside +- +-4.2.0 +- - Add NERDTreeDirArrows option to make the UI use pretty arrow chars +- instead of the old +~| chars to define the tree structure (sickill) +- - shift the syntax highlighting out into its own syntax file (gnap) +- - add some mac specific options to the filesystem menu - for macvim +- only (andersonfreitas) +- - Add NERDTreeMinimalUI option to remove some non functional parts of the +- nerdtree ui (camthompson) +- - tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the +- new behaviour (benjamingeiger) +- - if no name is given to :Bookmark, make it default to the name of the +- target file/dir (minyoung) +- - use 'file' completion when doing copying, create, and move +- operations (EvanDotPro) +- - lots of misc bug fixes (paddyoloughlin, sdewald, camthompson, Vitaly +- Bogdanov, AndrewRadev, mathias, scottstvnsn, kml, wycats, me RAWR!) +- +-4.1.0 +- features: +- - NERDTreeFind to reveal the node for the current buffer in the tree, +- see |NERDTreeFind|. This effectively merges the FindInNERDTree plugin (by +- Doug McInnes) into the script. +- - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan +- Ritter and Rémi Prévost. +- - truncate the root node if wider than the tree window. Thanks to Victor +- Gonzalez. +- +- bugfixes: +- - really fix window state restoring +- - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, +- jfilip1024, and Chris Chambers +- +-4.0.0 +- - add a new programmable menu system (see :help NERDTreeMenu). +- - add new APIs to add menus/menu-items to the menu system as well as +- custom key mappings to the NERD tree buffer (see :help NERDTreeAPI). +- - removed the old API functions +- - added a mapping to maximize/restore the size of nerd tree window, thanks +- to Guillaume Duranceau for the patch. See :help NERDTree-A for details. +- +- - fix a bug where secondary nerd trees (netrw hijacked trees) and +- NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. +- - fix a bug where the script ignored directories whose name ended in a dot, +- thanks to Aggelos Orfanakos for the patch. +- - fix a bug when using the x mapping on the tree root, thanks to Bryan +- Venteicher for the patch. +- - fix a bug where the cursor position/window size of the nerd tree buffer +- wasnt being stored on closing the window, thanks to Richard Hart. +- - fix a bug where NERDTreeMirror would mirror the wrong tree +- +-3.1.1 +- - fix a bug where a non-listed no-name buffer was getting created every +- time the tree windows was created, thanks to Derek Wyatt and owen1 +- - make behave the same as the 'o' mapping +- - some helptag fixes in the doc, thanks strull +- - fix a bug when using :set nohidden and opening a file where the previous +- buf was modified. Thanks iElectric +- - other minor fixes +- +-3.1.0 +- New features: +- - add mappings to open files in a vsplit, see :help NERDTree-s and :help +- NERDTree-gs +- - make the statusline for the nerd tree window default to something +- hopefully more useful. See :help 'NERDTreeStatusline' +- Bugfixes: +- - make the hijack netrw functionality work when vim is started with "vim +- " (thanks to Alf Mikula for the patch). +- - fix a bug where the CWD wasnt being changed for some operations even when +- NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) +- - add -bar to all the nerd tree :commands so they can chain with other +- :commands (thanks to tpope) +- - fix bugs when ignorecase was set (thanks to nach) +- - fix a bug with the relative path code (thanks to nach) +- - fix a bug where doing a :cd would cause :NERDTreeToggle to fail (thanks nach) +- +- +-3.0.1 +- Bugfixes: +- - fix bugs with :NERDTreeToggle and :NERDTreeMirror when 'hidden +- was not set +- - fix a bug where :NERDTree would fail if was relative and +- didnt start with a ./ or ../ Thanks to James Kanze. +- - make the q mapping work with secondary (:e style) trees, +- thanks to jamessan +- - fix a bunch of small bugs with secondary trees +- +- More insane refactoring. +- +-3.0.0 +- - hijack netrw so that doing an :edit will put a NERD tree in +- the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' +- - allow sharing of trees across tabs, see :help :NERDTreeMirror +- - remove "top" and "bottom" as valid settings for NERDTreeWinPos +- - change the '' mapping to 'i' +- - change the 'H' mapping to 'I' +- - lots of refactoring +diff --git a/CHANGELOG.md b/CHANGELOG.md +new file mode 100644 +index 0000000..ec6b35d +--- /dev/null ++++ b/CHANGELOG.md +@@ -0,0 +1,241 @@ ++# Change Log ++ ++### 5.1... ++- **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++- **`.0`**: Too many changes for one patch... ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 ++ - Add a "copy path to clipboard" menu option (@PhilRunninger) #1002 ++ - Enable root refresh on "vim ." a different way than #999. (@PhilRunninger) #1001 ++ - Fix refreshroot (@PhilRunninger) #999 ++ - Change version check to look for 703 not 730 (@vhalis) #994 ++ - Change minimum vim (@PhilRunninger) #991 ++ - Allow multi-character DirArrows (@PhilRunninger) #985 ++ - Remove redraw! while still clearing last message empty string. (@PhilRunninger) #979 ++ - fix _initChildren function value set to numChildrenCached error (@terryding77) #969 ++ - On Windows, do a case-insensitive comparison of paths. (@PhilRunninger) #967 ++ - Remove the "Please wait... DONE" messages. (@PhilRunninger) #966 ++ - Smarter delimiter default (@PhilRunninger) #963 ++ - Update directory .vimdc readme example (@spencerdcarlson) #961 ++ - Preview bookmarks (@PhilRunninger) #956 ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (@PhilRunninger) #955 ++ - Add an :EditBookmarks command to edit the bookmarks file (@PhilRunninger) #954 ++ - Before copying, turn off &shellslash. Restore after copy is finished. (@PhilRunninger) #952 ++ - Set a maximum window size when zooming. (@PhilRunninger) #950 ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (@PhilRunninger) #949 ++ - Escape a backslash so it can be used in a key mapping. (@PhilRunninger) #948 ++ - Add a NERDTreeMinimalMenu feature (@tuzz) #938 ++ - fixed root path error for windows (@zcodes) #935 ++ - Restore getDirChildren for use in nerdtree-project-plugin. (@PhilRunninger) #929 ++ - Document NERDTreeNodeDelimiter #912 (@PhilRunninger) #926 ++ - Allow modification of menu keybindings (@Leandros) #923 ++ - Add two more disqualifications for isCascadable(). (@PhilRunninger) #914 ++ - Allow highlighting more than one flag. (@kristijanhusak) #908 ++ - Support sorting files and directories by modification time. (@PhilRunninger) #901 ++ - Parse . and .. from path string with trailing slash. (@PhilRunninger) #899 ++ - Force sort to recalculate the cached sortKey. (@PhilRunninger) #898 ++ - Add NERDTreeRefreshRoot command (@wgfm) #897 ++ - Call Resolve on the file's path when calling :NERDTreeFind. (@PhilRunninger) #896 ++ - Catch all errors, not just NERDTree errors. (@PhilRunninger) #894 ++ - Fix typo in help file (@lvoisin) #892 ++ - Make NERDTreeCreator set the `'nolist'` option (@lifecrisis) #889 ++ - Refresh buffers after `m`, `m` operation on a folder (@PhilRunninger) #888 ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (@PhilRunninger) #887 ++ - Fix the / motions, which currently fail with cascades (@lifecrisis) #886 ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (@lifecrisis) #882 ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (@PhilRunninger) #878 ++ - Use tabnext instead of gt to allow users to remap gt. (@PhilRunninger) #877 ++ - Do a case sensitive comparison of new/existing buffers. (@PhilRunninger) #875 ++ - Fix opening sub-directories that have commas in their name. (@PhilRunninger) #873 ++ - Add new command to open NERDTree in the root of a VCS repository. (@PhilRunninger) #872 ++ - Make sure the path to the bookmarks file exists before writing it. (@PhilRunninger) #871 ++ - Unzoom NERDTree when opening a file (@PhilRunninger) #870 ++ - Support unusual characters in file and directory names (@PhilRunninger) #868 ++ - Reword renamed-buffer prompt to be more clear (@aflock) #867 ++ - Default to placing cursor on root when closing bookmark table (@lifecrisis) #866 ++ - Fix issues with sorting of nodes (@PhilRunninger) #856 ++ - Better OSX detection (@bubba-h57) #853 ++ - Bugfix - ensure keymaps dictionary exists before using it (@mnussbaum) #852 ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (@mnussbaum) #851 ++ - Add code to sort mappings in quickhelp (@lifecrisis) #849 ++ - Use ":clearjumps" in new NERDTree windows (@lifecrisis) #844 ++ - Like m-c did before, create parent directories if needed on m-m. (@PhilRunninger) #840 ++ - BUGFIX: Repair a problem with the `'u'` mapping. (@lifecrisis) #838 ++ - Make the NERDTree buffer writable when rendering it. (@PhilRunninger) #837 ++ - Code cleanup: Remove unsupported bookmark table mappings (@lifecrisis) #835 ++ - Replace strcharpart() with substitute() for backward compatibility (@bravestarr) #834 ++ - Fixed error `unknown function strcharpart` for older versions of Vim (@hav4ik) #833 ++ - Clear output when NERDTree menu is aborted (@lifecrisis) #832 ++ - Display a path with multi-byte characters correctly when it is truncated (@bravestarr) #830 ++ - Support revealing file and executing file with xdg-open for Linux (@ngnmhieu) #824 ++ - If node isn't open, count children on disk before deleting. (@PhilRunninger) #822 ++ - Add new variable g:NERDTreeRemoveFileCmd (@kutsan) #816 ++ - Use a better check for existence of the NERDTree buffer. (@PhilRunninger) #814 ++ - Fix focussing previous buffer when closing NERDTree (@mrubli) #801 ++ - Update the docs for "NERDTreeStatusline" (@lifecrisis) #796 ++ - BUGFIX: Unstable behavior in the "getPath()" method (@lifecrisis) #795 ++ - Revert the bugfix from pull request #785 (@lifecrisis) #794 ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (@lifecrisis) #786 ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (@lifecrisis) #785 ++ - Add modelines (@lifecrisis) #782 ++ - Change the type of completion used by NERDTreeFind (@lifecrisis) #781 ++ - change NERDTreeFind with args (@zhenyangze) #778 ++ - Style Choice: Using confirm() when deleting a bookmark (@lifecrisis) #777 ++ - remove useless substitute when `file =~# "/$"` (@skyblueee) #773 ++ - remove useless removeLeadingSpaces in _stripMarkup (@skyblueee) #772 ++ - Make the "o" mapping consistent with "x" (@lifecrisis) #769 ++ - Fix a problem with the "x" handler (@lifecrisis) #768 ++ - Clean up the handler for the "x" mapping (@lifecrisis) #767 ++ - Revert change to tab opening method (@lifecrisis) #766 ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (@lifecrisis) #765 ++ - Fix broken "t" and "T" mappings, tabs now open at end (@lifecrisis) #759 ++ - Update doc with already existing mapping variables (@asnr) #699 ++ - Fix the broken g:NERDTreeBookmarksSort setting (@lifecrisis) #696 ++ - Correct NERDTreeIgnore pattern in doc (@cntoplolicon) #648 ++ - Remove empty segments when splitting path (@sooth-sayer) #574 ++ - Suppress autocmds less agressively (@wincent) #578 #691 ++ - Add an Issues template to ask for more info initially. ++ - Fix markdown headers in readme (@josephfrazier) #676 ++ - Don't touch @o and @h registers when rendering ++ - Fix bug with files and directories with dollar signs (@alegen) #649 ++ - Reuse/reopen existing window trees where possible #244 ++ - Remove NERDTree.previousBuf() ++ - Change color of arrow (@Leeiio) #630 ++ - Improved a tip in README.markdown (@ggicci) #628 ++ - Shorten delete confimration of empty directory to `y` (@mikeperri) #530 ++ - Fix API call to open directory tree in window (@devm33) #533 ++ - Change default arrows on non-Windows platforms (@gwilk) #546 ++ - Update to README - combine cd and git clone (@zwhitchcox) #584 ++ - Update to README - Tip: start NERDTree when vim starts (@therealplato) #593 ++ - Escape filename when moving an open buffer (@zacharyvoase) #595 ++ - Fixed incorrect :helptags command in README (@curran) #619 ++ - Fixed incomplete escaping of folder arrows (@adityanatraj) #548 ++ - Added NERDTreeCascadeSingleChildDir option (@juanibiapina) #558 ++ - Replace strchars() with backward compatible workaround. ++ - Add support for copy command in Windows (@SkylerLipthay) #231 ++ - Fixed typo in README.markdown - :Helptags -> :helptags ++ - Rename "primary" and "secondary" trees to "tab" and "window" trees. ++ - Move a bunch of buffer level variables into the NERDTree and UI classes. ++ - Display cascading dirs on one line to save vertical/horizontal space (@matt-gardner: brainstorming/testing) ++ - Remove the old style UI - Remove `NERDTreeDirArrows` option. ++ - On windows default to + and ~ for expand/collapse directory symbols. ++ - Lots more refactoring. Move a bunch of b: level vars into b:NERDTree and friends. ++ ++### 5.0.0 ++- Refactor the code significantly: ++ * Break the classes out into their own files. ++ * Make the majority of the code OO - previously large parts were effectively a tangle of "global" methods. ++- Add an API to assign flags to nodes. This allows VCS plugins like https://github.com/Xuyuanp/nerdtree-git-plugin to exist. Thanks to @Xuyuanp for helping design/test/build said API. ++- add `scope` argument to the key map API see :help NERDTreeAddKeyMap() ++- add magic [[dir]] and [[file]] flags to NERDTreeIgnore ++- add support for custom path filters. See :help NERDTreeAddPathFilter() ++- add path listener API. See :help NERDTreePathListenerAPI. ++- expand the fs menu functionality to list file properties (@PhilRunninger, @apbarrero, @JESii) ++- make bookmarks work with `~` home shortcuts (@hiberabyss) ++- show OSX specific fsmenu options in regular vim on mac (@evindor) ++- make dir arrow icons configurable (@PickRelated) ++- optimise node sorting performance when opening large dirs (@vtsang) ++- make the root note render prettier by truncating it at a path slash (@gcmt) ++- remove NERDChristmasTree option - its always christmas now ++- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (@pendulm) ++- Many other fixes, doc updates and contributions from: ++ - @actionshrimp ++ - @SchDen ++ - @egalpin ++ - @cperl82 - many small fixes ++ - @toiffel ++ - @WoLpH ++ - @handcraftedbits ++ - @devmanhinton ++ - @xiaodili ++ - @zhangoose ++ - @gastropoda ++ - @mixvin ++ - @alvan ++ - @lucascaton ++ - @kelaban ++ - @shanesmith ++ - @staeff ++ - @pendulm ++ - @stephenprater ++ - @franksort ++ - @agrussellknives ++ - @AndrewRadev ++ - @Twinside ++ ++### 4.2.0 ++- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (@sickill) ++- shift the syntax highlighting out into its own syntax file (@gnap) ++- add some mac specific options to the filesystem menu - for macvim only (@andersonfreitas) ++- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (@camthompson) ++- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (@benjamingeiger) ++- if no name is given to :Bookmark, make it default to the name of the target file/dir (@minyoung) ++- use `file` completion when doing copying, create, and move operations (@EvanDotPro) ++- lots of misc bug fixes from: ++ - @paddyoloughlin ++ - @sdewald ++ - @camthompson ++ - @Vitaly ++ - @Bogdanov ++ - @AndrewRadev ++ - @mathias ++ - @scottstvnsn ++ - @kml ++ - @wycats ++ - me RAWR! ++ ++### 4.1.0 ++- features: ++ - NERDTreeFind to reveal the node for the current buffer in the tree, see `|NERDTreeFind|`. This effectively merges the FindInNERDTree plugin (by Doug McInnes) into the script. ++ - make NERDTreeQuitOnOpen apply to the t/T keymaps too. Thanks to Stefan Ritter and Rémi Prévost. ++ - truncate the root node if wider than the tree window. Thanks to Victor Gonzalez. ++ ++- bugfixes: ++ - really fix window state restoring ++ - fix some win32 path escaping issues. Thanks to Stephan Baumeister, Ricky, jfilip1024, and Chris Chambers ++ ++### 4.0.0 ++- add a new programmable menu system (see `:help NERDTreeMenu`). ++- add new APIs to add menus/menu-items to the menu system as well as custom key mappings to the NERD tree buffer (see `:help NERDTreeAPI`). ++- removed the old API functions ++- added a mapping to maximize/restore the size of nerd tree window, thanks to Guillaume Duranceau for the patch. See :help NERDTree-A for details. ++- fix a bug where secondary nerd trees (netrw hijacked trees) and NERDTreeQuitOnOpen didnt play nicely, thanks to Curtis Harvey. ++- fix a bug where the script ignored directories whose name ended in a dot, thanks to Aggelos Orfanakos for the patch. ++- fix a bug when using the x mapping on the tree root, thanks to Bryan Venteicher for the patch. ++- fix a bug where the cursor position/window size of the nerd tree buffer wasnt being stored on closing the window, thanks to Richard Hart. ++- fix a bug where NERDTreeMirror would mirror the wrong tree ++ ++### 3.1.1 ++- fix a bug where a non-listed no-name buffer was getting created every time the tree windows was created, thanks to Derek Wyatt and owen1 ++- make `` behave the same as the `o` mapping ++- some helptag fixes in the doc, thanks @strull ++- fix a bug when using `:set nohidden` and opening a file where the previous buf was modified. Thanks @iElectric ++- other minor fixes ++ ++### 3.1.0 ++- New features: ++ - add mappings to open files in a vsplit, see `:help NERDTree-s` and `:help NERDTree-gs` ++ - make the statusline for the nerd tree window default to something hopefully more useful. See `:help 'NERDTreeStatusline'` ++- Bugfixes: ++ - make the hijack netrw functionality work when vim is started with `vim ` (thanks to Alf Mikula for the patch). ++ - fix a bug where the CWD wasnt being changed for some operations even when NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) ++ - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to @tpope) ++ - fix bugs when ignorecase was set (thanks to @nach) ++ - fix a bug with the relative path code (thanks to @nach) ++ - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks @nach) ++ ++ ++### 3.0.1 ++- Bugfixes: ++ - fix bugs with :NERDTreeToggle and :NERDTreeMirror when `'hidden'` was not set ++ - fix a bug where `:NERDTree ` would fail if `` was relative and didnt start with a `./` or `../` Thanks to James Kanze. ++ - make the `q` mapping work with secondary (`:e ` style) trees, thanks to @jamessan ++ - fix a bunch of small bugs with secondary trees ++- More insane refactoring. ++ ++### 3.0.0 ++- hijack netrw so that doing an `:edit ` will put a NERD tree in the window rather than a netrw browser. See :help 'NERDTreeHijackNetrw' ++- allow sharing of trees across tabs, see `:help :NERDTreeMirror` ++- remove "top" and "bottom" as valid settings for NERDTreeWinPos ++- change the `''` mapping to `'i'` ++- change the `'H'` mapping to `'I'` ++- lots of refactoring +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index fd19282..d7d428d 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.0.0' ++ return '5.1.1' + endfunction + + " SECTION: General Functions {{{1 diff --git a/tasks/preservim__nerdtree-1007/tests/test.sh b/tasks/preservim__nerdtree-1007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..01fbec4ed5278e3d4eb9d8c434161bcf6ffb6d06 --- /dev/null +++ b/tasks/preservim__nerdtree-1007/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 33fe2fdf16a95c12e8284364c780ed405dbaad17 > "$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/preservim__nerdtree-1007/tests/verifier.py b/tasks/preservim__nerdtree-1007/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1007/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/preservim__nerdtree-1008/environment/Dockerfile b/tasks/preservim__nerdtree-1008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66baa9c6df4bc2ecbc0a6589e4babca6483d4d8c --- /dev/null +++ b/tasks/preservim__nerdtree-1008/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 347a58b0b0276958ccc5b2e7cf8edd9c9923906c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 347a58b0b0276958ccc5b2e7cf8edd9c9923906c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 347a58b0b0276958ccc5b2e7cf8edd9c9923906c \ + && 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/preservim__nerdtree-1008/instruction.md b/tasks/preservim__nerdtree-1008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..189c0ce0bdb0586108db3d5c95afabe5f7744119 --- /dev/null +++ b/tasks/preservim__nerdtree-1008/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** Fix NERDTree opening with the wrong size. + +## Description + + +### Description of Changes + + + +There were two commands that seemed to be causing the NERDTree window to +open in exactly half the screen width. They are: + +- silent! execute 'edit ' . t:NERDTreeBufName in _createTreeWin() +- setlocal nobuflisted in _setCommonBufOptions() + +These commands were reseting the width of NERDTree. The solution I chose +was to resize the window after creating the new window, and then to set +winfixwidth before setting the other common buffer options. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes, + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and + - [x] `PATCH` version when you make backwards-compatible bug fixes. +- [x] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) +- [x] Update the ChangeLog, following this format/example: + ``` + MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... + - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `347a58b0b027`. 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/preservim__nerdtree-1008/solution/patch.diff b/tasks/preservim__nerdtree-1008/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a12bfe995f2cbfedcbc57dba38f036fe68ab214b --- /dev/null +++ b/tasks/preservim__nerdtree-1008/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ec6b35d..6b98977 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + ### 5.1... ++- **`.2`**: Fix NERDTree opening with the wrong size. (@PhilRunninger) #1008 + - **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **`.0`**: Too many changes for one patch... + - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index d7d428d..845f920 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.1.1' ++ return '5.1.2' + endfunction + + " SECTION: General Functions {{{1 +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 5eac168..987e02e 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -189,18 +189,20 @@ function! s:Creator._createTreeWin() + let t:NERDTreeBufName = self._nextBufferName() + silent! execute l:splitLocation . 'vertical ' . l:splitSize . ' new' + silent! execute 'edit ' . t:NERDTreeBufName ++ silent! execute 'vertical resize '. l:splitSize + else + silent! execute l:splitLocation . 'vertical ' . l:splitSize . ' split' + silent! execute 'buffer ' . t:NERDTreeBufName + endif + ++ setlocal winfixwidth ++ + call self._setCommonBufOptions() + + if has('patch-7.4.1925') + clearjumps + endif + +- setlocal winfixwidth + endfunction + + " FUNCTION: s:Creator._isBufHidden(nr) {{{1 diff --git a/tasks/preservim__nerdtree-1008/solution/solve.sh b/tasks/preservim__nerdtree-1008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1008/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/preservim__nerdtree-1008/task.toml b/tasks/preservim__nerdtree-1008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f89b8d1062ec142ab534ae98da9e31585db11e5d --- /dev/null +++ b/tasks/preservim__nerdtree-1008/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1008" +description = "Fix NERDTree opening with the wrong size." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "347a58b0b0276958ccc5b2e7cf8edd9c9923906c" +reference = "https://github.com/preservim/nerdtree/pull/1008" +source_access = "auto" +built_at = "2026-11-16T16:10:02.471738+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c678d56a651949214723de46cc5f3d882bd51df1a9784e5e7f3e51d4d2ebf834" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-27T05:34:11Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", + "lib/nerdtree/creator.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +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:02.560410+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aaf3cf0c8e519c9a9eeeadae2d1473a3334805abeb37f306f49d1daeda3c5fc0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1008/tests/capture.py b/tasks/preservim__nerdtree-1008/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1008/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/preservim__nerdtree-1008/tests/instruction.md b/tasks/preservim__nerdtree-1008/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..189c0ce0bdb0586108db3d5c95afabe5f7744119 --- /dev/null +++ b/tasks/preservim__nerdtree-1008/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** Fix NERDTree opening with the wrong size. + +## Description + + +### Description of Changes + + + +There were two commands that seemed to be causing the NERDTree window to +open in exactly half the screen width. They are: + +- silent! execute 'edit ' . t:NERDTreeBufName in _createTreeWin() +- setlocal nobuflisted in _setCommonBufOptions() + +These commands were reseting the width of NERDTree. The solution I chose +was to resize the window after creating the new window, and then to set +winfixwidth before setting the other common buffer options. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes, + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and + - [x] `PATCH` version when you make backwards-compatible bug fixes. +- [x] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) +- [x] Update the ChangeLog, following this format/example: + ``` + MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... + - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `347a58b0b027`. 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/preservim__nerdtree-1008/tests/oracle.patch b/tasks/preservim__nerdtree-1008/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a12bfe995f2cbfedcbc57dba38f036fe68ab214b --- /dev/null +++ b/tasks/preservim__nerdtree-1008/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ec6b35d..6b98977 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + ### 5.1... ++- **`.2`**: Fix NERDTree opening with the wrong size. (@PhilRunninger) #1008 + - **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **`.0`**: Too many changes for one patch... + - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index d7d428d..845f920 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.1.1' ++ return '5.1.2' + endfunction + + " SECTION: General Functions {{{1 +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 5eac168..987e02e 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -189,18 +189,20 @@ function! s:Creator._createTreeWin() + let t:NERDTreeBufName = self._nextBufferName() + silent! execute l:splitLocation . 'vertical ' . l:splitSize . ' new' + silent! execute 'edit ' . t:NERDTreeBufName ++ silent! execute 'vertical resize '. l:splitSize + else + silent! execute l:splitLocation . 'vertical ' . l:splitSize . ' split' + silent! execute 'buffer ' . t:NERDTreeBufName + endif + ++ setlocal winfixwidth ++ + call self._setCommonBufOptions() + + if has('patch-7.4.1925') + clearjumps + endif + +- setlocal winfixwidth + endfunction + + " FUNCTION: s:Creator._isBufHidden(nr) {{{1 diff --git a/tasks/preservim__nerdtree-1008/tests/test.sh b/tasks/preservim__nerdtree-1008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2f7281702609d688490db1416af641a6bc0b0751 --- /dev/null +++ b/tasks/preservim__nerdtree-1008/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 347a58b0b0276958ccc5b2e7cf8edd9c9923906c > "$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/preservim__nerdtree-1008/tests/verifier.py b/tasks/preservim__nerdtree-1008/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1008/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/preservim__nerdtree-1009/environment/Dockerfile b/tasks/preservim__nerdtree-1009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bc5135884ce94f9d8c90af61a6f50b7eba775154 --- /dev/null +++ b/tasks/preservim__nerdtree-1009/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2cbc76bbfd807f022031f8c789f66d105d0a5d0b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2cbc76bbfd807f022031f8c789f66d105d0a5d0b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2cbc76bbfd807f022031f8c789f66d105d0a5d0b \ + && 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/preservim__nerdtree-1009/instruction.md b/tasks/preservim__nerdtree-1009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e6df59f07035c701a3179fd3f6d57858e4574f5 --- /dev/null +++ b/tasks/preservim__nerdtree-1009/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Remove @mentions from PR template and change log. They weren't working. + +## Description + + +### Description of Changes + +Closes # + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes, + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and + - [x] `PATCH` version when you make backwards-compatible bug fixes. +- [x] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) +- [x] Update the ChangeLog, following this format/example: + ``` + MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... + - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2cbc76bbfd80`. 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/preservim__nerdtree-1009/solution/patch.diff b/tasks/preservim__nerdtree-1009/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c4a1ef36d73832cbf2035574c976b5cee0a69a8e --- /dev/null +++ b/tasks/preservim__nerdtree-1009/solution/patch.diff @@ -0,0 +1,321 @@ +diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md +index a60d1d4..1a2765e 100644 +--- a/.github/PULL_REQUEST_TEMPLATE.md ++++ b/.github/PULL_REQUEST_TEMPLATE.md +@@ -17,6 +17,6 @@ Closes # + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... +- - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++ - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6b98977..e207f2c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,118 +1,119 @@ + # Change Log + + ### 5.1... +-- **`.2`**: Fix NERDTree opening with the wrong size. (@PhilRunninger) #1008 +-- **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++- **`.3`**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) #1009 ++- **`.2`**: Fix NERDTree opening with the wrong size. (PhilRunninger) #1008 ++- **`.1`**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **`.0`**: Too many changes for one patch... +- - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 +- - Add a "copy path to clipboard" menu option (@PhilRunninger) #1002 +- - Enable root refresh on "vim ." a different way than #999. (@PhilRunninger) #1001 +- - Fix refreshroot (@PhilRunninger) #999 +- - Change version check to look for 703 not 730 (@vhalis) #994 +- - Change minimum vim (@PhilRunninger) #991 +- - Allow multi-character DirArrows (@PhilRunninger) #985 +- - Remove redraw! while still clearing last message empty string. (@PhilRunninger) #979 +- - fix _initChildren function value set to numChildrenCached error (@terryding77) #969 +- - On Windows, do a case-insensitive comparison of paths. (@PhilRunninger) #967 +- - Remove the "Please wait... DONE" messages. (@PhilRunninger) #966 +- - Smarter delimiter default (@PhilRunninger) #963 +- - Update directory .vimdc readme example (@spencerdcarlson) #961 +- - Preview bookmarks (@PhilRunninger) #956 +- - Add new value to NERDTreeQuitOnOpen to close bookmark table (@PhilRunninger) #955 +- - Add an :EditBookmarks command to edit the bookmarks file (@PhilRunninger) #954 +- - Before copying, turn off &shellslash. Restore after copy is finished. (@PhilRunninger) #952 +- - Set a maximum window size when zooming. (@PhilRunninger) #950 +- - Confirm the wipeout of a unsaved buffer whose file has been renamed. (@PhilRunninger) #949 +- - Escape a backslash so it can be used in a key mapping. (@PhilRunninger) #948 +- - Add a NERDTreeMinimalMenu feature (@tuzz) #938 +- - fixed root path error for windows (@zcodes) #935 +- - Restore getDirChildren for use in nerdtree-project-plugin. (@PhilRunninger) #929 +- - Document NERDTreeNodeDelimiter #912 (@PhilRunninger) #926 +- - Allow modification of menu keybindings (@Leandros) #923 +- - Add two more disqualifications for isCascadable(). (@PhilRunninger) #914 +- - Allow highlighting more than one flag. (@kristijanhusak) #908 +- - Support sorting files and directories by modification time. (@PhilRunninger) #901 +- - Parse . and .. from path string with trailing slash. (@PhilRunninger) #899 +- - Force sort to recalculate the cached sortKey. (@PhilRunninger) #898 +- - Add NERDTreeRefreshRoot command (@wgfm) #897 +- - Call Resolve on the file's path when calling :NERDTreeFind. (@PhilRunninger) #896 +- - Catch all errors, not just NERDTree errors. (@PhilRunninger) #894 +- - Fix typo in help file (@lvoisin) #892 +- - Make NERDTreeCreator set the `'nolist'` option (@lifecrisis) #889 +- - Refresh buffers after `m`, `m` operation on a folder (@PhilRunninger) #888 +- - Use a better arg for FINDSTR when using the m,l command in Windows. (@PhilRunninger) #887 +- - Fix the / motions, which currently fail with cascades (@lifecrisis) #886 +- - Function "s:UI.getLineNum()" doesn't always work on cascades. (@lifecrisis) #882 +- - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (@PhilRunninger) #878 +- - Use tabnext instead of gt to allow users to remap gt. (@PhilRunninger) #877 +- - Do a case sensitive comparison of new/existing buffers. (@PhilRunninger) #875 +- - Fix opening sub-directories that have commas in their name. (@PhilRunninger) #873 +- - Add new command to open NERDTree in the root of a VCS repository. (@PhilRunninger) #872 +- - Make sure the path to the bookmarks file exists before writing it. (@PhilRunninger) #871 +- - Unzoom NERDTree when opening a file (@PhilRunninger) #870 +- - Support unusual characters in file and directory names (@PhilRunninger) #868 +- - Reword renamed-buffer prompt to be more clear (@aflock) #867 +- - Default to placing cursor on root when closing bookmark table (@lifecrisis) #866 +- - Fix issues with sorting of nodes (@PhilRunninger) #856 +- - Better OSX detection (@bubba-h57) #853 +- - Bugfix - ensure keymaps dictionary exists before using it (@mnussbaum) #852 +- - Decrease startup-time by avoiding linear-time iteration over key mappings (@mnussbaum) #851 +- - Add code to sort mappings in quickhelp (@lifecrisis) #849 +- - Use ":clearjumps" in new NERDTree windows (@lifecrisis) #844 +- - Like m-c did before, create parent directories if needed on m-m. (@PhilRunninger) #840 +- - BUGFIX: Repair a problem with the `'u'` mapping. (@lifecrisis) #838 +- - Make the NERDTree buffer writable when rendering it. (@PhilRunninger) #837 +- - Code cleanup: Remove unsupported bookmark table mappings (@lifecrisis) #835 +- - Replace strcharpart() with substitute() for backward compatibility (@bravestarr) #834 +- - Fixed error `unknown function strcharpart` for older versions of Vim (@hav4ik) #833 +- - Clear output when NERDTree menu is aborted (@lifecrisis) #832 +- - Display a path with multi-byte characters correctly when it is truncated (@bravestarr) #830 +- - Support revealing file and executing file with xdg-open for Linux (@ngnmhieu) #824 +- - If node isn't open, count children on disk before deleting. (@PhilRunninger) #822 +- - Add new variable g:NERDTreeRemoveFileCmd (@kutsan) #816 +- - Use a better check for existence of the NERDTree buffer. (@PhilRunninger) #814 +- - Fix focussing previous buffer when closing NERDTree (@mrubli) #801 +- - Update the docs for "NERDTreeStatusline" (@lifecrisis) #796 +- - BUGFIX: Unstable behavior in the "getPath()" method (@lifecrisis) #795 +- - Revert the bugfix from pull request #785 (@lifecrisis) #794 +- - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (@lifecrisis) #786 +- - BUGFIX: Allow ":NERDTreeFind" to reveal new files (@lifecrisis) #785 +- - Add modelines (@lifecrisis) #782 +- - Change the type of completion used by NERDTreeFind (@lifecrisis) #781 +- - change NERDTreeFind with args (@zhenyangze) #778 +- - Style Choice: Using confirm() when deleting a bookmark (@lifecrisis) #777 +- - remove useless substitute when `file =~# "/$"` (@skyblueee) #773 +- - remove useless removeLeadingSpaces in _stripMarkup (@skyblueee) #772 +- - Make the "o" mapping consistent with "x" (@lifecrisis) #769 +- - Fix a problem with the "x" handler (@lifecrisis) #768 +- - Clean up the handler for the "x" mapping (@lifecrisis) #767 +- - Revert change to tab opening method (@lifecrisis) #766 +- - BUGFIX: Add back support for "b:NERDTreeRoot" (@lifecrisis) #765 +- - Fix broken "t" and "T" mappings, tabs now open at end (@lifecrisis) #759 +- - Update doc with already existing mapping variables (@asnr) #699 +- - Fix the broken g:NERDTreeBookmarksSort setting (@lifecrisis) #696 +- - Correct NERDTreeIgnore pattern in doc (@cntoplolicon) #648 +- - Remove empty segments when splitting path (@sooth-sayer) #574 +- - Suppress autocmds less agressively (@wincent) #578 #691 ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) #1005 ++ - Add a "copy path to clipboard" menu option (PhilRunninger) #1002 ++ - Enable root refresh on "vim ." a different way than #999. (PhilRunninger) #1001 ++ - Fix refreshroot (PhilRunninger) #999 ++ - Change version check to look for 703 not 730 (vhalis) #994 ++ - Change minimum vim (PhilRunninger) #991 ++ - Allow multi-character DirArrows (PhilRunninger) #985 ++ - Remove redraw! while still clearing last message empty string. (PhilRunninger) #979 ++ - fix _initChildren function value set to numChildrenCached error (terryding77) #969 ++ - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) #967 ++ - Remove the "Please wait... DONE" messages. (PhilRunninger) #966 ++ - Smarter delimiter default (PhilRunninger) #963 ++ - Update directory .vimdc readme example (spencerdcarlson) #961 ++ - Preview bookmarks (PhilRunninger) #956 ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) #955 ++ - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) #954 ++ - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) #952 ++ - Set a maximum window size when zooming. (PhilRunninger) #950 ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) #949 ++ - Escape a backslash so it can be used in a key mapping. (PhilRunninger) #948 ++ - Add a NERDTreeMinimalMenu feature (tuzz) #938 ++ - fixed root path error for windows (zcodes) #935 ++ - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) #929 ++ - Document NERDTreeNodeDelimiter #912 (PhilRunninger) #926 ++ - Allow modification of menu keybindings (Leandros) #923 ++ - Add two more disqualifications for isCascadable(). (PhilRunninger) #914 ++ - Allow highlighting more than one flag. (kristijanhusak) #908 ++ - Support sorting files and directories by modification time. (PhilRunninger) #901 ++ - Parse . and .. from path string with trailing slash. (PhilRunninger) #899 ++ - Force sort to recalculate the cached sortKey. (PhilRunninger) #898 ++ - Add NERDTreeRefreshRoot command (wgfm) #897 ++ - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) #896 ++ - Catch all errors, not just NERDTree errors. (PhilRunninger) #894 ++ - Fix typo in help file (lvoisin) #892 ++ - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) #889 ++ - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) #888 ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) #887 ++ - Fix the / motions, which currently fail with cascades (lifecrisis) #886 ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) #882 ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) #878 ++ - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) #877 ++ - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) #875 ++ - Fix opening sub-directories that have commas in their name. (PhilRunninger) #873 ++ - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) #872 ++ - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) #871 ++ - Unzoom NERDTree when opening a file (PhilRunninger) #870 ++ - Support unusual characters in file and directory names (PhilRunninger) #868 ++ - Reword renamed-buffer prompt to be more clear (aflock) #867 ++ - Default to placing cursor on root when closing bookmark table (lifecrisis) #866 ++ - Fix issues with sorting of nodes (PhilRunninger) #856 ++ - Better OSX detection (bubba-h57) #853 ++ - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) #852 ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) #851 ++ - Add code to sort mappings in quickhelp (lifecrisis) #849 ++ - Use ":clearjumps" in new NERDTree windows (lifecrisis) #844 ++ - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) #840 ++ - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) #838 ++ - Make the NERDTree buffer writable when rendering it. (PhilRunninger) #837 ++ - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) #835 ++ - Replace strcharpart() with substitute() for backward compatibility (bravestarr) #834 ++ - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) #833 ++ - Clear output when NERDTree menu is aborted (lifecrisis) #832 ++ - Display a path with multi-byte characters correctly when it is truncated (bravestarr) #830 ++ - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) #824 ++ - If node isn't open, count children on disk before deleting. (PhilRunninger) #822 ++ - Add new variable g:NERDTreeRemoveFileCmd (kutsan) #816 ++ - Use a better check for existence of the NERDTree buffer. (PhilRunninger) #814 ++ - Fix focussing previous buffer when closing NERDTree (mrubli) #801 ++ - Update the docs for "NERDTreeStatusline" (lifecrisis) #796 ++ - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) #795 ++ - Revert the bugfix from pull request #785 (lifecrisis) #794 ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) #786 ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) #785 ++ - Add modelines (lifecrisis) #782 ++ - Change the type of completion used by NERDTreeFind (lifecrisis) #781 ++ - change NERDTreeFind with args (zhenyangze) #778 ++ - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) #777 ++ - remove useless substitute when `file =~# "/$"` (skyblueee) #773 ++ - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) #772 ++ - Make the "o" mapping consistent with "x" (lifecrisis) #769 ++ - Fix a problem with the "x" handler (lifecrisis) #768 ++ - Clean up the handler for the "x" mapping (lifecrisis) #767 ++ - Revert change to tab opening method (lifecrisis) #766 ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) #765 ++ - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) #759 ++ - Update doc with already existing mapping variables (asnr) #699 ++ - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) #696 ++ - Correct NERDTreeIgnore pattern in doc (cntoplolicon) #648 ++ - Remove empty segments when splitting path (sooth-sayer) #574 ++ - Suppress autocmds less agressively (wincent) #578 #691 + - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (@josephfrazier) #676 ++ - Fix markdown headers in readme (josephfrazier) #676 + - Don't touch @o and @h registers when rendering +- - Fix bug with files and directories with dollar signs (@alegen) #649 ++ - Fix bug with files and directories with dollar signs (alegen) #649 + - Reuse/reopen existing window trees where possible #244 + - Remove NERDTree.previousBuf() +- - Change color of arrow (@Leeiio) #630 +- - Improved a tip in README.markdown (@ggicci) #628 +- - Shorten delete confimration of empty directory to `y` (@mikeperri) #530 +- - Fix API call to open directory tree in window (@devm33) #533 +- - Change default arrows on non-Windows platforms (@gwilk) #546 +- - Update to README - combine cd and git clone (@zwhitchcox) #584 +- - Update to README - Tip: start NERDTree when vim starts (@therealplato) #593 +- - Escape filename when moving an open buffer (@zacharyvoase) #595 +- - Fixed incorrect :helptags command in README (@curran) #619 +- - Fixed incomplete escaping of folder arrows (@adityanatraj) #548 +- - Added NERDTreeCascadeSingleChildDir option (@juanibiapina) #558 ++ - Change color of arrow (Leeiio) #630 ++ - Improved a tip in README.markdown (ggicci) #628 ++ - Shorten delete confimration of empty directory to `y` (mikeperri) #530 ++ - Fix API call to open directory tree in window (devm33) #533 ++ - Change default arrows on non-Windows platforms (gwilk) #546 ++ - Update to README - combine cd and git clone (zwhitchcox) #584 ++ - Update to README - Tip: start NERDTree when vim starts (therealplato) #593 ++ - Escape filename when moving an open buffer (zacharyvoase) #595 ++ - Fixed incorrect :helptags command in README (curran) #619 ++ - Fixed incomplete escaping of folder arrows (adityanatraj) #548 ++ - Added NERDTreeCascadeSingleChildDir option (juanibiapina) #558 + - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (@SkylerLipthay) #231 ++ - Add support for copy command in Windows (SkylerLipthay) #231 + - Fixed typo in README.markdown - :Helptags -> :helptags + - Rename "primary" and "secondary" trees to "tab" and "window" trees. + - Move a bunch of buffer level variables into the NERDTree and UI classes. +@@ -130,14 +131,14 @@ + - add magic [[dir]] and [[file]] flags to NERDTreeIgnore + - add support for custom path filters. See :help NERDTreeAddPathFilter() + - add path listener API. See :help NERDTreePathListenerAPI. +-- expand the fs menu functionality to list file properties (@PhilRunninger, @apbarrero, @JESii) +-- make bookmarks work with `~` home shortcuts (@hiberabyss) +-- show OSX specific fsmenu options in regular vim on mac (@evindor) +-- make dir arrow icons configurable (@PickRelated) +-- optimise node sorting performance when opening large dirs (@vtsang) +-- make the root note render prettier by truncating it at a path slash (@gcmt) ++- expand the fs menu functionality to list file properties (PhilRunninger, apbarrero, JESii) ++- make bookmarks work with `~` home shortcuts (hiberabyss) ++- show OSX specific fsmenu options in regular vim on mac (evindor) ++- make dir arrow icons configurable (PickRelated) ++- optimise node sorting performance when opening large dirs (vtsang) ++- make the root note render prettier by truncating it at a path slash (gcmt) + - remove NERDChristmasTree option - its always christmas now +-- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (@pendulm) ++- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (pendulm) + - Many other fixes, doc updates and contributions from: + - @actionshrimp + - @SchDen +@@ -164,13 +165,13 @@ + - @Twinside + + ### 4.2.0 +-- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (@sickill) +-- shift the syntax highlighting out into its own syntax file (@gnap) +-- add some mac specific options to the filesystem menu - for macvim only (@andersonfreitas) +-- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (@camthompson) +-- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (@benjamingeiger) +-- if no name is given to :Bookmark, make it default to the name of the target file/dir (@minyoung) +-- use `file` completion when doing copying, create, and move operations (@EvanDotPro) ++- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (sickill) ++- shift the syntax highlighting out into its own syntax file (gnap) ++- add some mac specific options to the filesystem menu - for macvim only (andersonfreitas) ++- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (camthompson) ++- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (benjamingeiger) ++- if no name is given to :Bookmark, make it default to the name of the target file/dir (minyoung) ++- use `file` completion when doing copying, create, and move operations (EvanDotPro) + - lots of misc bug fixes from: + - @paddyoloughlin + - @sdewald +@@ -219,17 +220,17 @@ + - Bugfixes: + - make the hijack netrw functionality work when vim is started with `vim ` (thanks to Alf Mikula for the patch). + - fix a bug where the CWD wasnt being changed for some operations even when NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) +- - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to @tpope) +- - fix bugs when ignorecase was set (thanks to @nach) +- - fix a bug with the relative path code (thanks to @nach) +- - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks @nach) ++ - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to tpope) ++ - fix bugs when ignorecase was set (thanks to nach) ++ - fix a bug with the relative path code (thanks to nach) ++ - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks nach) + + + ### 3.0.1 + - Bugfixes: + - fix bugs with :NERDTreeToggle and :NERDTreeMirror when `'hidden'` was not set + - fix a bug where `:NERDTree ` would fail if `` was relative and didnt start with a `./` or `../` Thanks to James Kanze. +- - make the `q` mapping work with secondary (`:e ` style) trees, thanks to @jamessan ++ - make the `q` mapping work with secondary (`:e ` style) trees, thanks to jamessan + - fix a bunch of small bugs with secondary trees + - More insane refactoring. + +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 845f920..3951980 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.1.2' ++ return '5.1.3' + endfunction + + " SECTION: General Functions {{{1 diff --git a/tasks/preservim__nerdtree-1009/solution/solve.sh b/tasks/preservim__nerdtree-1009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1009/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/preservim__nerdtree-1009/task.toml b/tasks/preservim__nerdtree-1009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b4bb6cccb6cce336bbae869ea4e4da54a7a00e3 --- /dev/null +++ b/tasks/preservim__nerdtree-1009/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1009" +description = "Remove @mentions from PR template and change log. They weren't working." + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "2cbc76bbfd807f022031f8c789f66d105d0a5d0b" +reference = "https://github.com/preservim/nerdtree/pull/1009" +source_access = "auto" +built_at = "2026-11-16T16:10:02.469647+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:55d923e542c6f4651c3276bb0afd43676cf6a3f3f66636e4290ac6777c3e66ff" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-06-27T12:03:51Z" +diff_format = "unified" +context_files = [ + ".github/PULL_REQUEST_TEMPLATE.md", + "CHANGELOG.md", + "autoload/nerdtree.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 255 +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:02.560949+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:be6356e6f83d0b7ade99a11f97cf87e07b37dd3e7905e6a42b392a1a6990e3e1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1009/tests/capture.py b/tasks/preservim__nerdtree-1009/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1009/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/preservim__nerdtree-1009/tests/instruction.md b/tasks/preservim__nerdtree-1009/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e6df59f07035c701a3179fd3f6d57858e4574f5 --- /dev/null +++ b/tasks/preservim__nerdtree-1009/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Remove @mentions from PR template and change log. They weren't working. + +## Description + + +### Description of Changes + +Closes # + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes, + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner, and + - [x] `PATCH` version when you make backwards-compatible bug fixes. +- [x] Update version number in [autoload/nerdtree.vim](https://github.com/scrooloose/nerdtree/blob/master/autoload/nerdtree.vim#L7) +- [x] Update the ChangeLog, following this format/example: + ``` + MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... + - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2cbc76bbfd80`. 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/preservim__nerdtree-1009/tests/oracle.patch b/tasks/preservim__nerdtree-1009/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c4a1ef36d73832cbf2035574c976b5cee0a69a8e --- /dev/null +++ b/tasks/preservim__nerdtree-1009/tests/oracle.patch @@ -0,0 +1,321 @@ +diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md +index a60d1d4..1a2765e 100644 +--- a/.github/PULL_REQUEST_TEMPLATE.md ++++ b/.github/PULL_REQUEST_TEMPLATE.md +@@ -17,6 +17,6 @@ Closes # + - **.PATCH**: PR Title (Author) #PR Number + + ### 5.1... +- - **.1**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++ - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6b98977..e207f2c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,118 +1,119 @@ + # Change Log + + ### 5.1... +-- **`.2`**: Fix NERDTree opening with the wrong size. (@PhilRunninger) #1008 +-- **`.1`**: Update Changelog and create PR Template (@PhilRunninger) #1007 ++- **`.3`**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) #1009 ++- **`.2`**: Fix NERDTree opening with the wrong size. (PhilRunninger) #1008 ++- **`.1`**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **`.0`**: Too many changes for one patch... +- - Refresh a dir_node if the file wasn't found in it, and look once more. (@PhilRunninger) #1005 +- - Add a "copy path to clipboard" menu option (@PhilRunninger) #1002 +- - Enable root refresh on "vim ." a different way than #999. (@PhilRunninger) #1001 +- - Fix refreshroot (@PhilRunninger) #999 +- - Change version check to look for 703 not 730 (@vhalis) #994 +- - Change minimum vim (@PhilRunninger) #991 +- - Allow multi-character DirArrows (@PhilRunninger) #985 +- - Remove redraw! while still clearing last message empty string. (@PhilRunninger) #979 +- - fix _initChildren function value set to numChildrenCached error (@terryding77) #969 +- - On Windows, do a case-insensitive comparison of paths. (@PhilRunninger) #967 +- - Remove the "Please wait... DONE" messages. (@PhilRunninger) #966 +- - Smarter delimiter default (@PhilRunninger) #963 +- - Update directory .vimdc readme example (@spencerdcarlson) #961 +- - Preview bookmarks (@PhilRunninger) #956 +- - Add new value to NERDTreeQuitOnOpen to close bookmark table (@PhilRunninger) #955 +- - Add an :EditBookmarks command to edit the bookmarks file (@PhilRunninger) #954 +- - Before copying, turn off &shellslash. Restore after copy is finished. (@PhilRunninger) #952 +- - Set a maximum window size when zooming. (@PhilRunninger) #950 +- - Confirm the wipeout of a unsaved buffer whose file has been renamed. (@PhilRunninger) #949 +- - Escape a backslash so it can be used in a key mapping. (@PhilRunninger) #948 +- - Add a NERDTreeMinimalMenu feature (@tuzz) #938 +- - fixed root path error for windows (@zcodes) #935 +- - Restore getDirChildren for use in nerdtree-project-plugin. (@PhilRunninger) #929 +- - Document NERDTreeNodeDelimiter #912 (@PhilRunninger) #926 +- - Allow modification of menu keybindings (@Leandros) #923 +- - Add two more disqualifications for isCascadable(). (@PhilRunninger) #914 +- - Allow highlighting more than one flag. (@kristijanhusak) #908 +- - Support sorting files and directories by modification time. (@PhilRunninger) #901 +- - Parse . and .. from path string with trailing slash. (@PhilRunninger) #899 +- - Force sort to recalculate the cached sortKey. (@PhilRunninger) #898 +- - Add NERDTreeRefreshRoot command (@wgfm) #897 +- - Call Resolve on the file's path when calling :NERDTreeFind. (@PhilRunninger) #896 +- - Catch all errors, not just NERDTree errors. (@PhilRunninger) #894 +- - Fix typo in help file (@lvoisin) #892 +- - Make NERDTreeCreator set the `'nolist'` option (@lifecrisis) #889 +- - Refresh buffers after `m`, `m` operation on a folder (@PhilRunninger) #888 +- - Use a better arg for FINDSTR when using the m,l command in Windows. (@PhilRunninger) #887 +- - Fix the / motions, which currently fail with cascades (@lifecrisis) #886 +- - Function "s:UI.getLineNum()" doesn't always work on cascades. (@lifecrisis) #882 +- - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (@PhilRunninger) #878 +- - Use tabnext instead of gt to allow users to remap gt. (@PhilRunninger) #877 +- - Do a case sensitive comparison of new/existing buffers. (@PhilRunninger) #875 +- - Fix opening sub-directories that have commas in their name. (@PhilRunninger) #873 +- - Add new command to open NERDTree in the root of a VCS repository. (@PhilRunninger) #872 +- - Make sure the path to the bookmarks file exists before writing it. (@PhilRunninger) #871 +- - Unzoom NERDTree when opening a file (@PhilRunninger) #870 +- - Support unusual characters in file and directory names (@PhilRunninger) #868 +- - Reword renamed-buffer prompt to be more clear (@aflock) #867 +- - Default to placing cursor on root when closing bookmark table (@lifecrisis) #866 +- - Fix issues with sorting of nodes (@PhilRunninger) #856 +- - Better OSX detection (@bubba-h57) #853 +- - Bugfix - ensure keymaps dictionary exists before using it (@mnussbaum) #852 +- - Decrease startup-time by avoiding linear-time iteration over key mappings (@mnussbaum) #851 +- - Add code to sort mappings in quickhelp (@lifecrisis) #849 +- - Use ":clearjumps" in new NERDTree windows (@lifecrisis) #844 +- - Like m-c did before, create parent directories if needed on m-m. (@PhilRunninger) #840 +- - BUGFIX: Repair a problem with the `'u'` mapping. (@lifecrisis) #838 +- - Make the NERDTree buffer writable when rendering it. (@PhilRunninger) #837 +- - Code cleanup: Remove unsupported bookmark table mappings (@lifecrisis) #835 +- - Replace strcharpart() with substitute() for backward compatibility (@bravestarr) #834 +- - Fixed error `unknown function strcharpart` for older versions of Vim (@hav4ik) #833 +- - Clear output when NERDTree menu is aborted (@lifecrisis) #832 +- - Display a path with multi-byte characters correctly when it is truncated (@bravestarr) #830 +- - Support revealing file and executing file with xdg-open for Linux (@ngnmhieu) #824 +- - If node isn't open, count children on disk before deleting. (@PhilRunninger) #822 +- - Add new variable g:NERDTreeRemoveFileCmd (@kutsan) #816 +- - Use a better check for existence of the NERDTree buffer. (@PhilRunninger) #814 +- - Fix focussing previous buffer when closing NERDTree (@mrubli) #801 +- - Update the docs for "NERDTreeStatusline" (@lifecrisis) #796 +- - BUGFIX: Unstable behavior in the "getPath()" method (@lifecrisis) #795 +- - Revert the bugfix from pull request #785 (@lifecrisis) #794 +- - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (@lifecrisis) #786 +- - BUGFIX: Allow ":NERDTreeFind" to reveal new files (@lifecrisis) #785 +- - Add modelines (@lifecrisis) #782 +- - Change the type of completion used by NERDTreeFind (@lifecrisis) #781 +- - change NERDTreeFind with args (@zhenyangze) #778 +- - Style Choice: Using confirm() when deleting a bookmark (@lifecrisis) #777 +- - remove useless substitute when `file =~# "/$"` (@skyblueee) #773 +- - remove useless removeLeadingSpaces in _stripMarkup (@skyblueee) #772 +- - Make the "o" mapping consistent with "x" (@lifecrisis) #769 +- - Fix a problem with the "x" handler (@lifecrisis) #768 +- - Clean up the handler for the "x" mapping (@lifecrisis) #767 +- - Revert change to tab opening method (@lifecrisis) #766 +- - BUGFIX: Add back support for "b:NERDTreeRoot" (@lifecrisis) #765 +- - Fix broken "t" and "T" mappings, tabs now open at end (@lifecrisis) #759 +- - Update doc with already existing mapping variables (@asnr) #699 +- - Fix the broken g:NERDTreeBookmarksSort setting (@lifecrisis) #696 +- - Correct NERDTreeIgnore pattern in doc (@cntoplolicon) #648 +- - Remove empty segments when splitting path (@sooth-sayer) #574 +- - Suppress autocmds less agressively (@wincent) #578 #691 ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) #1005 ++ - Add a "copy path to clipboard" menu option (PhilRunninger) #1002 ++ - Enable root refresh on "vim ." a different way than #999. (PhilRunninger) #1001 ++ - Fix refreshroot (PhilRunninger) #999 ++ - Change version check to look for 703 not 730 (vhalis) #994 ++ - Change minimum vim (PhilRunninger) #991 ++ - Allow multi-character DirArrows (PhilRunninger) #985 ++ - Remove redraw! while still clearing last message empty string. (PhilRunninger) #979 ++ - fix _initChildren function value set to numChildrenCached error (terryding77) #969 ++ - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) #967 ++ - Remove the "Please wait... DONE" messages. (PhilRunninger) #966 ++ - Smarter delimiter default (PhilRunninger) #963 ++ - Update directory .vimdc readme example (spencerdcarlson) #961 ++ - Preview bookmarks (PhilRunninger) #956 ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) #955 ++ - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) #954 ++ - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) #952 ++ - Set a maximum window size when zooming. (PhilRunninger) #950 ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) #949 ++ - Escape a backslash so it can be used in a key mapping. (PhilRunninger) #948 ++ - Add a NERDTreeMinimalMenu feature (tuzz) #938 ++ - fixed root path error for windows (zcodes) #935 ++ - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) #929 ++ - Document NERDTreeNodeDelimiter #912 (PhilRunninger) #926 ++ - Allow modification of menu keybindings (Leandros) #923 ++ - Add two more disqualifications for isCascadable(). (PhilRunninger) #914 ++ - Allow highlighting more than one flag. (kristijanhusak) #908 ++ - Support sorting files and directories by modification time. (PhilRunninger) #901 ++ - Parse . and .. from path string with trailing slash. (PhilRunninger) #899 ++ - Force sort to recalculate the cached sortKey. (PhilRunninger) #898 ++ - Add NERDTreeRefreshRoot command (wgfm) #897 ++ - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) #896 ++ - Catch all errors, not just NERDTree errors. (PhilRunninger) #894 ++ - Fix typo in help file (lvoisin) #892 ++ - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) #889 ++ - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) #888 ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) #887 ++ - Fix the / motions, which currently fail with cascades (lifecrisis) #886 ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) #882 ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) #878 ++ - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) #877 ++ - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) #875 ++ - Fix opening sub-directories that have commas in their name. (PhilRunninger) #873 ++ - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) #872 ++ - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) #871 ++ - Unzoom NERDTree when opening a file (PhilRunninger) #870 ++ - Support unusual characters in file and directory names (PhilRunninger) #868 ++ - Reword renamed-buffer prompt to be more clear (aflock) #867 ++ - Default to placing cursor on root when closing bookmark table (lifecrisis) #866 ++ - Fix issues with sorting of nodes (PhilRunninger) #856 ++ - Better OSX detection (bubba-h57) #853 ++ - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) #852 ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) #851 ++ - Add code to sort mappings in quickhelp (lifecrisis) #849 ++ - Use ":clearjumps" in new NERDTree windows (lifecrisis) #844 ++ - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) #840 ++ - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) #838 ++ - Make the NERDTree buffer writable when rendering it. (PhilRunninger) #837 ++ - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) #835 ++ - Replace strcharpart() with substitute() for backward compatibility (bravestarr) #834 ++ - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) #833 ++ - Clear output when NERDTree menu is aborted (lifecrisis) #832 ++ - Display a path with multi-byte characters correctly when it is truncated (bravestarr) #830 ++ - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) #824 ++ - If node isn't open, count children on disk before deleting. (PhilRunninger) #822 ++ - Add new variable g:NERDTreeRemoveFileCmd (kutsan) #816 ++ - Use a better check for existence of the NERDTree buffer. (PhilRunninger) #814 ++ - Fix focussing previous buffer when closing NERDTree (mrubli) #801 ++ - Update the docs for "NERDTreeStatusline" (lifecrisis) #796 ++ - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) #795 ++ - Revert the bugfix from pull request #785 (lifecrisis) #794 ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) #786 ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) #785 ++ - Add modelines (lifecrisis) #782 ++ - Change the type of completion used by NERDTreeFind (lifecrisis) #781 ++ - change NERDTreeFind with args (zhenyangze) #778 ++ - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) #777 ++ - remove useless substitute when `file =~# "/$"` (skyblueee) #773 ++ - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) #772 ++ - Make the "o" mapping consistent with "x" (lifecrisis) #769 ++ - Fix a problem with the "x" handler (lifecrisis) #768 ++ - Clean up the handler for the "x" mapping (lifecrisis) #767 ++ - Revert change to tab opening method (lifecrisis) #766 ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) #765 ++ - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) #759 ++ - Update doc with already existing mapping variables (asnr) #699 ++ - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) #696 ++ - Correct NERDTreeIgnore pattern in doc (cntoplolicon) #648 ++ - Remove empty segments when splitting path (sooth-sayer) #574 ++ - Suppress autocmds less agressively (wincent) #578 #691 + - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (@josephfrazier) #676 ++ - Fix markdown headers in readme (josephfrazier) #676 + - Don't touch @o and @h registers when rendering +- - Fix bug with files and directories with dollar signs (@alegen) #649 ++ - Fix bug with files and directories with dollar signs (alegen) #649 + - Reuse/reopen existing window trees where possible #244 + - Remove NERDTree.previousBuf() +- - Change color of arrow (@Leeiio) #630 +- - Improved a tip in README.markdown (@ggicci) #628 +- - Shorten delete confimration of empty directory to `y` (@mikeperri) #530 +- - Fix API call to open directory tree in window (@devm33) #533 +- - Change default arrows on non-Windows platforms (@gwilk) #546 +- - Update to README - combine cd and git clone (@zwhitchcox) #584 +- - Update to README - Tip: start NERDTree when vim starts (@therealplato) #593 +- - Escape filename when moving an open buffer (@zacharyvoase) #595 +- - Fixed incorrect :helptags command in README (@curran) #619 +- - Fixed incomplete escaping of folder arrows (@adityanatraj) #548 +- - Added NERDTreeCascadeSingleChildDir option (@juanibiapina) #558 ++ - Change color of arrow (Leeiio) #630 ++ - Improved a tip in README.markdown (ggicci) #628 ++ - Shorten delete confimration of empty directory to `y` (mikeperri) #530 ++ - Fix API call to open directory tree in window (devm33) #533 ++ - Change default arrows on non-Windows platforms (gwilk) #546 ++ - Update to README - combine cd and git clone (zwhitchcox) #584 ++ - Update to README - Tip: start NERDTree when vim starts (therealplato) #593 ++ - Escape filename when moving an open buffer (zacharyvoase) #595 ++ - Fixed incorrect :helptags command in README (curran) #619 ++ - Fixed incomplete escaping of folder arrows (adityanatraj) #548 ++ - Added NERDTreeCascadeSingleChildDir option (juanibiapina) #558 + - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (@SkylerLipthay) #231 ++ - Add support for copy command in Windows (SkylerLipthay) #231 + - Fixed typo in README.markdown - :Helptags -> :helptags + - Rename "primary" and "secondary" trees to "tab" and "window" trees. + - Move a bunch of buffer level variables into the NERDTree and UI classes. +@@ -130,14 +131,14 @@ + - add magic [[dir]] and [[file]] flags to NERDTreeIgnore + - add support for custom path filters. See :help NERDTreeAddPathFilter() + - add path listener API. See :help NERDTreePathListenerAPI. +-- expand the fs menu functionality to list file properties (@PhilRunninger, @apbarrero, @JESii) +-- make bookmarks work with `~` home shortcuts (@hiberabyss) +-- show OSX specific fsmenu options in regular vim on mac (@evindor) +-- make dir arrow icons configurable (@PickRelated) +-- optimise node sorting performance when opening large dirs (@vtsang) +-- make the root note render prettier by truncating it at a path slash (@gcmt) ++- expand the fs menu functionality to list file properties (PhilRunninger, apbarrero, JESii) ++- make bookmarks work with `~` home shortcuts (hiberabyss) ++- show OSX specific fsmenu options in regular vim on mac (evindor) ++- make dir arrow icons configurable (PickRelated) ++- optimise node sorting performance when opening large dirs (vtsang) ++- make the root note render prettier by truncating it at a path slash (gcmt) + - remove NERDChristmasTree option - its always christmas now +-- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (@pendulm) ++- add "cascade" open and closing for dirs containing only another single dir. See :help NERDTreeCascadeOpenSingleChildDir (pendulm) + - Many other fixes, doc updates and contributions from: + - @actionshrimp + - @SchDen +@@ -164,13 +165,13 @@ + - @Twinside + + ### 4.2.0 +-- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (@sickill) +-- shift the syntax highlighting out into its own syntax file (@gnap) +-- add some mac specific options to the filesystem menu - for macvim only (@andersonfreitas) +-- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (@camthompson) +-- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (@benjamingeiger) +-- if no name is given to :Bookmark, make it default to the name of the target file/dir (@minyoung) +-- use `file` completion when doing copying, create, and move operations (@EvanDotPro) ++- Add NERDTreeDirArrows option to make the UI use pretty arrow chars instead of the old +~| chars to define the tree structure (sickill) ++- shift the syntax highlighting out into its own syntax file (gnap) ++- add some mac specific options to the filesystem menu - for macvim only (andersonfreitas) ++- Add NERDTreeMinimalUI option to remove some non functional parts of the nerdtree ui (camthompson) ++- tweak the behaviour of :NERDTreeFind - see :help :NERDTreeFind for the new behaviour (benjamingeiger) ++- if no name is given to :Bookmark, make it default to the name of the target file/dir (minyoung) ++- use `file` completion when doing copying, create, and move operations (EvanDotPro) + - lots of misc bug fixes from: + - @paddyoloughlin + - @sdewald +@@ -219,17 +220,17 @@ + - Bugfixes: + - make the hijack netrw functionality work when vim is started with `vim ` (thanks to Alf Mikula for the patch). + - fix a bug where the CWD wasnt being changed for some operations even when NERDTreeChDirMode==2 (thanks to Lucas S. Buchala) +- - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to @tpope) +- - fix bugs when ignorecase was set (thanks to @nach) +- - fix a bug with the relative path code (thanks to @nach) +- - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks @nach) ++ - add -bar to all the nerd tree :commands so they can chain with other :commands (thanks to tpope) ++ - fix bugs when ignorecase was set (thanks to nach) ++ - fix a bug with the relative path code (thanks to nach) ++ - fix a bug where doing a `:cd` would cause `:NERDTreeToggle` to fail (thanks nach) + + + ### 3.0.1 + - Bugfixes: + - fix bugs with :NERDTreeToggle and :NERDTreeMirror when `'hidden'` was not set + - fix a bug where `:NERDTree ` would fail if `` was relative and didnt start with a `./` or `../` Thanks to James Kanze. +- - make the `q` mapping work with secondary (`:e ` style) trees, thanks to @jamessan ++ - make the `q` mapping work with secondary (`:e ` style) trees, thanks to jamessan + - fix a bunch of small bugs with secondary trees + - More insane refactoring. + +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 845f920..3951980 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,7 +4,7 @@ endif + let g:loaded_nerdtree_autoload = 1 + + function! nerdtree#version() +- return '5.1.2' ++ return '5.1.3' + endfunction + + " SECTION: General Functions {{{1 diff --git a/tasks/preservim__nerdtree-1009/tests/test.sh b/tasks/preservim__nerdtree-1009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..78733de0ddbb8494c5d1568511800df0fb17d720 --- /dev/null +++ b/tasks/preservim__nerdtree-1009/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 2cbc76bbfd807f022031f8c789f66d105d0a5d0b > "$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/preservim__nerdtree-1009/tests/verifier.py b/tasks/preservim__nerdtree-1009/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1009/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/preservim__nerdtree-1013/environment/Dockerfile b/tasks/preservim__nerdtree-1013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..21a4ee900e7470846be27f34429993350fd7f837 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ca16df25fa1d6bc8505aadbc19f8cd95afa9a58d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ca16df25fa1d6bc8505aadbc19f8cd95afa9a58d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ca16df25fa1d6bc8505aadbc19f8cd95afa9a58d \ + && 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/preservim__nerdtree-1013/instruction.md b/tasks/preservim__nerdtree-1013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e10091ab42c81e012c4b45e7fcd4ece821e7f108 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Make Enter work on the `.. ( up a dir )` line + +## Description + +### Description of Changes + + +Added a callback to handle cases where a node is not found on the tree, as is the case when selecting the `.. ( up a dir )` line. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca16df25fa1d`. 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/preservim__nerdtree-1013/solution/patch.diff b/tasks/preservim__nerdtree-1013/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e1463886700dce6d1c35fc0b32a2df4e87f622d8 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/solution/patch.diff @@ -0,0 +1,40 @@ +diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md +index cdb8b35..88ffdf3 100644 +--- a/.github/ISSUE_TEMPLATE/bug.md ++++ b/.github/ISSUE_TEMPLATE/bug.md +@@ -22,9 +22,8 @@ After reading, and before submitting your issue, please remove this introductory + + #### Environment (for bug reports) + - [ ] Operating System: +-- [ ] Vim/Neovim version `:version`: +-- [ ] NERDTree version `:echo nerdtree#version(0)` or `git rev-parse --short HEAD`: +-- [ ] A link to my [vimrc](), or ++- [ ] Vim/Neovim version `:echo v:version`: ++- [ ] NERDTree version, found on 1st line in NERDTree quickhelp `?`: + - [ ] vimrc settings + - [ ] NERDTree variables + ```vim +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8d2a531..03dc27a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) N/A + - **.0**: Expand functionality of `` mapping. (PhilRunninger) #1011 + #### 5.1... +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 89feb59..057e799 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -17,6 +17,7 @@ function! nerdtree#ui_glue#createDefaultBindings() + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'FileNode', 'callback': s."customOpenFile"}) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'DirNode', 'callback': s."customOpenDir"}) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'Bookmark', 'callback': s."customOpenBookmark"}) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'all', 'callback': s."activateAll" }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': "DirNode", 'callback': s."activateDirNode" }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': "FileNode", 'callback': s."activateFileNode" }) diff --git a/tasks/preservim__nerdtree-1013/solution/solve.sh b/tasks/preservim__nerdtree-1013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1013/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/preservim__nerdtree-1013/task.toml b/tasks/preservim__nerdtree-1013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..44683b0a1d71363f7bb4ad13fab8d9f79e120fe0 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1013" +description = "Make Enter work on the `.. ( up a dir )` line" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "ca16df25fa1d6bc8505aadbc19f8cd95afa9a58d" +reference = "https://github.com/preservim/nerdtree/pull/1013" +source_access = "auto" +built_at = "2026-11-16T16:10:02.467881+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a78913f6c2f3d7bc5d432977550b16f549e2800c239878ab92d7ca2c23e4048e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-07-02T19:45:37Z" +diff_format = "unified" +context_files = [ + ".github/ISSUE_TEMPLATE/bug.md", + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +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:02.561477+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e98bbc9686312148963f2faa4628ee53ab54f8dbccf37a6e42e641504cb936c8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1013/tests/capture.py b/tasks/preservim__nerdtree-1013/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1013/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/preservim__nerdtree-1013/tests/instruction.md b/tasks/preservim__nerdtree-1013/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e10091ab42c81e012c4b45e7fcd4ece821e7f108 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Make Enter work on the `.. ( up a dir )` line + +## Description + +### Description of Changes + + +Added a callback to handle cases where a node is not found on the tree, as is the case when selecting the `.. ( up a dir )` line. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ca16df25fa1d`. 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/preservim__nerdtree-1013/tests/oracle.patch b/tasks/preservim__nerdtree-1013/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e1463886700dce6d1c35fc0b32a2df4e87f622d8 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/tests/oracle.patch @@ -0,0 +1,40 @@ +diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md +index cdb8b35..88ffdf3 100644 +--- a/.github/ISSUE_TEMPLATE/bug.md ++++ b/.github/ISSUE_TEMPLATE/bug.md +@@ -22,9 +22,8 @@ After reading, and before submitting your issue, please remove this introductory + + #### Environment (for bug reports) + - [ ] Operating System: +-- [ ] Vim/Neovim version `:version`: +-- [ ] NERDTree version `:echo nerdtree#version(0)` or `git rev-parse --short HEAD`: +-- [ ] A link to my [vimrc](), or ++- [ ] Vim/Neovim version `:echo v:version`: ++- [ ] NERDTree version, found on 1st line in NERDTree quickhelp `?`: + - [ ] vimrc settings + - [ ] NERDTree variables + ```vim +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8d2a531..03dc27a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) N/A + - **.0**: Expand functionality of `` mapping. (PhilRunninger) #1011 + #### 5.1... +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 89feb59..057e799 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -17,6 +17,7 @@ function! nerdtree#ui_glue#createDefaultBindings() + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'FileNode', 'callback': s."customOpenFile"}) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'DirNode', 'callback': s."customOpenDir"}) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'Bookmark', 'callback': s."customOpenBookmark"}) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapCustomOpen, 'scope':'all', 'callback': s."activateAll" }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': "DirNode", 'callback': s."activateDirNode" }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': "FileNode", 'callback': s."activateFileNode" }) diff --git a/tasks/preservim__nerdtree-1013/tests/test.sh b/tasks/preservim__nerdtree-1013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..89f4d92d12e85108576ae1b704f4f697ca01bfb0 --- /dev/null +++ b/tasks/preservim__nerdtree-1013/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 ca16df25fa1d6bc8505aadbc19f8cd95afa9a58d > "$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/preservim__nerdtree-1013/tests/verifier.py b/tasks/preservim__nerdtree-1013/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1013/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/preservim__nerdtree-1015/environment/Dockerfile b/tasks/preservim__nerdtree-1015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d7de888407e232ce2f0413043fb348a5e32c7f9 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 62b78de3674de8e3d294ab2a5e6ce98d1ad35f20 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 62b78de3674de8e3d294ab2a5e6ce98d1ad35f20 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 62b78de3674de8e3d294ab2a5e6ce98d1ad35f20 \ + && 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/preservim__nerdtree-1015/instruction.md b/tasks/preservim__nerdtree-1015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dcdb4f5b8eab5aa1cae3f897f2eec9cf9723dd0 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** When searching for root line num, stop at the end of the file. + +## Description + +When using the following NERDTreeStatusLine, Vim would lock up and not +work anymore. The problem was that when trying to find the root line +number, the loop was continuing past the end of the file, looping +"forever". The fix was to simply stop at the end of the file. + +let g:NERDTreeStatusline = "%{exists('g:NERDTreeFileNode')&&" . + \ "has_key(g:NERDTreeFileNode.GetSelected(),'path')?" . + \ "g:NERDTreeFileNode.GetSelected().path.getLastPathComponent(0):''}" + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `62b78de3674d`. 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/preservim__nerdtree-1015/solution/patch.diff b/tasks/preservim__nerdtree-1015/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..66f748dc6744d722486c49c26a557da74da7e135 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6b804bd..2273aa4 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) #1015 + - **.3**: Fix `` key map on the bookmark (lkebin) #1014 + - **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) N/A +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 3aa5959..97f95d9 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -254,7 +254,7 @@ endfunction + " gets the line number of the root node + function! s:UI.getRootLineNum() + let rootLine = 1 +- while getline(rootLine) !~# '^\(/\|<\)' ++ while rootLine <= line('$') && getline(rootLine) !~# '^\(/\|<\)' + let rootLine = rootLine + 1 + endwhile + return rootLine diff --git a/tasks/preservim__nerdtree-1015/solution/solve.sh b/tasks/preservim__nerdtree-1015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1015/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/preservim__nerdtree-1015/task.toml b/tasks/preservim__nerdtree-1015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a309b96b2a90d8b87460affd13ec9b1a1631a23e --- /dev/null +++ b/tasks/preservim__nerdtree-1015/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1015" +description = "When searching for root line num, stop at the end of the file." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "62b78de3674de8e3d294ab2a5e6ce98d1ad35f20" +reference = "https://github.com/preservim/nerdtree/pull/1015" +source_access = "auto" +built_at = "2026-11-16T16:10:02.466142+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:389924442d60eef36b8ba5f735e95b1702e1a2cceca1e2c1c4a53b9c438d3cf5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-07-04T04:21:51Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/ui.vim", +] +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:02.562022+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2a4a71f0f942ae8367ebecc5e3286e68ac54de040b694788f85012cbcfb3b97f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1015/tests/capture.py b/tasks/preservim__nerdtree-1015/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1015/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/preservim__nerdtree-1015/tests/instruction.md b/tasks/preservim__nerdtree-1015/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dcdb4f5b8eab5aa1cae3f897f2eec9cf9723dd0 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** When searching for root line num, stop at the end of the file. + +## Description + +When using the following NERDTreeStatusLine, Vim would lock up and not +work anymore. The problem was that when trying to find the root line +number, the loop was continuing past the end of the file, looping +"forever". The fix was to simply stop at the end of the file. + +let g:NERDTreeStatusline = "%{exists('g:NERDTreeFileNode')&&" . + \ "has_key(g:NERDTreeFileNode.GetSelected(),'path')?" . + \ "g:NERDTreeFileNode.GetSelected().path.getLastPathComponent(0):''}" + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `62b78de3674d`. 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/preservim__nerdtree-1015/tests/oracle.patch b/tasks/preservim__nerdtree-1015/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..66f748dc6744d722486c49c26a557da74da7e135 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6b804bd..2273aa4 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) #1015 + - **.3**: Fix `` key map on the bookmark (lkebin) #1014 + - **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) N/A +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 3aa5959..97f95d9 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -254,7 +254,7 @@ endfunction + " gets the line number of the root node + function! s:UI.getRootLineNum() + let rootLine = 1 +- while getline(rootLine) !~# '^\(/\|<\)' ++ while rootLine <= line('$') && getline(rootLine) !~# '^\(/\|<\)' + let rootLine = rootLine + 1 + endwhile + return rootLine diff --git a/tasks/preservim__nerdtree-1015/tests/test.sh b/tasks/preservim__nerdtree-1015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3574a2792e0fb903608f9b3647dd67765f2e193 --- /dev/null +++ b/tasks/preservim__nerdtree-1015/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 62b78de3674de8e3d294ab2a5e6ce98d1ad35f20 > "$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/preservim__nerdtree-1015/tests/verifier.py b/tasks/preservim__nerdtree-1015/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1015/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/preservim__nerdtree-1016/environment/Dockerfile b/tasks/preservim__nerdtree-1016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4e4d82638af836c70e8a9200725181ade967c3fa --- /dev/null +++ b/tasks/preservim__nerdtree-1016/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 89a1a4355bd9572d0f5b3d23733c243c6e7b05c2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 89a1a4355bd9572d0f5b3d23733c243c6e7b05c2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 89a1a4355bd9572d0f5b3d23733c243c6e7b05c2 \ + && 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/preservim__nerdtree-1016/instruction.md b/tasks/preservim__nerdtree-1016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51e716652ebcd646febf4ec068f6b3f555f5eea0 --- /dev/null +++ b/tasks/preservim__nerdtree-1016/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Use :mode instead of :redraw! when updating menu. + +## Description + +### Description of Changes +. + +Inferring from the command that we need to be using is `:mode` because it will clear the screen before redrawing. `:redraw!` apparently is a little more selective about what it will clear before redrawing the text, and was leaving the NERDTree menu on the screen when refreshing it. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `89a1a4355bd9`. 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/preservim__nerdtree-1016/solution/patch.diff b/tasks/preservim__nerdtree-1016/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..025a1e261099ef8f6e094b3466860149c4491e2d --- /dev/null +++ b/tasks/preservim__nerdtree-1016/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2273aa4..ad030a6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) #1016 + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) #1015 + - **.3**: Fix `` key map on the bookmark (lkebin) #1014 + - **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 26dbd29..1182c53 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -31,7 +31,7 @@ function! s:MenuController.showMenu() + let l:done = 0 + + while !l:done +- redraw! ++ mode + call self._echoPrompt() + + let l:key = nr2char(getchar()) diff --git a/tasks/preservim__nerdtree-1016/solution/solve.sh b/tasks/preservim__nerdtree-1016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1016/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/preservim__nerdtree-1016/task.toml b/tasks/preservim__nerdtree-1016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4801b0b69f514bd20baec915d11f21fd56319c89 --- /dev/null +++ b/tasks/preservim__nerdtree-1016/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1016" +description = "Use :mode instead of :redraw! when updating menu." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "89a1a4355bd9572d0f5b3d23733c243c6e7b05c2" +reference = "https://github.com/preservim/nerdtree/pull/1016" +source_access = "auto" +built_at = "2026-11-16T16:10:02.464536+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d7b50afea16221ad5ce7139ea6b2bf21516415fe62a787358a2be810cc6eefe2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-07-07T07:19:18Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/menu_controller.vim", +] +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:02.562546+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c17afa91dd78b5d227654b579cbfc6cd6f206f99d997cab0e095c1138bbf536b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1016/tests/capture.py b/tasks/preservim__nerdtree-1016/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1016/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/preservim__nerdtree-1016/tests/instruction.md b/tasks/preservim__nerdtree-1016/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51e716652ebcd646febf4ec068f6b3f555f5eea0 --- /dev/null +++ b/tasks/preservim__nerdtree-1016/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Use :mode instead of :redraw! when updating menu. + +## Description + +### Description of Changes +. + +Inferring from the command that we need to be using is `:mode` because it will clear the screen before redrawing. `:redraw!` apparently is a little more selective about what it will clear before redrawing the text, and was leaving the NERDTree menu on the screen when refreshing it. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) #PR Number + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) #1007 + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `89a1a4355bd9`. 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/preservim__nerdtree-1016/tests/oracle.patch b/tasks/preservim__nerdtree-1016/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..025a1e261099ef8f6e094b3466860149c4491e2d --- /dev/null +++ b/tasks/preservim__nerdtree-1016/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2273aa4..ad030a6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) #1016 + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) #1015 + - **.3**: Fix `` key map on the bookmark (lkebin) #1014 + - **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) #1013 +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 26dbd29..1182c53 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -31,7 +31,7 @@ function! s:MenuController.showMenu() + let l:done = 0 + + while !l:done +- redraw! ++ mode + call self._echoPrompt() + + let l:key = nr2char(getchar()) diff --git a/tasks/preservim__nerdtree-1016/tests/test.sh b/tasks/preservim__nerdtree-1016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..62aabf4d5825cef0b889feb2b2d3855889fab86c --- /dev/null +++ b/tasks/preservim__nerdtree-1016/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 89a1a4355bd9572d0f5b3d23733c243c6e7b05c2 > "$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/preservim__nerdtree-1016/tests/verifier.py b/tasks/preservim__nerdtree-1016/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1016/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/preservim__nerdtree-1019/environment/Dockerfile b/tasks/preservim__nerdtree-1019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f44d8f0c14a1558d2b7ef9898f5ee74e836b3218 --- /dev/null +++ b/tasks/preservim__nerdtree-1019/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2f0d48d632dc303095084b382cb665ae57ad2e63 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2f0d48d632dc303095084b382cb665ae57ad2e63 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2f0d48d632dc303095084b382cb665ae57ad2e63 \ + && 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/preservim__nerdtree-1019/instruction.md b/tasks/preservim__nerdtree-1019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4ab29406a00759820003f43a8e1d99440c91b71 --- /dev/null +++ b/tasks/preservim__nerdtree-1019/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Use :mode only in neovim. MacVim still needs to use :redraw! + +## Description + +### Description of Changes +As reported in MacVim has the same problem with `:mode` that neovim has with `:redraw!` in the NERDtree menu. I made an autoload function that handles both cases (with `if has('nvim')`), and swapped it in for all the `redraw` and `redraw!` statements. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) [#PR Number](link to PR) + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f0d48d632dc`. 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/preservim__nerdtree-1019/solution/patch.diff b/tasks/preservim__nerdtree-1019/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a1c907dd69d7d49ead55aa0be18b86ed3d2e7b8f --- /dev/null +++ b/tasks/preservim__nerdtree-1019/solution/patch.diff @@ -0,0 +1,153 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 58a23bf..232fe7b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! [#1019](https://github.com/scrooloose/nerdtree/pull/1019) + - **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. [#1017](https://github.com/scrooloose/nerdtree/pull/1017) + - **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 20ef1be..d441859 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -22,8 +22,24 @@ endfunction + " SECTION: General Functions {{{1 + "============================================================ + +-function! nerdtree#slash() ++"FUNCTION: nerdtree#redraw(bang) ++" Redraws the screen (Neovim uses the mode statement). If bang is TRUE, use ++" redraw! instead of redraw. ++function! nerdtree#redraw(bang) ++ if has('nvim') ++ mode ++ else ++ if a:bang ++ redraw! ++ else ++ redraw ++ endif ++ endif ++endfunction + ++"FUNCTION: nerdtree#slash() ++" Returns the directory separator based on OS and &shellslash ++function! nerdtree#slash() + if nerdtree#runningWindows() + if exists('+shellslash') && &shellslash + return '/' +@@ -216,7 +232,7 @@ endfunction + "Args: + "msg: the message to echo + function! nerdtree#echo(msg) +- redraw ++ call nerdtree#redraw(0) + echomsg empty(a:msg) ? "" : ("NERDTree: " . a:msg) + endfunction + +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 045e8ad..76572fd 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -254,7 +254,7 @@ function! s:deleteBookmark(bookmark) + + let l:choices = "&Yes\n&No" + +- echo | redraw ++ echo | call nerdtree#redraw(0) + let l:selection = confirm(l:message, l:choices, 1, 'Warning') + + if l:selection != 1 +@@ -266,7 +266,7 @@ function! s:deleteBookmark(bookmark) + call a:bookmark.delete() + silent call b:NERDTree.root.refresh() + call b:NERDTree.render() +- echo | redraw ++ echo | call nerdtree#redraw(0) + catch /^NERDTree/ + call nerdtree#echoWarning('could not remove bookmark') + endtry +@@ -577,7 +577,7 @@ function! s:refreshRoot() + call nerdtree#exec(g:NERDTree.GetWinNum() . "wincmd w") + call b:NERDTree.root.refresh() + call b:NERDTree.render() +- redraw ++ call nerdtree#redraw(0) + call nerdtree#exec(l:curWin . "wincmd w") + call nerdtree#echo("") + endfunction +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 1182c53..f027249 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -31,7 +31,7 @@ function! s:MenuController.showMenu() + let l:done = 0 + + while !l:done +- mode ++ call nerdtree#redraw(1) + call self._echoPrompt() + + let l:key = nr2char(getchar()) +@@ -42,7 +42,7 @@ function! s:MenuController.showMenu() + + " Redraw when "Ctrl-C" or "Esc" is received. + if !l:done || self.selection == -1 +- redraw! ++ call nerdtree#redraw(1) + endif + endtry + +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 5c37e4d..4ba653f 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -78,7 +78,7 @@ function! s:inputPrompt(action) + endif + + if g:NERDTreeMenuController.isMinimal() +- redraw! " Clear the menu ++ call nerdtree#redraw(1) " Clear the menu + return minimal . " " + else + let divider = "==========================================================" +@@ -185,7 +185,7 @@ function! NERDTreeAddNode() + call newTreeNode.putCursorHere(1, 0) + endif + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Node Not Created.") + endtry +@@ -234,7 +234,7 @@ function! NERDTreeMoveNode() + + call curNode.putCursorHere(1, 0) + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Node Not Renamed.") + endtry +@@ -272,7 +272,7 @@ function! NERDTreeDeleteNode() + call s:promptToDelBuffer(bufnum, prompt) + endif + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Could not remove node") + endtry +@@ -362,7 +362,7 @@ function! NERDTreeCopyNode() + call nerdtree#echo("Copy aborted.") + endif + let &shellslash = l:shellslash +- redraw! ++ call nerdtree#redraw(1) + endfunction + + " FUNCTION: NERDTreeCopyPath() {{{1 diff --git a/tasks/preservim__nerdtree-1019/solution/solve.sh b/tasks/preservim__nerdtree-1019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1019/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/preservim__nerdtree-1019/task.toml b/tasks/preservim__nerdtree-1019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08bdd3beb4d1b21942ad2764e88f684e0548c704 --- /dev/null +++ b/tasks/preservim__nerdtree-1019/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1019" +description = "Use :mode only in neovim. MacVim still needs to use :redraw!" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "2f0d48d632dc303095084b382cb665ae57ad2e63" +reference = "https://github.com/preservim/nerdtree/pull/1019" +source_access = "auto" +built_at = "2026-11-16T16:10:02.462875+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:17131d54b04c6668cf83ae164652f741ba574a2b1eb56237d3141f070e604673" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-07-10T13:45:59Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", + "autoload/nerdtree/ui_glue.vim", + "lib/nerdtree/menu_controller.vim", + "nerdtree_plugin/fs_menu.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +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:02.563107+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ae5e02800af196a423e0e024c7c825d26681938bd6084f84bd77c8ed711f1f85" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1019/tests/capture.py b/tasks/preservim__nerdtree-1019/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1019/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/preservim__nerdtree-1019/tests/instruction.md b/tasks/preservim__nerdtree-1019/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4ab29406a00759820003f43a8e1d99440c91b71 --- /dev/null +++ b/tasks/preservim__nerdtree-1019/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Use :mode only in neovim. MacVim still needs to use :redraw! + +## Description + +### Description of Changes +As reported in MacVim has the same problem with `:mode` that neovim has with `:redraw!` in the NERDtree menu. I made an autoload function that handles both cases (with `if has('nvim')`), and swapped it in for all the `redraw` and `redraw!` statements. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following this format/example: + ``` + #### MAJOR.MINOR... + - **.PATCH**: PR Title (Author) [#PR Number](link to PR) + + #### 5.1... + - **.1**: Update Changelog and create PR Template (PhilRunninger) + - **.0**: Too many changes for one patch... + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2f0d48d632dc`. 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/preservim__nerdtree-1019/tests/oracle.patch b/tasks/preservim__nerdtree-1019/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a1c907dd69d7d49ead55aa0be18b86ed3d2e7b8f --- /dev/null +++ b/tasks/preservim__nerdtree-1019/tests/oracle.patch @@ -0,0 +1,153 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 58a23bf..232fe7b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.2... ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! [#1019](https://github.com/scrooloose/nerdtree/pull/1019) + - **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. [#1017](https://github.com/scrooloose/nerdtree/pull/1017) + - **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 20ef1be..d441859 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -22,8 +22,24 @@ endfunction + " SECTION: General Functions {{{1 + "============================================================ + +-function! nerdtree#slash() ++"FUNCTION: nerdtree#redraw(bang) ++" Redraws the screen (Neovim uses the mode statement). If bang is TRUE, use ++" redraw! instead of redraw. ++function! nerdtree#redraw(bang) ++ if has('nvim') ++ mode ++ else ++ if a:bang ++ redraw! ++ else ++ redraw ++ endif ++ endif ++endfunction + ++"FUNCTION: nerdtree#slash() ++" Returns the directory separator based on OS and &shellslash ++function! nerdtree#slash() + if nerdtree#runningWindows() + if exists('+shellslash') && &shellslash + return '/' +@@ -216,7 +232,7 @@ endfunction + "Args: + "msg: the message to echo + function! nerdtree#echo(msg) +- redraw ++ call nerdtree#redraw(0) + echomsg empty(a:msg) ? "" : ("NERDTree: " . a:msg) + endfunction + +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 045e8ad..76572fd 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -254,7 +254,7 @@ function! s:deleteBookmark(bookmark) + + let l:choices = "&Yes\n&No" + +- echo | redraw ++ echo | call nerdtree#redraw(0) + let l:selection = confirm(l:message, l:choices, 1, 'Warning') + + if l:selection != 1 +@@ -266,7 +266,7 @@ function! s:deleteBookmark(bookmark) + call a:bookmark.delete() + silent call b:NERDTree.root.refresh() + call b:NERDTree.render() +- echo | redraw ++ echo | call nerdtree#redraw(0) + catch /^NERDTree/ + call nerdtree#echoWarning('could not remove bookmark') + endtry +@@ -577,7 +577,7 @@ function! s:refreshRoot() + call nerdtree#exec(g:NERDTree.GetWinNum() . "wincmd w") + call b:NERDTree.root.refresh() + call b:NERDTree.render() +- redraw ++ call nerdtree#redraw(0) + call nerdtree#exec(l:curWin . "wincmd w") + call nerdtree#echo("") + endfunction +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 1182c53..f027249 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -31,7 +31,7 @@ function! s:MenuController.showMenu() + let l:done = 0 + + while !l:done +- mode ++ call nerdtree#redraw(1) + call self._echoPrompt() + + let l:key = nr2char(getchar()) +@@ -42,7 +42,7 @@ function! s:MenuController.showMenu() + + " Redraw when "Ctrl-C" or "Esc" is received. + if !l:done || self.selection == -1 +- redraw! ++ call nerdtree#redraw(1) + endif + endtry + +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 5c37e4d..4ba653f 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -78,7 +78,7 @@ function! s:inputPrompt(action) + endif + + if g:NERDTreeMenuController.isMinimal() +- redraw! " Clear the menu ++ call nerdtree#redraw(1) " Clear the menu + return minimal . " " + else + let divider = "==========================================================" +@@ -185,7 +185,7 @@ function! NERDTreeAddNode() + call newTreeNode.putCursorHere(1, 0) + endif + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Node Not Created.") + endtry +@@ -234,7 +234,7 @@ function! NERDTreeMoveNode() + + call curNode.putCursorHere(1, 0) + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Node Not Renamed.") + endtry +@@ -272,7 +272,7 @@ function! NERDTreeDeleteNode() + call s:promptToDelBuffer(bufnum, prompt) + endif + +- redraw! ++ call nerdtree#redraw(1) + catch /^NERDTree/ + call nerdtree#echoWarning("Could not remove node") + endtry +@@ -362,7 +362,7 @@ function! NERDTreeCopyNode() + call nerdtree#echo("Copy aborted.") + endif + let &shellslash = l:shellslash +- redraw! ++ call nerdtree#redraw(1) + endfunction + + " FUNCTION: NERDTreeCopyPath() {{{1 diff --git a/tasks/preservim__nerdtree-1019/tests/test.sh b/tasks/preservim__nerdtree-1019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..494a7638fd7b876b6f8c8758c8814c20333af3d9 --- /dev/null +++ b/tasks/preservim__nerdtree-1019/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 2f0d48d632dc303095084b382cb665ae57ad2e63 > "$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/preservim__nerdtree-1019/tests/verifier.py b/tasks/preservim__nerdtree-1019/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1019/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/preservim__nerdtree-1029/environment/Dockerfile b/tasks/preservim__nerdtree-1029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0b0d13677a6c265aa5a521895d5d9a10104608d7 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 184fbb6ffea6dc69726b229a08153c9d08522386 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 184fbb6ffea6dc69726b229a08153c9d08522386 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 184fbb6ffea6dc69726b229a08153c9d08522386 \ + && 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/preservim__nerdtree-1029/instruction.md b/tasks/preservim__nerdtree-1029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dde1dca1e135b45d49c15ec2581bcfc38a6c98b3 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Add file extension and size to sorting capabilities + +## Description + +### Description of Changes + + +- Add `[[extension]]` to the sorting capabilities in `g:NERDTreeSortOrder`. +- Add `[[size]]` and `[[-size]]` to the sorting capabilities in `g:NERDTreeSortOrder`. +- Update NERDTree documentation. + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `184fbb6ffea6`. 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/preservim__nerdtree-1029/solution/patch.diff b/tasks/preservim__nerdtree-1029/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98a6ac77609d0f4e53e57c1c6f02584a26cfa739 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/solution/patch.diff @@ -0,0 +1,151 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e98ea0e..9e49417 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 5.3... ++- **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... + - **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) + - **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index a9ccc99..14f7078 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -1043,28 +1043,31 @@ window. Use one of the follow lines for this setting: > + Values: a list of regular expressions. + Default: ['\/$', '*', '\.swp$', '\.bak$', '\~$'] + +-This setting is a list of regular expressions which are used to specify the +-order of nodes under their parent. ++This setting is a list of regular expressions which are used to group or sort ++the nodes under their parent. + + For example, if the setting is: > + ['\.vim$', '\.c$', '\.h$', '*', 'foobar'] + < +-then all .vim files will be placed at the top, followed by all .c files then ++then all .vim files will be grouped at the top, followed by all .c files then + all .h files. All files containing the string 'foobar' will be placed at the + end. The star is a special flag: it tells the script that every node that + doesn't match any of the other regexps should be placed here. + +-If no star is present in NERDTreeSortOrder then one is automatically +-appended to the array. ++If no star is present in NERDTreeSortOrder, then one is automatically ++appended to the end of the list. + + The regex '\/$' should be used to match directory nodes. + +-A special flag can be used to sort by the modification timestamps of files and +-directories. It is either '[[timestamp]]' for ascending, or '[[-timestamp]]' +-for descending. If placed at the beginning of the list, files and directories +-are sorted by timestamp, and then by the remaining items in the sort order +-list. If this flag is in any other position of the list, timestamp sorting is +-done secondarily. See examples 4, 5, and 6 below. ++Files can also be sorted by 1) the modification timestamp, 2) the size, or 3) ++the extension. Directories are always sorted by name. To accomplish this, the ++following special flags are used: ++ [[timestamp]] [[-timestamp]] [[size]] [[-size]] [[extension]] ++The hyphen specifies a descending sort; extensions are sorted in ascending ++order only. If placed at the beginning of the list, files are sorted according ++to these flags first, and then grouped by the remaining items in the list. If ++the flags are in any other position of the list, this special sorting is done ++secondarily. See examples 4, 5, and 6 below. + + After this sorting is done, the files in each group are sorted alphabetically. + +@@ -1072,20 +1075,20 @@ Examples: > + (1) ['*', '\/$'] + (2) [] + (3) ['\/$', '\.rb$', '\.php$', '*', '\.swp$', '\.bak$', '\~$'] +- (4) ['[[timestamp]]'] +- (5) ['\/$', '*', '[[-timestamp]]'] +- (6) ['\.md$', '\.c$', '[[-timestamp]]', '*'] ++ (4) ['[[-size]]'] ++ (5) ['\/$', '*', '[[timestamp]]'] ++ (6) ['foo','\/$','[[extension]]'] + < + 1. Directories will appear last, everything else will appear above. + 2. Everything will simply appear in alphabetical order. + 3. Dirs will appear first, then ruby and php. Swap files, bak files and vim + backup files will appear last with everything else preceding them. +-4. All files and directories are sorted by timestamp, oldest first. If any +- files have identical timestamps, they are sorted alphabetically. +-5. Directories are first, newest to oldest, then everything else, newest to +- oldest. +-6. Markdown files first, followed by C source files, then everything else. +- Each group is shown newest to oldest. ++4. Everything is sorted by size, largest to smallest, with directories ++ considered to have size 0 bytes. ++5. Directories will appear first alphabetically, followed by files, sorted by ++ timestamp, oldest first. ++6. Files and directories matching 'foo' first, followed by other directories, ++ then all other files. Each section of files is sorted by file extension. + + ------------------------------------------------------------------------------ + *NERDTreeStatusline* +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index c3af195..fb1fbf8 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -380,7 +380,8 @@ endfunction + function! s:Path.getSortOrderIndex() + let i = 0 + while i < len(g:NERDTreeSortOrder) +- if self.getLastPathComponent(1) =~# g:NERDTreeSortOrder[i] ++ if g:NERDTreeSortOrder[i] !~? '\[\[-\?\(timestamp\|size\|extension\)\]\]' && ++ \ self.getLastPathComponent(1) =~# g:NERDTreeSortOrder[i] + return i + endif + let i = i + 1 +@@ -407,15 +408,38 @@ endfunction + " FUNCTION: Path.getSortKey() {{{1 + " returns a key used in compare function for sorting + function! s:Path.getSortKey() +- let l:ascending = index(g:NERDTreeSortOrder,'[[timestamp]]') +- let l:descending = index(g:NERDTreeSortOrder,'[[-timestamp]]') +- if !exists("self._sortKey") || g:NERDTreeSortOrder !=# g:NERDTreeOldSortOrder || l:ascending >= 0 || l:descending >= 0 +- let self._sortKey = [self.getSortOrderIndex()] +- +- if l:descending >= 0 +- call insert(self._sortKey, -getftime(self.str()), l:descending == 0 ? 0 : len(self._sortKey)) +- elseif l:ascending >= 0 +- call insert(self._sortKey, getftime(self.str()), l:ascending == 0 ? 0 : len(self._sortKey)) ++ if !exists("self._sortKey") || g:NERDTreeSortOrder !=# g:NERDTreeOldSortOrder ++ " Look for file metadata tags: [[timestamp]], [[extension]], [[size]] ++ let metadata = [] ++ for tag in g:NERDTreeSortOrder ++ if tag =~? '\[\[-\?timestamp\]\]' ++ if self.isDirectory ++ call add(metadata, 0) ++ else ++ call add(metadata, (tag =~ '-' ? -1 : 1) * getftime(self.str())) ++ endif ++ elseif tag =~? '\[\[-\?size\]\]' ++ if self.isDirectory ++ call add(metadata, 0) ++ else ++ call add(metadata, (tag =~ '-' ? -1 : 1) * getfsize(self.str())) ++ endif ++ elseif tag =~? '\[\[extension\]\]' ++ if self.isDirectory ++ call add(metadata, '') ++ else ++ let extension = matchstr(self.getLastPathComponent(0), '[^.]\+\.\zs[^.]\+$') ++ call add(metadata, extension == '' ? nr2char(str2nr('0x10ffff',16)) : extension) ++ endif ++ endif ++ endfor ++ ++ if g:NERDTreeSortOrder[0] =~ '\[\[.*\]\]' ++ " Apply tags' sorting first if specified first. ++ let self._sortKey = metadata + [self.getSortOrderIndex()] ++ else ++ " Otherwise, do regex grouping first. ++ let self._sortKey = [self.getSortOrderIndex()] + metadata + endif + + let path = self.getLastPathComponent(1) diff --git a/tasks/preservim__nerdtree-1029/solution/solve.sh b/tasks/preservim__nerdtree-1029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1029/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/preservim__nerdtree-1029/task.toml b/tasks/preservim__nerdtree-1029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a34ae65e66fb6cacbaf69ad9a85dc423898aa326 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1029" +description = "Add file extension and size to sorting capabilities" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "184fbb6ffea6dc69726b229a08153c9d08522386" +reference = "https://github.com/preservim/nerdtree/pull/1029" +source_access = "auto" +built_at = "2026-11-16T16:10:02.461399+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c02567c4b50e135ee0cededc5ffb6533d745fbaeda2c6cbe48aebeb50660fe77" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-08-19T07:51:35Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "doc/NERDTree.txt", + "lib/nerdtree/path.vim", +] +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:02.563652+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c54a4cf49dfacf4396ff904b4d065d54df17ec115231c46613b910eab9a29433" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1029/tests/capture.py b/tasks/preservim__nerdtree-1029/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1029/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/preservim__nerdtree-1029/tests/instruction.md b/tasks/preservim__nerdtree-1029/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dde1dca1e135b45d49c15ec2581bcfc38a6c98b3 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Add file extension and size to sorting capabilities + +## Description + +### Description of Changes + + +- Add `[[extension]]` to the sorting capabilities in `g:NERDTreeSortOrder`. +- Add `[[size]]` and `[[-size]]` to the sorting capabilities in `g:NERDTreeSortOrder`. +- Update NERDTree documentation. + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md). + + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `184fbb6ffea6`. 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/preservim__nerdtree-1029/tests/oracle.patch b/tasks/preservim__nerdtree-1029/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..98a6ac77609d0f4e53e57c1c6f02584a26cfa739 --- /dev/null +++ b/tasks/preservim__nerdtree-1029/tests/oracle.patch @@ -0,0 +1,151 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e98ea0e..9e49417 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 5.3... ++- **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... + - **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) + - **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index a9ccc99..14f7078 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -1043,28 +1043,31 @@ window. Use one of the follow lines for this setting: > + Values: a list of regular expressions. + Default: ['\/$', '*', '\.swp$', '\.bak$', '\~$'] + +-This setting is a list of regular expressions which are used to specify the +-order of nodes under their parent. ++This setting is a list of regular expressions which are used to group or sort ++the nodes under their parent. + + For example, if the setting is: > + ['\.vim$', '\.c$', '\.h$', '*', 'foobar'] + < +-then all .vim files will be placed at the top, followed by all .c files then ++then all .vim files will be grouped at the top, followed by all .c files then + all .h files. All files containing the string 'foobar' will be placed at the + end. The star is a special flag: it tells the script that every node that + doesn't match any of the other regexps should be placed here. + +-If no star is present in NERDTreeSortOrder then one is automatically +-appended to the array. ++If no star is present in NERDTreeSortOrder, then one is automatically ++appended to the end of the list. + + The regex '\/$' should be used to match directory nodes. + +-A special flag can be used to sort by the modification timestamps of files and +-directories. It is either '[[timestamp]]' for ascending, or '[[-timestamp]]' +-for descending. If placed at the beginning of the list, files and directories +-are sorted by timestamp, and then by the remaining items in the sort order +-list. If this flag is in any other position of the list, timestamp sorting is +-done secondarily. See examples 4, 5, and 6 below. ++Files can also be sorted by 1) the modification timestamp, 2) the size, or 3) ++the extension. Directories are always sorted by name. To accomplish this, the ++following special flags are used: ++ [[timestamp]] [[-timestamp]] [[size]] [[-size]] [[extension]] ++The hyphen specifies a descending sort; extensions are sorted in ascending ++order only. If placed at the beginning of the list, files are sorted according ++to these flags first, and then grouped by the remaining items in the list. If ++the flags are in any other position of the list, this special sorting is done ++secondarily. See examples 4, 5, and 6 below. + + After this sorting is done, the files in each group are sorted alphabetically. + +@@ -1072,20 +1075,20 @@ Examples: > + (1) ['*', '\/$'] + (2) [] + (3) ['\/$', '\.rb$', '\.php$', '*', '\.swp$', '\.bak$', '\~$'] +- (4) ['[[timestamp]]'] +- (5) ['\/$', '*', '[[-timestamp]]'] +- (6) ['\.md$', '\.c$', '[[-timestamp]]', '*'] ++ (4) ['[[-size]]'] ++ (5) ['\/$', '*', '[[timestamp]]'] ++ (6) ['foo','\/$','[[extension]]'] + < + 1. Directories will appear last, everything else will appear above. + 2. Everything will simply appear in alphabetical order. + 3. Dirs will appear first, then ruby and php. Swap files, bak files and vim + backup files will appear last with everything else preceding them. +-4. All files and directories are sorted by timestamp, oldest first. If any +- files have identical timestamps, they are sorted alphabetically. +-5. Directories are first, newest to oldest, then everything else, newest to +- oldest. +-6. Markdown files first, followed by C source files, then everything else. +- Each group is shown newest to oldest. ++4. Everything is sorted by size, largest to smallest, with directories ++ considered to have size 0 bytes. ++5. Directories will appear first alphabetically, followed by files, sorted by ++ timestamp, oldest first. ++6. Files and directories matching 'foo' first, followed by other directories, ++ then all other files. Each section of files is sorted by file extension. + + ------------------------------------------------------------------------------ + *NERDTreeStatusline* +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index c3af195..fb1fbf8 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -380,7 +380,8 @@ endfunction + function! s:Path.getSortOrderIndex() + let i = 0 + while i < len(g:NERDTreeSortOrder) +- if self.getLastPathComponent(1) =~# g:NERDTreeSortOrder[i] ++ if g:NERDTreeSortOrder[i] !~? '\[\[-\?\(timestamp\|size\|extension\)\]\]' && ++ \ self.getLastPathComponent(1) =~# g:NERDTreeSortOrder[i] + return i + endif + let i = i + 1 +@@ -407,15 +408,38 @@ endfunction + " FUNCTION: Path.getSortKey() {{{1 + " returns a key used in compare function for sorting + function! s:Path.getSortKey() +- let l:ascending = index(g:NERDTreeSortOrder,'[[timestamp]]') +- let l:descending = index(g:NERDTreeSortOrder,'[[-timestamp]]') +- if !exists("self._sortKey") || g:NERDTreeSortOrder !=# g:NERDTreeOldSortOrder || l:ascending >= 0 || l:descending >= 0 +- let self._sortKey = [self.getSortOrderIndex()] +- +- if l:descending >= 0 +- call insert(self._sortKey, -getftime(self.str()), l:descending == 0 ? 0 : len(self._sortKey)) +- elseif l:ascending >= 0 +- call insert(self._sortKey, getftime(self.str()), l:ascending == 0 ? 0 : len(self._sortKey)) ++ if !exists("self._sortKey") || g:NERDTreeSortOrder !=# g:NERDTreeOldSortOrder ++ " Look for file metadata tags: [[timestamp]], [[extension]], [[size]] ++ let metadata = [] ++ for tag in g:NERDTreeSortOrder ++ if tag =~? '\[\[-\?timestamp\]\]' ++ if self.isDirectory ++ call add(metadata, 0) ++ else ++ call add(metadata, (tag =~ '-' ? -1 : 1) * getftime(self.str())) ++ endif ++ elseif tag =~? '\[\[-\?size\]\]' ++ if self.isDirectory ++ call add(metadata, 0) ++ else ++ call add(metadata, (tag =~ '-' ? -1 : 1) * getfsize(self.str())) ++ endif ++ elseif tag =~? '\[\[extension\]\]' ++ if self.isDirectory ++ call add(metadata, '') ++ else ++ let extension = matchstr(self.getLastPathComponent(0), '[^.]\+\.\zs[^.]\+$') ++ call add(metadata, extension == '' ? nr2char(str2nr('0x10ffff',16)) : extension) ++ endif ++ endif ++ endfor ++ ++ if g:NERDTreeSortOrder[0] =~ '\[\[.*\]\]' ++ " Apply tags' sorting first if specified first. ++ let self._sortKey = metadata + [self.getSortOrderIndex()] ++ else ++ " Otherwise, do regex grouping first. ++ let self._sortKey = [self.getSortOrderIndex()] + metadata + endif + + let path = self.getLastPathComponent(1) diff --git a/tasks/preservim__nerdtree-1029/tests/test.sh b/tasks/preservim__nerdtree-1029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6a1c71bb2ac67897512515b702d75391c32203fa --- /dev/null +++ b/tasks/preservim__nerdtree-1029/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 184fbb6ffea6dc69726b229a08153c9d08522386 > "$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/preservim__nerdtree-1029/tests/verifier.py b/tasks/preservim__nerdtree-1029/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1029/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/preservim__nerdtree-1031/environment/Dockerfile b/tasks/preservim__nerdtree-1031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d3ea8bba12da8e8b4c00c15448407b4479ad6456 --- /dev/null +++ b/tasks/preservim__nerdtree-1031/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9afab6257b954a1e9591928e7a8cd220fde51552 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9afab6257b954a1e9591928e7a8cd220fde51552 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9afab6257b954a1e9591928e7a8cd220fde51552 \ + && 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/preservim__nerdtree-1031/instruction.md b/tasks/preservim__nerdtree-1031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef217a22ac0721e7a1a1609935a5ca97f38e04d3 --- /dev/null +++ b/tasks/preservim__nerdtree-1031/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Fix the `e` key mapping to use netrw if desired + +## Description + +### Description of Changes + + +Use `execute "edit ".`... instead of the NERDTree functions to open files or directories, allowing the NERDTreeHijackNetrw setting to do it thing. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9afab6257b95`. 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/preservim__nerdtree-1031/solution/patch.diff b/tasks/preservim__nerdtree-1031/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a536ccb8c3f786ef42843acf3dde96407284a1f8 --- /dev/null +++ b/tasks/preservim__nerdtree-1031/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 9e49417..e8b4290 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.3... ++- **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... + - **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index f045868..b82e791 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -72,6 +72,7 @@ function! nerdtree#ui_glue#createDefaultBindings() + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenInTabSilent, 'scope': 'Bookmark', 'callback': s . 'openInNewTabSilent' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenExpl, 'scope': "DirNode", 'callback': s."openExplorer" }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenExpl, 'scope': "FileNode", 'callback': s."openExplorer" }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapDeleteBookmark, 'scope': "Bookmark", 'callback': s."deleteBookmark" }) + endfunction +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index aa9dea6..4015f0b 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -523,7 +523,8 @@ endfunction + " Open an explorer window for this node in the previous window. The explorer + " can be a NERDTree window or a netrw window. + function! s:TreeDirNode.openExplorer() +- call self.open({'where': 'p'}) ++ execute "wincmd p" ++ execute "edit ".self.path.str({'format':'Edit'}) + endfunction + + " FUNCTION: TreeDirNode.openInNewTab(options) {{{1 +diff --git a/lib/nerdtree/tree_file_node.vim b/lib/nerdtree/tree_file_node.vim +index d4c060f..c14f62a 100644 +--- a/lib/nerdtree/tree_file_node.vim ++++ b/lib/nerdtree/tree_file_node.vim +@@ -246,6 +246,12 @@ function! s:TreeFileNode.openInNewTab(options) + call self.open(extend({'where': 't'}, a:options)) + endfunction + ++" FUNCTION: TreeFileNode.openExplorer() ++function! s:TreeFileNode.openExplorer() ++ execute "wincmd p" ++ execute "edit ".self.path.getParent().str({'format':'Edit'}) ++endfunction ++ + " FUNCTION: TreeFileNode.putCursorHere(isJump, recurseUpward){{{1 + " Places the cursor on the line number this node is rendered on + " diff --git a/tasks/preservim__nerdtree-1031/solution/solve.sh b/tasks/preservim__nerdtree-1031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1031/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/preservim__nerdtree-1031/task.toml b/tasks/preservim__nerdtree-1031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2be0da9c17003bbcaedeb35e6e02135c95bd64ff --- /dev/null +++ b/tasks/preservim__nerdtree-1031/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1031" +description = "Fix the `e` key mapping to use netrw if desired" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "9afab6257b954a1e9591928e7a8cd220fde51552" +reference = "https://github.com/preservim/nerdtree/pull/1031" +source_access = "auto" +built_at = "2026-11-16T16:10:02.460022+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b27a07e4ee41a87a7ea63f6df267518d70635fa6be802144695d4130015b9dcb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-08-28T00:53:24Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", + "lib/nerdtree/tree_dir_node.vim", + "lib/nerdtree/tree_file_node.vim", +] +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:02.564179+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:26d4194d143ec21065f89a506f30ac98d2278f502a993350ddd7cf36cdd471f2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1031/tests/capture.py b/tasks/preservim__nerdtree-1031/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1031/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/preservim__nerdtree-1031/tests/instruction.md b/tasks/preservim__nerdtree-1031/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef217a22ac0721e7a1a1609935a5ca97f38e04d3 --- /dev/null +++ b/tasks/preservim__nerdtree-1031/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Fix the `e` key mapping to use netrw if desired + +## Description + +### Description of Changes + + +Use `execute "edit ".`... instead of the NERDTree functions to open files or directories, allowing the NERDTreeHijackNetrw setting to do it thing. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9afab6257b95`. 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/preservim__nerdtree-1031/tests/oracle.patch b/tasks/preservim__nerdtree-1031/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a536ccb8c3f786ef42843acf3dde96407284a1f8 --- /dev/null +++ b/tasks/preservim__nerdtree-1031/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 9e49417..e8b4290 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.3... ++- **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... + - **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index f045868..b82e791 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -72,6 +72,7 @@ function! nerdtree#ui_glue#createDefaultBindings() + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenInTabSilent, 'scope': 'Bookmark', 'callback': s . 'openInNewTabSilent' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenExpl, 'scope': "DirNode", 'callback': s."openExplorer" }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenExpl, 'scope': "FileNode", 'callback': s."openExplorer" }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapDeleteBookmark, 'scope': "Bookmark", 'callback': s."deleteBookmark" }) + endfunction +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index aa9dea6..4015f0b 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -523,7 +523,8 @@ endfunction + " Open an explorer window for this node in the previous window. The explorer + " can be a NERDTree window or a netrw window. + function! s:TreeDirNode.openExplorer() +- call self.open({'where': 'p'}) ++ execute "wincmd p" ++ execute "edit ".self.path.str({'format':'Edit'}) + endfunction + + " FUNCTION: TreeDirNode.openInNewTab(options) {{{1 +diff --git a/lib/nerdtree/tree_file_node.vim b/lib/nerdtree/tree_file_node.vim +index d4c060f..c14f62a 100644 +--- a/lib/nerdtree/tree_file_node.vim ++++ b/lib/nerdtree/tree_file_node.vim +@@ -246,6 +246,12 @@ function! s:TreeFileNode.openInNewTab(options) + call self.open(extend({'where': 't'}, a:options)) + endfunction + ++" FUNCTION: TreeFileNode.openExplorer() ++function! s:TreeFileNode.openExplorer() ++ execute "wincmd p" ++ execute "edit ".self.path.getParent().str({'format':'Edit'}) ++endfunction ++ + " FUNCTION: TreeFileNode.putCursorHere(isJump, recurseUpward){{{1 + " Places the cursor on the line number this node is rendered on + " diff --git a/tasks/preservim__nerdtree-1031/tests/test.sh b/tasks/preservim__nerdtree-1031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a12d94cb57c0dfae06644b7da1d93d9287d787e --- /dev/null +++ b/tasks/preservim__nerdtree-1031/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 9afab6257b954a1e9591928e7a8cd220fde51552 > "$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/preservim__nerdtree-1031/tests/verifier.py b/tasks/preservim__nerdtree-1031/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1031/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/preservim__nerdtree-1032/environment/Dockerfile b/tasks/preservim__nerdtree-1032/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff6178bb9f89cc98bde5ee9fb8a3ab2558ad5d0c --- /dev/null +++ b/tasks/preservim__nerdtree-1032/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 42455176896560bf8cf7fc8457232131231b358f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 42455176896560bf8cf7fc8457232131231b358f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 42455176896560bf8cf7fc8457232131231b358f \ + && 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/preservim__nerdtree-1032/instruction.md b/tasks/preservim__nerdtree-1032/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29cba6f423a6c17cababaf7c0063c20915b6109a --- /dev/null +++ b/tasks/preservim__nerdtree-1032/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Support tab-specific CWDs + +## Description + +### Description of Changes + + +The user can now select whether to use `:cd` or `:tcd` when changing the current working directory. This is controlled by a new variable: `g:NERDTreeUseTCD`. + + + +A new value was added to `g:NERDTreeChDirMode`. If it's set to 3, when switching tabs, an autocmd changes the CWD to be the root of the tab's NERDTree. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `424551768965`. 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/preservim__nerdtree-1032/solution/patch.diff b/tasks/preservim__nerdtree-1032/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..56d2568ff0872c1bb54c862e112d1d54f3e178f0 --- /dev/null +++ b/tasks/preservim__nerdtree-1032/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index f79be93..73d17b1 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,8 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + ++#### 6.2 ++- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) + #### 6.1 + - **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) + - **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 14f7078..32b0b5d 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -849,9 +849,17 @@ above nodes would then be sorted like this: > + z110.txt + < + ------------------------------------------------------------------------------ +- *NERDTreeChDirMode* ++ *NERDTreeUseTCD* ++Values: 0 or 1. ++Default: 0. ++ ++By default, NERDTree will use the `:cd` command to change the current working ++directory. If this setting is turned on, and the `:tcd` command is available, it ++will be used instead. + +-Values: 0, 1 or 2. ++------------------------------------------------------------------------------ ++ *NERDTreeChDirMode* ++Values: 0, 1, 2, or 3. + Default: 0. + + Use this setting to tell the script when (if at all) to change the current +@@ -871,6 +879,9 @@ the CWD is changed whenever the tree root is changed. For example, if the CWD + is /home/marty/foobar and you make the node for /home/marty/foobar/baz the new + root then the CWD will become /home/marty/foobar/baz. + ++If the set to 3, then it behaves the same as if set to 2, and the CWD is ++changed whenever changing tabs to whatever the tree root is on that tab. ++ + ------------------------------------------------------------------------------ + *NERDTreeHighlightCursorline* + Values: 0 or 1. +@@ -980,7 +991,6 @@ then (to single click activate it) you must click somewhere in + + ------------------------------------------------------------------------------ + *NERDTreeQuitOnOpen* +- + Values: 0,1,2 or 3. + Default: 0 + +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index a12eb36..3e7ade8 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -20,7 +20,7 @@ function! s:NERDTree.changeRoot(node) + call self.root.open() + + "change dir to the dir of the new root if instructed to +- if g:NERDTreeChDirMode ==# 2 ++ if g:NERDTreeChDirMode >= 2 + call self.root.path.changeToDir() + endif + +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index d00bb89..ccb9423 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -87,8 +87,13 @@ function! s:Path.changeToDir() + endif + + try +- execute "cd " . dir +- call nerdtree#echo("CWD is now: " . getcwd()) ++ if g:NERDTreeUseTCD && exists(":tcd") == 2 ++ execute "tcd " . dir ++ call nerdtree#echo("Tab's CWD is now: " . getcwd()) ++ else ++ execute "cd " . dir ++ call nerdtree#echo("CWD is now: " . getcwd()) ++ endif + catch + throw "NERDTree.PathChangeError: cannot change CWD to " . dir + endtry +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index 40609f0..5faebaa 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -48,6 +48,7 @@ call s:initVariable("g:NERDTreeAutoCenterThreshold", 3) + call s:initVariable("g:NERDTreeCaseSensitiveSort", 0) + call s:initVariable("g:NERDTreeNaturalSort", 0) + call s:initVariable("g:NERDTreeSortHiddenFirst", 1) ++call s:initVariable("g:NERDTreeUseTCD", 0) + call s:initVariable("g:NERDTreeChDirMode", 0) + call s:initVariable("g:NERDTreeCreatePrefix", "silent") + call s:initVariable("g:NERDTreeMinimalUI", 0) +@@ -183,6 +184,12 @@ if g:NERDTreeHijackNetrw + augroup END + endif + ++if g:NERDTreeChDirMode == 3 ++ augroup NERDTreeChDirOnTabSwitch ++ autocmd TabEnter * if g:NERDTree.ExistsForTab()|call g:NERDTree.ForCurrentTab().getRoot().path.changeToDir()|endif ++ augroup END ++endif ++ + " SECTION: Public API {{{1 + "============================================================ + function! NERDTreeAddMenuItem(options) diff --git a/tasks/preservim__nerdtree-1032/solution/solve.sh b/tasks/preservim__nerdtree-1032/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1032/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/preservim__nerdtree-1032/task.toml b/tasks/preservim__nerdtree-1032/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..91fc5d8a5d0da24053273e5c544c53a5e65cbacb --- /dev/null +++ b/tasks/preservim__nerdtree-1032/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1032" +description = "Support tab-specific CWDs" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "42455176896560bf8cf7fc8457232131231b358f" +reference = "https://github.com/preservim/nerdtree/pull/1032" +source_access = "auto" +built_at = "2026-11-16T16:10:02.450590+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e7d64cf4acf828b8370917b1a7a7e7572043b0e72350f62f369617cd48aa5268" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-10-16T17:26:21Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "doc/NERDTree.txt", + "lib/nerdtree/nerdtree.vim", + "lib/nerdtree/path.vim", + "plugin/NERD_tree.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 36 +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:02.564691+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c2e9e8a71cc3d3565ba9c01d75ba007ac34ac6e5893086c243f3263412fac9ae" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1032/tests/capture.py b/tasks/preservim__nerdtree-1032/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1032/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/preservim__nerdtree-1032/tests/instruction.md b/tasks/preservim__nerdtree-1032/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29cba6f423a6c17cababaf7c0063c20915b6109a --- /dev/null +++ b/tasks/preservim__nerdtree-1032/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Support tab-specific CWDs + +## Description + +### Description of Changes + + +The user can now select whether to use `:cd` or `:tcd` when changing the current working directory. This is controlled by a new variable: `g:NERDTreeUseTCD`. + + + +A new value was added to `g:NERDTreeChDirMode`. If it's set to 3, when switching tabs, an autocmd changes the CWD to be the root of the tab's NERDTree. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `424551768965`. 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/preservim__nerdtree-1032/tests/oracle.patch b/tasks/preservim__nerdtree-1032/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..56d2568ff0872c1bb54c862e112d1d54f3e178f0 --- /dev/null +++ b/tasks/preservim__nerdtree-1032/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index f79be93..73d17b1 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,8 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + ++#### 6.2 ++- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) + #### 6.1 + - **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) + - **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 14f7078..32b0b5d 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -849,9 +849,17 @@ above nodes would then be sorted like this: > + z110.txt + < + ------------------------------------------------------------------------------ +- *NERDTreeChDirMode* ++ *NERDTreeUseTCD* ++Values: 0 or 1. ++Default: 0. ++ ++By default, NERDTree will use the `:cd` command to change the current working ++directory. If this setting is turned on, and the `:tcd` command is available, it ++will be used instead. + +-Values: 0, 1 or 2. ++------------------------------------------------------------------------------ ++ *NERDTreeChDirMode* ++Values: 0, 1, 2, or 3. + Default: 0. + + Use this setting to tell the script when (if at all) to change the current +@@ -871,6 +879,9 @@ the CWD is changed whenever the tree root is changed. For example, if the CWD + is /home/marty/foobar and you make the node for /home/marty/foobar/baz the new + root then the CWD will become /home/marty/foobar/baz. + ++If the set to 3, then it behaves the same as if set to 2, and the CWD is ++changed whenever changing tabs to whatever the tree root is on that tab. ++ + ------------------------------------------------------------------------------ + *NERDTreeHighlightCursorline* + Values: 0 or 1. +@@ -980,7 +991,6 @@ then (to single click activate it) you must click somewhere in + + ------------------------------------------------------------------------------ + *NERDTreeQuitOnOpen* +- + Values: 0,1,2 or 3. + Default: 0 + +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index a12eb36..3e7ade8 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -20,7 +20,7 @@ function! s:NERDTree.changeRoot(node) + call self.root.open() + + "change dir to the dir of the new root if instructed to +- if g:NERDTreeChDirMode ==# 2 ++ if g:NERDTreeChDirMode >= 2 + call self.root.path.changeToDir() + endif + +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index d00bb89..ccb9423 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -87,8 +87,13 @@ function! s:Path.changeToDir() + endif + + try +- execute "cd " . dir +- call nerdtree#echo("CWD is now: " . getcwd()) ++ if g:NERDTreeUseTCD && exists(":tcd") == 2 ++ execute "tcd " . dir ++ call nerdtree#echo("Tab's CWD is now: " . getcwd()) ++ else ++ execute "cd " . dir ++ call nerdtree#echo("CWD is now: " . getcwd()) ++ endif + catch + throw "NERDTree.PathChangeError: cannot change CWD to " . dir + endtry +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index 40609f0..5faebaa 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -48,6 +48,7 @@ call s:initVariable("g:NERDTreeAutoCenterThreshold", 3) + call s:initVariable("g:NERDTreeCaseSensitiveSort", 0) + call s:initVariable("g:NERDTreeNaturalSort", 0) + call s:initVariable("g:NERDTreeSortHiddenFirst", 1) ++call s:initVariable("g:NERDTreeUseTCD", 0) + call s:initVariable("g:NERDTreeChDirMode", 0) + call s:initVariable("g:NERDTreeCreatePrefix", "silent") + call s:initVariable("g:NERDTreeMinimalUI", 0) +@@ -183,6 +184,12 @@ if g:NERDTreeHijackNetrw + augroup END + endif + ++if g:NERDTreeChDirMode == 3 ++ augroup NERDTreeChDirOnTabSwitch ++ autocmd TabEnter * if g:NERDTree.ExistsForTab()|call g:NERDTree.ForCurrentTab().getRoot().path.changeToDir()|endif ++ augroup END ++endif ++ + " SECTION: Public API {{{1 + "============================================================ + function! NERDTreeAddMenuItem(options) diff --git a/tasks/preservim__nerdtree-1032/tests/test.sh b/tasks/preservim__nerdtree-1032/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5326ffbe5fcba24762eda5bd27f0752f9ea5dd37 --- /dev/null +++ b/tasks/preservim__nerdtree-1032/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 42455176896560bf8cf7fc8457232131231b358f > "$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/preservim__nerdtree-1032/tests/verifier.py b/tasks/preservim__nerdtree-1032/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1032/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/preservim__nerdtree-1035/environment/Dockerfile b/tasks/preservim__nerdtree-1035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54e094d43ccc99808361f27b687d26bca00e40f3 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3d508aedce35e1d952d3ce92378ad27ea5960fa6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3d508aedce35e1d952d3ce92378ad27ea5960fa6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3d508aedce35e1d952d3ce92378ad27ea5960fa6 \ + && 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/preservim__nerdtree-1035/instruction.md b/tasks/preservim__nerdtree-1035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf5eca226520aa25f6a7e5846b3005df2960cb61 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Make the behavior of window splits consistent + +## Description + +### Description of Changes + +This PR addresses changes requested for #941, and expands on the work started there. + + +This PR forces NERDTree to respect the user's values for the `splitright` and `splitbelow` settings, and the `g:NERDTreeWinPos` variable. This changes the current behavior of the splits opened by NERDTree, so this will be a new MAJOR release - 6.0.0. The changes are as follows: + +1. The window to be split will **always** be the previous window. This could be the one where `:NERDTree` (or `:NERDTreeFocus` or `:NERDTreeToggle`) was invoked. Or maybe a window command (such as `10h`) was used to jump directly to the NERDTree window. When in doubt, you can use the `p` command to jump between the previous and current windows. +1. The `g:NERDTreeWinPos` variable will **always** be respected. This pertains to a NERDTree created when `g:NERDTreeHijackNetrw` is 1, and Vim is invoked with a directory, as in `vim .`. When splitting the window multiple times in this scenario, NERDTree will stay full-height on the desired side of the screen. +1. The vim setting `splitright` will be be respected. When performing a vertical split (`s` or `gs`), the previous window will be split to the right (`splitright`) or left (`nosplitright`) as directed by the user's setting. +1. The vim setting `splitbelow` will be be respected. When performing a horizontal split (`i` or `gi`), the previous window will be split above (`nosplitbelow`) or below (`splitbelow`) as directed by the user's setting. + +These changes bring consistency to the NERDTree split commands, which previously had worked differently for vertical vs horizontal splitting. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [x] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3d508aedce35`. 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/preservim__nerdtree-1035/solution/patch.diff b/tasks/preservim__nerdtree-1035/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7a4aaf95d128498773e22b5b980dc2a5b0cfbc64 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/solution/patch.diff @@ -0,0 +1,173 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e8b4290..2045af8 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 6.0... ++- **.0**: Make the behavior of window splits consistent [#1035](https://github.com/scrooloose/nerdtree/pull/1035) + #### 5.3... + - **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 4391565..61adb9c 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,6 +4,11 @@ endif + let g:loaded_nerdtree_autoload = 1 + + let s:rootNERDTreePath = resolve(expand(":p:h:h")) ++ ++"FUNCTION: nerdtree#version(...) {{{1 ++" If any value is given as an argument, the entire line of text from the ++" change log is shown for the current version; otherwise, only the version ++" number is shown. + function! nerdtree#version(...) + let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) + let l:text = 'Unknown' +@@ -22,6 +27,7 @@ endfunction + " SECTION: General Functions {{{1 + "============================================================ + ++"FUNCTION: nerdtree#slash() {{{2 + function! nerdtree#slash() + + if nerdtree#runningWindows() +@@ -49,7 +55,6 @@ function! nerdtree#and(x,y) + if (l:x % 2) && (l:y % 2) + let l:result += float2nr(pow(2, l:n)) + endif +- echomsg l:x . ", " . l:y . " => " l:result + let l:x = float2nr(l:x / 2) + let l:y = float2nr(l:y / 2) + let l:n += 1 +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 705d4f9..bed912d 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -148,12 +148,19 @@ function! s:NERDTree.GetWinNum() + return bufwinnr(t:NERDTreeBufName) + endif + ++ " If WindowTree, there is no t:NERDTreeBufName variable. Search all windows. ++ for w in range(1,winnr('$')) ++ if bufname(winbufnr(w)) =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' ++ return w ++ endif ++ endfor ++ + return -1 + endfunction + + "FUNCTION: s:NERDTree.IsOpen() {{{1 + function! s:NERDTree.IsOpen() +- return s:NERDTree.GetWinNum() != -1 || bufname('%') =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' ++ return s:NERDTree.GetWinNum() != -1 + endfunction + + "FUNCTION: s:NERDTree.isTabTree() {{{1 +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 5953eea..ffc7506 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -71,9 +71,9 @@ endfunction + function! s:Opener._gotoTargetWin() + if b:NERDTree.isWinTree() + if self._where == 'v' +- vsplit ++ call self._newVSplit() + elseif self._where == 'h' +- split ++ call self._newSplit() + elseif self._where == 't' + tabnew + endif +@@ -153,44 +153,17 @@ endfunction + + " FUNCTION: Opener._newSplit() {{{1 + function! s:Opener._newSplit() +- " Save the user's settings for splitbelow and splitright +- let savesplitbelow=&splitbelow +- let savesplitright=&splitright +- +- " 'there' will be set to a command to move from the split window +- " back to the explorer window +- " +- " 'back' will be set to a command to move from the explorer window +- " back to the newly split window +- " +- " 'right' and 'below' will be set to the settings needed for +- " splitbelow and splitright IF the explorer is the only window. +- " +- let there= g:NERDTreeWinPos ==# "left" ? "wincmd h" : "wincmd l" +- let back = g:NERDTreeWinPos ==# "left" ? "wincmd l" : "wincmd h" +- let right= g:NERDTreeWinPos ==# "left" +- let below=0 +- +- " Attempt to go to adjacent window +- call nerdtree#exec(back, 1) +- + let onlyOneWin = (winnr("$") ==# 1) +- +- " If no adjacent window, set splitright and splitbelow appropriately ++ let savesplitright = &splitright + if onlyOneWin +- let &splitright=right +- let &splitbelow=below +- else +- " found adjacent window - invert split direction +- let &splitright=!right +- let &splitbelow=!below ++ let &splitright = (g:NERDTreeWinPos ==# "left") + endif + +- let splitMode = onlyOneWin ? "vertical" : "" +- + " Open the new window + try +- exec(splitMode." sp ") ++ call nerdtree#exec('wincmd p', 1) ++ " If only one window (ie. NERDTree), split vertically instead. ++ call nerdtree#exec(onlyOneWin ? "vertical split" : "split",1) + catch /^Vim\%((\a\+)\)\=:E37/ + call g:NERDTree.CursorToTreeWin() + throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self._path.str() ." is already open and modified." +@@ -200,14 +173,12 @@ function! s:Opener._newSplit() + + "resize the tree window if no other window was open before + if onlyOneWin +- let size = exists("b:NERDTreeOldWindowSize") ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize +- call nerdtree#exec(there, 1) +- exec("silent ". splitMode ." resize ". size) ++ let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize ++ call nerdtree#exec('wincmd p', 1) ++ call nerdtree#exec('silent '. splitMode .' resize '. size, 1) + call nerdtree#exec('wincmd p', 0) + endif + +- " Restore splitmode settings +- let &splitbelow=savesplitbelow + let &splitright=savesplitright + endfunction + +@@ -215,7 +186,10 @@ endfunction + function! s:Opener._newVSplit() + let l:winwidth = winwidth('.') + +- if winnr('$') == 1 ++ let onlyOneWin = (winnr("$") ==# 1) ++ let savesplitright = &splitright ++ if onlyOneWin ++ let &splitright = (g:NERDTreeWinPos ==# "left") + let l:winwidth = g:NERDTreeWinSize + endif + +@@ -229,6 +203,7 @@ function! s:Opener._newVSplit() + execute 'silent vertical resize ' . l:winwidth + + call nerdtree#exec(l:currentWindowNumber . 'wincmd w', 0) ++ let &splitright=savesplitright + endfunction + + " FUNCTION: Opener.open(target) {{{1 diff --git a/tasks/preservim__nerdtree-1035/solution/solve.sh b/tasks/preservim__nerdtree-1035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1035/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/preservim__nerdtree-1035/task.toml b/tasks/preservim__nerdtree-1035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b85c9487a0463301fe1ac394a3e3da4d5c067c57 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1035" +description = "Make the behavior of window splits consistent" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "3d508aedce35e1d952d3ce92378ad27ea5960fa6" +reference = "https://github.com/preservim/nerdtree/pull/1035" +source_access = "auto" +built_at = "2026-11-16T16:10:02.438788+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:536be4f70d5c0ae616343dbfb29182001e9495ebda3ad3d4b1f4dcefac18f13d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-09-24T05:19:28Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", + "lib/nerdtree/nerdtree.vim", + "lib/nerdtree/opener.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 73 +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:02.565218+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ee60fb1d8a29135b8fd6bddf434b89636607c3912ed47f91d250d076e3badd9a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1035/tests/capture.py b/tasks/preservim__nerdtree-1035/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1035/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/preservim__nerdtree-1035/tests/instruction.md b/tasks/preservim__nerdtree-1035/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf5eca226520aa25f6a7e5846b3005df2960cb61 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Make the behavior of window splits consistent + +## Description + +### Description of Changes + +This PR addresses changes requested for #941, and expands on the work started there. + + +This PR forces NERDTree to respect the user's values for the `splitright` and `splitbelow` settings, and the `g:NERDTreeWinPos` variable. This changes the current behavior of the splits opened by NERDTree, so this will be a new MAJOR release - 6.0.0. The changes are as follows: + +1. The window to be split will **always** be the previous window. This could be the one where `:NERDTree` (or `:NERDTreeFocus` or `:NERDTreeToggle`) was invoked. Or maybe a window command (such as `10h`) was used to jump directly to the NERDTree window. When in doubt, you can use the `p` command to jump between the previous and current windows. +1. The `g:NERDTreeWinPos` variable will **always** be respected. This pertains to a NERDTree created when `g:NERDTreeHijackNetrw` is 1, and Vim is invoked with a directory, as in `vim .`. When splitting the window multiple times in this scenario, NERDTree will stay full-height on the desired side of the screen. +1. The vim setting `splitright` will be be respected. When performing a vertical split (`s` or `gs`), the previous window will be split to the right (`splitright`) or left (`nosplitright`) as directed by the user's setting. +1. The vim setting `splitbelow` will be be respected. When performing a horizontal split (`i` or `gi`), the previous window will be split above (`nosplitbelow`) or below (`splitbelow`) as directed by the user's setting. + +These changes bring consistency to the NERDTree split commands, which previously had worked differently for vertical vs horizontal splitting. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [x] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3d508aedce35`. 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/preservim__nerdtree-1035/tests/oracle.patch b/tasks/preservim__nerdtree-1035/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7a4aaf95d128498773e22b5b980dc2a5b0cfbc64 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/tests/oracle.patch @@ -0,0 +1,173 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e8b4290..2045af8 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 6.0... ++- **.0**: Make the behavior of window splits consistent [#1035](https://github.com/scrooloose/nerdtree/pull/1035) + #### 5.3... + - **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 4391565..61adb9c 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -4,6 +4,11 @@ endif + let g:loaded_nerdtree_autoload = 1 + + let s:rootNERDTreePath = resolve(expand(":p:h:h")) ++ ++"FUNCTION: nerdtree#version(...) {{{1 ++" If any value is given as an argument, the entire line of text from the ++" change log is shown for the current version; otherwise, only the version ++" number is shown. + function! nerdtree#version(...) + let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) + let l:text = 'Unknown' +@@ -22,6 +27,7 @@ endfunction + " SECTION: General Functions {{{1 + "============================================================ + ++"FUNCTION: nerdtree#slash() {{{2 + function! nerdtree#slash() + + if nerdtree#runningWindows() +@@ -49,7 +55,6 @@ function! nerdtree#and(x,y) + if (l:x % 2) && (l:y % 2) + let l:result += float2nr(pow(2, l:n)) + endif +- echomsg l:x . ", " . l:y . " => " l:result + let l:x = float2nr(l:x / 2) + let l:y = float2nr(l:y / 2) + let l:n += 1 +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 705d4f9..bed912d 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -148,12 +148,19 @@ function! s:NERDTree.GetWinNum() + return bufwinnr(t:NERDTreeBufName) + endif + ++ " If WindowTree, there is no t:NERDTreeBufName variable. Search all windows. ++ for w in range(1,winnr('$')) ++ if bufname(winbufnr(w)) =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' ++ return w ++ endif ++ endfor ++ + return -1 + endfunction + + "FUNCTION: s:NERDTree.IsOpen() {{{1 + function! s:NERDTree.IsOpen() +- return s:NERDTree.GetWinNum() != -1 || bufname('%') =~# '^' . g:NERDTreeCreator.BufNamePrefix() . '\d\+$' ++ return s:NERDTree.GetWinNum() != -1 + endfunction + + "FUNCTION: s:NERDTree.isTabTree() {{{1 +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 5953eea..ffc7506 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -71,9 +71,9 @@ endfunction + function! s:Opener._gotoTargetWin() + if b:NERDTree.isWinTree() + if self._where == 'v' +- vsplit ++ call self._newVSplit() + elseif self._where == 'h' +- split ++ call self._newSplit() + elseif self._where == 't' + tabnew + endif +@@ -153,44 +153,17 @@ endfunction + + " FUNCTION: Opener._newSplit() {{{1 + function! s:Opener._newSplit() +- " Save the user's settings for splitbelow and splitright +- let savesplitbelow=&splitbelow +- let savesplitright=&splitright +- +- " 'there' will be set to a command to move from the split window +- " back to the explorer window +- " +- " 'back' will be set to a command to move from the explorer window +- " back to the newly split window +- " +- " 'right' and 'below' will be set to the settings needed for +- " splitbelow and splitright IF the explorer is the only window. +- " +- let there= g:NERDTreeWinPos ==# "left" ? "wincmd h" : "wincmd l" +- let back = g:NERDTreeWinPos ==# "left" ? "wincmd l" : "wincmd h" +- let right= g:NERDTreeWinPos ==# "left" +- let below=0 +- +- " Attempt to go to adjacent window +- call nerdtree#exec(back, 1) +- + let onlyOneWin = (winnr("$") ==# 1) +- +- " If no adjacent window, set splitright and splitbelow appropriately ++ let savesplitright = &splitright + if onlyOneWin +- let &splitright=right +- let &splitbelow=below +- else +- " found adjacent window - invert split direction +- let &splitright=!right +- let &splitbelow=!below ++ let &splitright = (g:NERDTreeWinPos ==# "left") + endif + +- let splitMode = onlyOneWin ? "vertical" : "" +- + " Open the new window + try +- exec(splitMode." sp ") ++ call nerdtree#exec('wincmd p', 1) ++ " If only one window (ie. NERDTree), split vertically instead. ++ call nerdtree#exec(onlyOneWin ? "vertical split" : "split",1) + catch /^Vim\%((\a\+)\)\=:E37/ + call g:NERDTree.CursorToTreeWin() + throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self._path.str() ." is already open and modified." +@@ -200,14 +173,12 @@ function! s:Opener._newSplit() + + "resize the tree window if no other window was open before + if onlyOneWin +- let size = exists("b:NERDTreeOldWindowSize") ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize +- call nerdtree#exec(there, 1) +- exec("silent ". splitMode ." resize ". size) ++ let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize ++ call nerdtree#exec('wincmd p', 1) ++ call nerdtree#exec('silent '. splitMode .' resize '. size, 1) + call nerdtree#exec('wincmd p', 0) + endif + +- " Restore splitmode settings +- let &splitbelow=savesplitbelow + let &splitright=savesplitright + endfunction + +@@ -215,7 +186,10 @@ endfunction + function! s:Opener._newVSplit() + let l:winwidth = winwidth('.') + +- if winnr('$') == 1 ++ let onlyOneWin = (winnr("$") ==# 1) ++ let savesplitright = &splitright ++ if onlyOneWin ++ let &splitright = (g:NERDTreeWinPos ==# "left") + let l:winwidth = g:NERDTreeWinSize + endif + +@@ -229,6 +203,7 @@ function! s:Opener._newVSplit() + execute 'silent vertical resize ' . l:winwidth + + call nerdtree#exec(l:currentWindowNumber . 'wincmd w', 0) ++ let &splitright=savesplitright + endfunction + + " FUNCTION: Opener.open(target) {{{1 diff --git a/tasks/preservim__nerdtree-1035/tests/test.sh b/tasks/preservim__nerdtree-1035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..71f3c9d49a867d270364dae91fca60021a52aba0 --- /dev/null +++ b/tasks/preservim__nerdtree-1035/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 3d508aedce35e1d952d3ce92378ad27ea5960fa6 > "$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/preservim__nerdtree-1035/tests/verifier.py b/tasks/preservim__nerdtree-1035/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1035/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/preservim__nerdtree-1037/environment/Dockerfile b/tasks/preservim__nerdtree-1037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..704f2fab485c7710445193ca686d0f2879d59854 --- /dev/null +++ b/tasks/preservim__nerdtree-1037/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 51fc75efdb8ac58c853492c3f61d854f65ed78ec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 51fc75efdb8ac58c853492c3f61d854f65ed78ec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 51fc75efdb8ac58c853492c3f61d854f65ed78ec \ + && 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/preservim__nerdtree-1037/instruction.md b/tasks/preservim__nerdtree-1037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d9e9e80a82f8405040ad96df70dee04edad15ec --- /dev/null +++ b/tasks/preservim__nerdtree-1037/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Enable events when closing NerdTree window. + +## Description + +### Description of Changes + + +This change allows Airline's autocommand to updated its statuslines. +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `51fc75efdb8a`. 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/preservim__nerdtree-1037/solution/patch.diff b/tasks/preservim__nerdtree-1037/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c7ac0957f354242467bd883d7fee0b7a08a2bf07 --- /dev/null +++ b/tasks/preservim__nerdtree-1037/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e8b4290..1885f1c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.3... ++- **.2**: Enable events when closing NerdTree window. [#1037](https://github.com/scrooloose/nerdtree/pull/1037) + - **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 705d4f9..eb305d6 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -52,7 +52,7 @@ function! s:NERDTree.Close() + endif + + call nerdtree#exec(s:NERDTree.GetWinNum() . " wincmd w", 1) +- call nerdtree#exec("close", 1) ++ call nerdtree#exec("close", 0) + if l:useWinId + call nerdtree#exec("call win_gotoid(" . l:activeBufOrWin . ")", 0) + else diff --git a/tasks/preservim__nerdtree-1037/solution/solve.sh b/tasks/preservim__nerdtree-1037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1037/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/preservim__nerdtree-1037/task.toml b/tasks/preservim__nerdtree-1037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..db377c245b3acb8cf179a6454185cb2bf2e2c5aa --- /dev/null +++ b/tasks/preservim__nerdtree-1037/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1037" +description = "Enable events when closing NerdTree window." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "51fc75efdb8ac58c853492c3f61d854f65ed78ec" +reference = "https://github.com/preservim/nerdtree/pull/1037" +source_access = "auto" +built_at = "2026-11-16T16:10:02.458655+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c04f01b74b8cd9f01ad9ee8404be60906f70e9270669a69b6b1ad4ebf61276f8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-09-13T14:49:27Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/nerdtree.vim", +] +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:02.565728+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e67197a28b5a54178a29be90138332af59979d6d12740fcb93f0e592e11e08cc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1037/tests/capture.py b/tasks/preservim__nerdtree-1037/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1037/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/preservim__nerdtree-1037/tests/instruction.md b/tasks/preservim__nerdtree-1037/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d9e9e80a82f8405040ad96df70dee04edad15ec --- /dev/null +++ b/tasks/preservim__nerdtree-1037/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Enable events when closing NerdTree window. + +## Description + +### Description of Changes + + +This change allows Airline's autocommand to updated its statuslines. +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `51fc75efdb8a`. 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/preservim__nerdtree-1037/tests/oracle.patch b/tasks/preservim__nerdtree-1037/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c7ac0957f354242467bd883d7fee0b7a08a2bf07 --- /dev/null +++ b/tasks/preservim__nerdtree-1037/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e8b4290..1885f1c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 5.3... ++- **.2**: Enable events when closing NerdTree window. [#1037](https://github.com/scrooloose/nerdtree/pull/1037) + - **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) + - **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 705d4f9..eb305d6 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -52,7 +52,7 @@ function! s:NERDTree.Close() + endif + + call nerdtree#exec(s:NERDTree.GetWinNum() . " wincmd w", 1) +- call nerdtree#exec("close", 1) ++ call nerdtree#exec("close", 0) + if l:useWinId + call nerdtree#exec("call win_gotoid(" . l:activeBufOrWin . ")", 0) + else diff --git a/tasks/preservim__nerdtree-1037/tests/test.sh b/tasks/preservim__nerdtree-1037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c13d9ff54148fc1de9a4121eeb428095aa7a181 --- /dev/null +++ b/tasks/preservim__nerdtree-1037/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 51fc75efdb8ac58c853492c3f61d854f65ed78ec > "$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/preservim__nerdtree-1037/tests/verifier.py b/tasks/preservim__nerdtree-1037/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1037/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/preservim__nerdtree-1038/environment/Dockerfile b/tasks/preservim__nerdtree-1038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ebcfb2f36495f781cc8e6eead329e3a89d261735 --- /dev/null +++ b/tasks/preservim__nerdtree-1038/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 60ec10b477eefc81eeafafa2a8c1b00046ee48fb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 60ec10b477eefc81eeafafa2a8c1b00046ee48fb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 60ec10b477eefc81eeafafa2a8c1b00046ee48fb \ + && 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/preservim__nerdtree-1038/instruction.md b/tasks/preservim__nerdtree-1038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61fac6ac9d724824d0ad7e66a37dbf4f73ed2b80 --- /dev/null +++ b/tasks/preservim__nerdtree-1038/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Fix (p)ath not displaying in the minimal menu + +## Description + +### Description of Changes + +The ‘copy (p)ath to clipboard’ menu item was added +recently in this pull request: + + +However, this caused the NERDTreeMinimalMenu to +display ‘copy’ instead of ‘(p)ath’ because it was +simply using the first word of the item’s text. + +This change fixes that bug by using a regex to +pick out the first word beginning with ‘(’ + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60ec10b477ee`. 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/preservim__nerdtree-1038/solution/patch.diff b/tasks/preservim__nerdtree-1038/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6232a09eb8ac213cf1e38a4a7c9dd37e76212e2d --- /dev/null +++ b/tasks/preservim__nerdtree-1038/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 05e82d9..874c09d 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -62,9 +62,10 @@ function! s:MenuController._echoPrompt() + + if self.isMinimal() + let selection = self.menuItems[self.selection].text ++ let keyword = matchstr(selection, "\([^ ]*") + + let shortcuts = map(copy(self.menuItems), "v:val['shortcut']") +- let shortcuts[self.selection] = " " . split(selection)[0] . " " ++ let shortcuts[self.selection] = " " . keyword . " " + + echo "Menu: [" . join(shortcuts, ",") . "] (" . navHelp . " or shortcut): " + else diff --git a/tasks/preservim__nerdtree-1038/solution/solve.sh b/tasks/preservim__nerdtree-1038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1038/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/preservim__nerdtree-1038/task.toml b/tasks/preservim__nerdtree-1038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c227b6a6a0a2a6e8a46ea4f519a4d0905a5445f2 --- /dev/null +++ b/tasks/preservim__nerdtree-1038/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1038" +description = "Fix (p)ath not displaying in the minimal menu" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "60ec10b477eefc81eeafafa2a8c1b00046ee48fb" +reference = "https://github.com/preservim/nerdtree/pull/1038" +source_access = "auto" +built_at = "2026-11-16T16:10:02.457253+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dfa472d922deb5e588887a62c336b69c7cf15f86367855ffd11a8be30643f1e9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-09-15T18:41:27Z" +diff_format = "unified" +context_files = [ + "lib/nerdtree/menu_controller.vim", +] +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:02.566269+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ef644ddf911d1484ae7f459b4cfa2e5fda400bfb08096fce0dfc6b688a06aa65" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1038/tests/capture.py b/tasks/preservim__nerdtree-1038/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1038/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/preservim__nerdtree-1038/tests/instruction.md b/tasks/preservim__nerdtree-1038/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61fac6ac9d724824d0ad7e66a37dbf4f73ed2b80 --- /dev/null +++ b/tasks/preservim__nerdtree-1038/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Fix (p)ath not displaying in the minimal menu + +## Description + +### Description of Changes + +The ‘copy (p)ath to clipboard’ menu item was added +recently in this pull request: + + +However, this caused the NERDTreeMinimalMenu to +display ‘copy’ instead of ‘(p)ath’ because it was +simply using the first word of the item’s text. + +This change fixes that bug by using a regex to +pick out the first word beginning with ‘(’ + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60ec10b477ee`. 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/preservim__nerdtree-1038/tests/oracle.patch b/tasks/preservim__nerdtree-1038/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6232a09eb8ac213cf1e38a4a7c9dd37e76212e2d --- /dev/null +++ b/tasks/preservim__nerdtree-1038/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index 05e82d9..874c09d 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -62,9 +62,10 @@ function! s:MenuController._echoPrompt() + + if self.isMinimal() + let selection = self.menuItems[self.selection].text ++ let keyword = matchstr(selection, "\([^ ]*") + + let shortcuts = map(copy(self.menuItems), "v:val['shortcut']") +- let shortcuts[self.selection] = " " . split(selection)[0] . " " ++ let shortcuts[self.selection] = " " . keyword . " " + + echo "Menu: [" . join(shortcuts, ",") . "] (" . navHelp . " or shortcut): " + else diff --git a/tasks/preservim__nerdtree-1038/tests/test.sh b/tasks/preservim__nerdtree-1038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed8a146d0aa0e8b64372b007c9bb7f0a8d8a1fc1 --- /dev/null +++ b/tasks/preservim__nerdtree-1038/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 60ec10b477eefc81eeafafa2a8c1b00046ee48fb > "$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/preservim__nerdtree-1038/tests/verifier.py b/tasks/preservim__nerdtree-1038/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1038/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/preservim__nerdtree-1040/environment/Dockerfile b/tasks/preservim__nerdtree-1040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..052d4f523076508e1674ac860949c2216b26b919 --- /dev/null +++ b/tasks/preservim__nerdtree-1040/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bd744eab8df5730db167a26486bc9afde46c4046 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bd744eab8df5730db167a26486bc9afde46c4046 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bd744eab8df5730db167a26486bc9afde46c4046 \ + && 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/preservim__nerdtree-1040/instruction.md b/tasks/preservim__nerdtree-1040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..143345662cda2e782c05ed81e4abdd73baffbc70 --- /dev/null +++ b/tasks/preservim__nerdtree-1040/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Reintroduce necessary variable mistakenly removed. + +## Description + +### Description of Changes + + +`let splitMode =...` was removed, but is still needed, in the 6.0.0 release. This PR adds it back in. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd744eab8df5`. 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/preservim__nerdtree-1040/solution/patch.diff b/tasks/preservim__nerdtree-1040/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8230e8fdbce0b367a9bb0373ad295c3f3aa14b7f --- /dev/null +++ b/tasks/preservim__nerdtree-1040/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index b103b30..69ea21b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,17 +1,18 @@ + # Change Log + + #### 6.0... +-- **.0**: Make the behavior of window splits consistent [#1035](https://github.com/scrooloose/nerdtree/pull/1035) ++- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) ++- **.0**: Make the behavior of window splits consistent (PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) + #### 5.3... +-- **.3**: Fix (p)ath not displaying in the minimal menu [#1038](https://github.com/scrooloose/nerdtree/pull/1038) +-- **.2**: Enable events when closing NerdTree window. [#1037](https://github.com/scrooloose/nerdtree/pull/1037) +-- **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) +-- **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) ++- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/scrooloose/nerdtree/pull/1038) ++- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/scrooloose/nerdtree/pull/1037) ++- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/scrooloose/nerdtree/pull/1031) ++- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... +-- **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) ++- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/scrooloose/nerdtree/pull/1026) + - **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +-- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! [#1019](https://github.com/scrooloose/nerdtree/pull/1019) +-- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. [#1017](https://github.com/scrooloose/nerdtree/pull/1017) ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/scrooloose/nerdtree/pull/1019) ++- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/scrooloose/nerdtree/pull/1017) + - **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) + - **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/scrooloose/nerdtree/pull/1014) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index ffc7506..fa0c988 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -158,12 +158,13 @@ function! s:Opener._newSplit() + if onlyOneWin + let &splitright = (g:NERDTreeWinPos ==# "left") + endif ++ " If only one window (ie. NERDTree), split vertically instead. ++ let splitMode = onlyOneWin ? "vertical" : "" + + " Open the new window + try + call nerdtree#exec('wincmd p', 1) +- " If only one window (ie. NERDTree), split vertically instead. +- call nerdtree#exec(onlyOneWin ? "vertical split" : "split",1) ++ call nerdtree#exec(splitMode . " split",1) + catch /^Vim\%((\a\+)\)\=:E37/ + call g:NERDTree.CursorToTreeWin() + throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self._path.str() ." is already open and modified." diff --git a/tasks/preservim__nerdtree-1040/solution/solve.sh b/tasks/preservim__nerdtree-1040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1040/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/preservim__nerdtree-1040/task.toml b/tasks/preservim__nerdtree-1040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52d8000254a251cc53785bb94278f740867280c3 --- /dev/null +++ b/tasks/preservim__nerdtree-1040/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1040" +description = "Reintroduce necessary variable mistakenly removed." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "bd744eab8df5730db167a26486bc9afde46c4046" +reference = "https://github.com/preservim/nerdtree/pull/1040" +source_access = "auto" +built_at = "2026-11-16T16:10:02.455914+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b411b13a7164e4bf888dfb27915ffde372df982c1077a81dbc3980b64af1b78d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-09-26T12:47:37Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/opener.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 22 +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:02.566778+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c55d35fb7da4a89c396f4c0524ed07886abffa9f58605dea735017f40617ac43" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1040/tests/capture.py b/tasks/preservim__nerdtree-1040/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1040/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/preservim__nerdtree-1040/tests/instruction.md b/tasks/preservim__nerdtree-1040/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..143345662cda2e782c05ed81e4abdd73baffbc70 --- /dev/null +++ b/tasks/preservim__nerdtree-1040/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Reintroduce necessary variable mistakenly removed. + +## Description + +### Description of Changes + + +`let splitMode =...` was removed, but is still needed, in the 6.0.0 release. This PR adds it back in. + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bd744eab8df5`. 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/preservim__nerdtree-1040/tests/oracle.patch b/tasks/preservim__nerdtree-1040/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8230e8fdbce0b367a9bb0373ad295c3f3aa14b7f --- /dev/null +++ b/tasks/preservim__nerdtree-1040/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index b103b30..69ea21b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,17 +1,18 @@ + # Change Log + + #### 6.0... +-- **.0**: Make the behavior of window splits consistent [#1035](https://github.com/scrooloose/nerdtree/pull/1035) ++- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) ++- **.0**: Make the behavior of window splits consistent (PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) + #### 5.3... +-- **.3**: Fix (p)ath not displaying in the minimal menu [#1038](https://github.com/scrooloose/nerdtree/pull/1038) +-- **.2**: Enable events when closing NerdTree window. [#1037](https://github.com/scrooloose/nerdtree/pull/1037) +-- **.1**: Fix the `e` key mapping to use netrw if desired [#1031](https://github.com/scrooloose/nerdtree/pull/1031) +-- **.0**: Add file extension and size to sorting capabilities [#1029](https://github.com/scrooloose/nerdtree/pull/1029) ++- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/scrooloose/nerdtree/pull/1038) ++- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/scrooloose/nerdtree/pull/1037) ++- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/scrooloose/nerdtree/pull/1031) ++- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/scrooloose/nerdtree/pull/1029) + #### 5.2... +-- **.9**: Suppress events for intermediate window/tab/buffer changes [#1026](https://github.com/scrooloose/nerdtree/pull/1026) ++- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/scrooloose/nerdtree/pull/1026) + - **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +-- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! [#1019](https://github.com/scrooloose/nerdtree/pull/1019) +-- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. [#1017](https://github.com/scrooloose/nerdtree/pull/1017) ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/scrooloose/nerdtree/pull/1019) ++- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/scrooloose/nerdtree/pull/1017) + - **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) + - **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) + - **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/scrooloose/nerdtree/pull/1014) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index ffc7506..fa0c988 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -158,12 +158,13 @@ function! s:Opener._newSplit() + if onlyOneWin + let &splitright = (g:NERDTreeWinPos ==# "left") + endif ++ " If only one window (ie. NERDTree), split vertically instead. ++ let splitMode = onlyOneWin ? "vertical" : "" + + " Open the new window + try + call nerdtree#exec('wincmd p', 1) +- " If only one window (ie. NERDTree), split vertically instead. +- call nerdtree#exec(onlyOneWin ? "vertical split" : "split",1) ++ call nerdtree#exec(splitMode . " split",1) + catch /^Vim\%((\a\+)\)\=:E37/ + call g:NERDTree.CursorToTreeWin() + throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self._path.str() ." is already open and modified." diff --git a/tasks/preservim__nerdtree-1040/tests/test.sh b/tasks/preservim__nerdtree-1040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d419fb1b3f918a7257891a9219c6191b80f961f --- /dev/null +++ b/tasks/preservim__nerdtree-1040/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 bd744eab8df5730db167a26486bc9afde46c4046 > "$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/preservim__nerdtree-1040/tests/verifier.py b/tasks/preservim__nerdtree-1040/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1040/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/preservim__nerdtree-1043/environment/Dockerfile b/tasks/preservim__nerdtree-1043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8d60f1f9f226432a0e5697028d2a8b06009869a2 --- /dev/null +++ b/tasks/preservim__nerdtree-1043/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 496b61ead1acd80128164cce5c2ff8e89c42ded2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 496b61ead1acd80128164cce5c2ff8e89c42ded2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 496b61ead1acd80128164cce5c2ff8e89c42ded2 \ + && 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/preservim__nerdtree-1043/instruction.md b/tasks/preservim__nerdtree-1043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b28bde1bfedeb5ab87d5db66cc242070112da5ca --- /dev/null +++ b/tasks/preservim__nerdtree-1043/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** If file path doesn't exist, :NERDTreeFind its parent directory instead. + +## Description + +This happens in the following scenario: +``` +:edit path/new_file +:NERDTreeFind +``` +Instead of an error message about an **invalid path**, this change will +now find the parent directory instead. It will not work if the new file +is **path/new_folder/new_file**, and that's OK because even vim itself +cannot handle both the new folder and the new file; `:w` won't create +the new folder. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `496b61ead1ac`. 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/preservim__nerdtree-1043/solution/patch.diff b/tasks/preservim__nerdtree-1043/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..87066cfefa33b7ac83e9a2cf9dfcd1bf8e0d68ab --- /dev/null +++ b/tasks/preservim__nerdtree-1043/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index dbcdfc8..bcb99c6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 6.1... ++- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... + - **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) + - **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index b82e791..4ba5b05 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,6 +284,9 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') ++ if !filereadable(l:pathStr) ++ let l:pathStr = fnamemodify(l:pathStr, ':h') ++ endif + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') diff --git a/tasks/preservim__nerdtree-1043/solution/solve.sh b/tasks/preservim__nerdtree-1043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1043/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/preservim__nerdtree-1043/task.toml b/tasks/preservim__nerdtree-1043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..685dd45c0bc2e042c8904567182446717c56e74f --- /dev/null +++ b/tasks/preservim__nerdtree-1043/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1043" +description = "If file path doesn't exist, :NERDTreeFind its parent directory instead." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "496b61ead1acd80128164cce5c2ff8e89c42ded2" +reference = "https://github.com/preservim/nerdtree/pull/1043" +source_access = "auto" +built_at = "2026-11-16T16:10:02.397702+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ece8f288a929eddf30599e4a59e2cd846adc95b3ebc63906d28674ac72c51e79" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-09-29T15:28:59Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", +] +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:02.567278+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9594da67d16cb2a14b2cd8659dd5597b5b901b070099a0bf95d343f86a1b1b25" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1043/tests/capture.py b/tasks/preservim__nerdtree-1043/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1043/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/preservim__nerdtree-1043/tests/instruction.md b/tasks/preservim__nerdtree-1043/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b28bde1bfedeb5ab87d5db66cc242070112da5ca --- /dev/null +++ b/tasks/preservim__nerdtree-1043/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** If file path doesn't exist, :NERDTreeFind its parent directory instead. + +## Description + +This happens in the following scenario: +``` +:edit path/new_file +:NERDTreeFind +``` +Instead of an error message about an **invalid path**, this change will +now find the parent directory instead. It will not work if the new file +is **path/new_folder/new_file**, and that's OK because even vim itself +cannot handle both the new folder and the new file; `:w` won't create +the new folder. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [x] `MINOR` version when you add functionality in a backwards-compatible manner + - [ ] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `496b61ead1ac`. 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/preservim__nerdtree-1043/tests/oracle.patch b/tasks/preservim__nerdtree-1043/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..87066cfefa33b7ac83e9a2cf9dfcd1bf8e0d68ab --- /dev/null +++ b/tasks/preservim__nerdtree-1043/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index dbcdfc8..bcb99c6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,5 +1,7 @@ + # Change Log + ++#### 6.1... ++- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... + - **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) + - **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index b82e791..4ba5b05 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,6 +284,9 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') ++ if !filereadable(l:pathStr) ++ let l:pathStr = fnamemodify(l:pathStr, ':h') ++ endif + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') diff --git a/tasks/preservim__nerdtree-1043/tests/test.sh b/tasks/preservim__nerdtree-1043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ac521f744321e7e3b1d04b91dcbc816426a6aa0 --- /dev/null +++ b/tasks/preservim__nerdtree-1043/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 496b61ead1acd80128164cce5c2ff8e89c42ded2 > "$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/preservim__nerdtree-1043/tests/verifier.py b/tasks/preservim__nerdtree-1043/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1043/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/preservim__nerdtree-1045/environment/Dockerfile b/tasks/preservim__nerdtree-1045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a10c1ce011ce5d269ca6dca03d32f4ce1f7d9e1c --- /dev/null +++ b/tasks/preservim__nerdtree-1045/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6318406f6606481b5e3a42a5754096063d996587 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6318406f6606481b5e3a42a5754096063d996587 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6318406f6606481b5e3a42a5754096063d996587 \ + && 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/preservim__nerdtree-1045/instruction.md b/tasks/preservim__nerdtree-1045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4f4feaad89a5e8c84a7074b7e17d70eb7da6007 --- /dev/null +++ b/tasks/preservim__nerdtree-1045/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Catch errors when trying to read CHANGELOG.md. + +## Description + +The ArchLinux package +(https://www.archlinux.org/packages/community/any/vim-nerdtree/) puts +this file in the wrong location. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6318406f6606`. 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/preservim__nerdtree-1045/solution/patch.diff b/tasks/preservim__nerdtree-1045/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4488c67b926a6c018a9268200a858e64ee93cb5d --- /dev/null +++ b/tasks/preservim__nerdtree-1045/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index bcb99c6..8795c6b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... + - **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 61adb9c..76c076e 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -10,17 +10,20 @@ let s:rootNERDTreePath = resolve(expand(":p:h:h")) + " change log is shown for the current version; otherwise, only the version + " number is shown. + function! nerdtree#version(...) +- let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) + let l:text = 'Unknown' +- let l:line = 0 +- while l:line <= len(l:changelog) +- if l:changelog[l:line] =~ '\d\+\.\d\+' +- let l:text = substitute(l:changelog[l:line], '.*\(\d\+.\d\+\).*', '\1', '') +- let l:text .= substitute(l:changelog[l:line+1], '^.\{-}\(\.\d\+\).\{-}:\(.*\)', a:0>0 ? '\1:\2' : '\1', '') +- break +- endif +- let l:line += 1 +- endwhile ++ try ++ let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) ++ let l:line = 0 ++ while l:line <= len(l:changelog) ++ if l:changelog[l:line] =~ '\d\+\.\d\+' ++ let l:text = substitute(l:changelog[l:line], '.*\(\d\+.\d\+\).*', '\1', '') ++ let l:text .= substitute(l:changelog[l:line+1], '^.\{-}\(\.\d\+\).\{-}:\(.*\)', a:0>0 ? '\1:\2' : '\1', '') ++ break ++ endif ++ let l:line += 1 ++ endwhile ++ catch ++ endtry + return l:text + endfunction + diff --git a/tasks/preservim__nerdtree-1045/solution/solve.sh b/tasks/preservim__nerdtree-1045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1045/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/preservim__nerdtree-1045/task.toml b/tasks/preservim__nerdtree-1045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c66d25ddecdd9a83295a285d0b9cbc3f47b82c93 --- /dev/null +++ b/tasks/preservim__nerdtree-1045/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1045" +description = "Catch errors when trying to read CHANGELOG.md." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "6318406f6606481b5e3a42a5754096063d996587" +reference = "https://github.com/preservim/nerdtree/pull/1045" +source_access = "auto" +built_at = "2026-11-16T16:10:02.454578+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:859d758f461bc148230803534a6591e750e2da2bf0b011b67188736a30df4222" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-10-01T13:17:33Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 24 +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:02.567793+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f213cb7b3282e17c7761dff42594bb36c71ff6bcf36f06b7064b6a988dc27da8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1045/tests/capture.py b/tasks/preservim__nerdtree-1045/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1045/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/preservim__nerdtree-1045/tests/instruction.md b/tasks/preservim__nerdtree-1045/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4f4feaad89a5e8c84a7074b7e17d70eb7da6007 --- /dev/null +++ b/tasks/preservim__nerdtree-1045/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Catch errors when trying to read CHANGELOG.md. + +## Description + +The ArchLinux package +(https://www.archlinux.org/packages/community/any/vim-nerdtree/) puts +this file in the wrong location. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6318406f6606`. 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/preservim__nerdtree-1045/tests/oracle.patch b/tasks/preservim__nerdtree-1045/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4488c67b926a6c018a9268200a858e64ee93cb5d --- /dev/null +++ b/tasks/preservim__nerdtree-1045/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index bcb99c6..8795c6b 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... + - **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 61adb9c..76c076e 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -10,17 +10,20 @@ let s:rootNERDTreePath = resolve(expand(":p:h:h")) + " change log is shown for the current version; otherwise, only the version + " number is shown. + function! nerdtree#version(...) +- let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) + let l:text = 'Unknown' +- let l:line = 0 +- while l:line <= len(l:changelog) +- if l:changelog[l:line] =~ '\d\+\.\d\+' +- let l:text = substitute(l:changelog[l:line], '.*\(\d\+.\d\+\).*', '\1', '') +- let l:text .= substitute(l:changelog[l:line+1], '^.\{-}\(\.\d\+\).\{-}:\(.*\)', a:0>0 ? '\1:\2' : '\1', '') +- break +- endif +- let l:line += 1 +- endwhile ++ try ++ let l:changelog = readfile(join([s:rootNERDTreePath, "CHANGELOG.md"], nerdtree#slash())) ++ let l:line = 0 ++ while l:line <= len(l:changelog) ++ if l:changelog[l:line] =~ '\d\+\.\d\+' ++ let l:text = substitute(l:changelog[l:line], '.*\(\d\+.\d\+\).*', '\1', '') ++ let l:text .= substitute(l:changelog[l:line+1], '^.\{-}\(\.\d\+\).\{-}:\(.*\)', a:0>0 ? '\1:\2' : '\1', '') ++ break ++ endif ++ let l:line += 1 ++ endwhile ++ catch ++ endtry + return l:text + endfunction + diff --git a/tasks/preservim__nerdtree-1045/tests/test.sh b/tasks/preservim__nerdtree-1045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..64645c853aee9e04b4032396780e77db088f2d2f --- /dev/null +++ b/tasks/preservim__nerdtree-1045/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 6318406f6606481b5e3a42a5754096063d996587 > "$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/preservim__nerdtree-1045/tests/verifier.py b/tasks/preservim__nerdtree-1045/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1045/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/preservim__nerdtree-1047/environment/Dockerfile b/tasks/preservim__nerdtree-1047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d8581c4ad9bfae5f1e1e297a36cc092814c1301e --- /dev/null +++ b/tasks/preservim__nerdtree-1047/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2d639b70e73ecf3f62884a578fe5e5937e6d8a92 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2d639b70e73ecf3f62884a578fe5e5937e6d8a92 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2d639b70e73ecf3f62884a578fe5e5937e6d8a92 \ + && 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/preservim__nerdtree-1047/instruction.md b/tasks/preservim__nerdtree-1047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21abacf553ba26abddc7ec78ad18f1f96b9d3e84 --- /dev/null +++ b/tasks/preservim__nerdtree-1047/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Wrap saveScreenState's statements in a try-catch block. + +## Description + +If you're in NERDTree, and you press : to open a command line, and then +press Ctrl+F to open the [Command Line] window, you will see errors +related to switching windows while in this function. (Those commands are +not allowed while in the [Command Line] window.) The try-catch block +handles the errors, preventing their being displayed. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d639b70e73e`. 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/preservim__nerdtree-1047/solution/patch.diff b/tasks/preservim__nerdtree-1047/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..422218ae9d879b30936fd39d63d9459ac891afcf --- /dev/null +++ b/tasks/preservim__nerdtree-1047/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8795c6b..239ce81 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index d384071..5e8b3b6 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -355,12 +355,15 @@ endfunction + " scroll position + function! s:UI.saveScreenState() + let win = winnr() +- call g:NERDTree.CursorToTreeWin() + let self._screenState = {} +- let self._screenState['oldPos'] = getpos(".") +- let self._screenState['oldTopLine'] = line("w0") +- let self._screenState['oldWindowSize']= winwidth("") +- call nerdtree#exec(win . "wincmd w", 1) ++ try ++ call g:NERDTree.CursorToTreeWin() ++ let self._screenState['oldPos'] = getpos(".") ++ let self._screenState['oldTopLine'] = line("w0") ++ let self._screenState['oldWindowSize']= winwidth("") ++ call nerdtree#exec(win . "wincmd w", 1) ++ catch ++ endtry + endfunction + + " FUNCTION: s:UI.setShowHidden(val) {{{1 diff --git a/tasks/preservim__nerdtree-1047/solution/solve.sh b/tasks/preservim__nerdtree-1047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1047/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/preservim__nerdtree-1047/task.toml b/tasks/preservim__nerdtree-1047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d4d6e69bb4420945fbb01a7b463c67259a3e4a18 --- /dev/null +++ b/tasks/preservim__nerdtree-1047/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1047" +description = "Wrap saveScreenState's statements in a try-catch block." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "2d639b70e73ecf3f62884a578fe5e5937e6d8a92" +reference = "https://github.com/preservim/nerdtree/pull/1047" +source_access = "auto" +built_at = "2026-11-16T16:10:02.453219+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8e14914779b85976f68b47cd1c65c4b664ba4e46d17e2bad1c408e3cb5651a30" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-10-08T18:01:51Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/ui.vim", +] +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:02.568309+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:54248045d2e20a0b2908ef7945a3aa0784eb6857a699c5f4089a039289f9a958" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1047/tests/capture.py b/tasks/preservim__nerdtree-1047/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1047/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/preservim__nerdtree-1047/tests/instruction.md b/tasks/preservim__nerdtree-1047/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21abacf553ba26abddc7ec78ad18f1f96b9d3e84 --- /dev/null +++ b/tasks/preservim__nerdtree-1047/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** Wrap saveScreenState's statements in a try-catch block. + +## Description + +If you're in NERDTree, and you press : to open a command line, and then +press Ctrl+F to open the [Command Line] window, you will see errors +related to switching windows while in this function. (Those commands are +not allowed while in the [Command Line] window.) The try-catch block +handles the errors, preventing their being displayed. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d639b70e73e`. 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/preservim__nerdtree-1047/tests/oracle.patch b/tasks/preservim__nerdtree-1047/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..422218ae9d879b30936fd39d63d9459ac891afcf --- /dev/null +++ b/tasks/preservim__nerdtree-1047/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8795c6b..239ce81 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) + #### 6.0... +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index d384071..5e8b3b6 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -355,12 +355,15 @@ endfunction + " scroll position + function! s:UI.saveScreenState() + let win = winnr() +- call g:NERDTree.CursorToTreeWin() + let self._screenState = {} +- let self._screenState['oldPos'] = getpos(".") +- let self._screenState['oldTopLine'] = line("w0") +- let self._screenState['oldWindowSize']= winwidth("") +- call nerdtree#exec(win . "wincmd w", 1) ++ try ++ call g:NERDTree.CursorToTreeWin() ++ let self._screenState['oldPos'] = getpos(".") ++ let self._screenState['oldTopLine'] = line("w0") ++ let self._screenState['oldWindowSize']= winwidth("") ++ call nerdtree#exec(win . "wincmd w", 1) ++ catch ++ endtry + endfunction + + " FUNCTION: s:UI.setShowHidden(val) {{{1 diff --git a/tasks/preservim__nerdtree-1047/tests/test.sh b/tasks/preservim__nerdtree-1047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a73b7f13013ba12a736fe187307d5cf20b1729ad --- /dev/null +++ b/tasks/preservim__nerdtree-1047/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 2d639b70e73ecf3f62884a578fe5e5937e6d8a92 > "$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/preservim__nerdtree-1047/tests/verifier.py b/tasks/preservim__nerdtree-1047/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1047/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/preservim__nerdtree-1048/environment/Dockerfile b/tasks/preservim__nerdtree-1048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..934e8044c100c442e6dc9d52a6e18ac43d9d4b72 --- /dev/null +++ b/tasks/preservim__nerdtree-1048/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4fe24d31569d365712b5fa95ac2688a68528b723 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4fe24d31569d365712b5fa95ac2688a68528b723 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4fe24d31569d365712b5fa95ac2688a68528b723 \ + && 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/preservim__nerdtree-1048/instruction.md b/tasks/preservim__nerdtree-1048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..422bc5b08b60c03fc009e711123ab21ac3a1f7fd --- /dev/null +++ b/tasks/preservim__nerdtree-1048/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Save/Set screen state also on WinLeave and WinEnter. + +## Description + +The particular use case here is when switching tabs with `gt` and the +NERDTrees have been mirrored. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fe24d31569d`. 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/preservim__nerdtree-1048/solution/patch.diff b/tasks/preservim__nerdtree-1048/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..335b276b20f19d117ac6c12c4eb791183e7b1cd4 --- /dev/null +++ b/tasks/preservim__nerdtree-1048/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 239ce81..d390cf6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) + - **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index a8e26d4..40609f0 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -170,10 +170,10 @@ call nerdtree#ui_glue#setupCommands() + "============================================================ + augroup NERDTree + "Save the cursor position whenever we close the nerd tree +- exec "autocmd BufLeave ". g:NERDTreeCreator.BufNamePrefix() ."* if g:NERDTree.IsOpen() | call b:NERDTree.ui.saveScreenState() | endif" ++ exec "autocmd BufLeave,WinLeave ". g:NERDTreeCreator.BufNamePrefix() ."* if g:NERDTree.IsOpen() | call b:NERDTree.ui.saveScreenState() | endif" + + "disallow insert mode in the NERDTree +- exec "autocmd BufEnter ". g:NERDTreeCreator.BufNamePrefix() ."* stopinsert" ++ exec "autocmd BufEnter,WinEnter ". g:NERDTreeCreator.BufNamePrefix() ."* stopinsert" + augroup END + + if g:NERDTreeHijackNetrw diff --git a/tasks/preservim__nerdtree-1048/solution/solve.sh b/tasks/preservim__nerdtree-1048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1048/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/preservim__nerdtree-1048/task.toml b/tasks/preservim__nerdtree-1048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..69f35594431e6402c80ae19e7848e7faa19e92af --- /dev/null +++ b/tasks/preservim__nerdtree-1048/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1048" +description = "Save/Set screen state also on WinLeave and WinEnter." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "4fe24d31569d365712b5fa95ac2688a68528b723" +reference = "https://github.com/preservim/nerdtree/pull/1048" +source_access = "auto" +built_at = "2026-11-16T16:10:02.414590+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dc05dbd8c4dc22a7b54a80faabe63a32c9114339cbbfcfd5379641b835100469" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-10-11T05:04:06Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "plugin/NERD_tree.vim", +] +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:02.568832+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:43a71fe6ce94b6e642f9f80eb0da3045f72b623189abb2839245c8fe74210cbf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1048/tests/capture.py b/tasks/preservim__nerdtree-1048/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1048/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/preservim__nerdtree-1048/tests/instruction.md b/tasks/preservim__nerdtree-1048/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..422bc5b08b60c03fc009e711123ab21ac3a1f7fd --- /dev/null +++ b/tasks/preservim__nerdtree-1048/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Save/Set screen state also on WinLeave and WinEnter. + +## Description + +The particular use case here is when switching tabs with `gt` and the +NERDTrees have been mirrored. + +### Description of Changes + + +--- +### New Version Info + +- [x] Derive a new version number. Increment the: + - [ ] `MAJOR` version when you make incompatible API changes + - [ ] `MINOR` version when you add functionality in a backwards-compatible manner + - [x] `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +- [x] Tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fe24d31569d`. 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/preservim__nerdtree-1048/tests/oracle.patch b/tasks/preservim__nerdtree-1048/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..335b276b20f19d117ac6c12c4eb791183e7b1cd4 --- /dev/null +++ b/tasks/preservim__nerdtree-1048/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 239ce81..d390cf6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -1,6 +1,7 @@ + # Change Log + + #### 6.1... ++- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) + - **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) + - **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index a8e26d4..40609f0 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -170,10 +170,10 @@ call nerdtree#ui_glue#setupCommands() + "============================================================ + augroup NERDTree + "Save the cursor position whenever we close the nerd tree +- exec "autocmd BufLeave ". g:NERDTreeCreator.BufNamePrefix() ."* if g:NERDTree.IsOpen() | call b:NERDTree.ui.saveScreenState() | endif" ++ exec "autocmd BufLeave,WinLeave ". g:NERDTreeCreator.BufNamePrefix() ."* if g:NERDTree.IsOpen() | call b:NERDTree.ui.saveScreenState() | endif" + + "disallow insert mode in the NERDTree +- exec "autocmd BufEnter ". g:NERDTreeCreator.BufNamePrefix() ."* stopinsert" ++ exec "autocmd BufEnter,WinEnter ". g:NERDTreeCreator.BufNamePrefix() ."* stopinsert" + augroup END + + if g:NERDTreeHijackNetrw diff --git a/tasks/preservim__nerdtree-1048/tests/test.sh b/tasks/preservim__nerdtree-1048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1e7066131ed7ef24f83ffeba5d6f47206b7a565 --- /dev/null +++ b/tasks/preservim__nerdtree-1048/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 4fe24d31569d365712b5fa95ac2688a68528b723 > "$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/preservim__nerdtree-1048/tests/verifier.py b/tasks/preservim__nerdtree-1048/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1048/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/preservim__nerdtree-1049/environment/Dockerfile b/tasks/preservim__nerdtree-1049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..89923a904b2c24d2228b2e4c7588637cd88323bf --- /dev/null +++ b/tasks/preservim__nerdtree-1049/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 926ff0ec038d2be0bf4ff3412d3c7144b5f82498 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 926ff0ec038d2be0bf4ff3412d3c7144b5f82498 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 926ff0ec038d2be0bf4ff3412d3c7144b5f82498 \ + && 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/preservim__nerdtree-1049/instruction.md b/tasks/preservim__nerdtree-1049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3607f0559ab93c47a9eec4d0a15a01fb2e01d67e --- /dev/null +++ b/tasks/preservim__nerdtree-1049/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Add VIM built-in package management to read me file + +## Description + +I am a new user in vim then I found this awesome plugin +The only problem was about installing it inside the new version of vim which I knew we don't have to use an external package manager, therefore, I just added the missing part in order to make it easier to install for the people like myself :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `926ff0ec038d`. 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/preservim__nerdtree-1049/solution/patch.diff b/tasks/preservim__nerdtree-1049/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..711593e76dce861ee462826bc95fb96ded954c27 --- /dev/null +++ b/tasks/preservim__nerdtree-1049/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 991da00..f79be93 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -9,6 +9,7 @@ + --> + + #### 6.1 ++- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) + - **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) + - **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) +diff --git a/README.markdown b/README.markdown +index 75b311a..a9ff7d1 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -17,6 +17,13 @@ included documentation. + Installation + ------------ + ++If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: ++ ++ git clone https://github.com/scrooloose/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++ vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q ++ ++Otherwise, these are some of the other options: ++ + #### [pathogen.vim](https://github.com/tpope/vim-pathogen) + + git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree diff --git a/tasks/preservim__nerdtree-1049/solution/solve.sh b/tasks/preservim__nerdtree-1049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1049/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/preservim__nerdtree-1049/task.toml b/tasks/preservim__nerdtree-1049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d4436c853a0a21a844396f39b931a9f2813daba2 --- /dev/null +++ b/tasks/preservim__nerdtree-1049/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1049" +description = "Add VIM built-in package management to read me file" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "926ff0ec038d2be0bf4ff3412d3c7144b5f82498" +reference = "https://github.com/preservim/nerdtree/pull/1049" +source_access = "auto" +built_at = "2026-11-16T16:10:02.451929+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:77968a6c7a48301b6c3ed95b16be1496ef92b43d89f2cf2812817add3d9e5d7e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-10-14T13:13:21Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", +] +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:02.569434+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9a42d3b4f2b71051cbd96108cc652060ea634f085c875f87d0ac25e6e5c124d2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1049/tests/capture.py b/tasks/preservim__nerdtree-1049/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1049/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/preservim__nerdtree-1049/tests/instruction.md b/tasks/preservim__nerdtree-1049/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3607f0559ab93c47a9eec4d0a15a01fb2e01d67e --- /dev/null +++ b/tasks/preservim__nerdtree-1049/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Add VIM built-in package management to read me file + +## Description + +I am a new user in vim then I found this awesome plugin +The only problem was about installing it inside the new version of vim which I knew we don't have to use an external package manager, therefore, I just added the missing part in order to make it easier to install for the people like myself :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `926ff0ec038d`. 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/preservim__nerdtree-1049/tests/oracle.patch b/tasks/preservim__nerdtree-1049/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..711593e76dce861ee462826bc95fb96ded954c27 --- /dev/null +++ b/tasks/preservim__nerdtree-1049/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 991da00..f79be93 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -9,6 +9,7 @@ + --> + + #### 6.1 ++- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) + - **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) + - **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) + - **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) +diff --git a/README.markdown b/README.markdown +index 75b311a..a9ff7d1 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -17,6 +17,13 @@ included documentation. + Installation + ------------ + ++If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: ++ ++ git clone https://github.com/scrooloose/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++ vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q ++ ++Otherwise, these are some of the other options: ++ + #### [pathogen.vim](https://github.com/tpope/vim-pathogen) + + git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree diff --git a/tasks/preservim__nerdtree-1049/tests/test.sh b/tasks/preservim__nerdtree-1049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..219b93e3897d770a8f9fd85045f236d7320041fd --- /dev/null +++ b/tasks/preservim__nerdtree-1049/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 926ff0ec038d2be0bf4ff3412d3c7144b5f82498 > "$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/preservim__nerdtree-1049/tests/verifier.py b/tasks/preservim__nerdtree-1049/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1049/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/preservim__nerdtree-1056/environment/Dockerfile b/tasks/preservim__nerdtree-1056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d50a0fdc34efed471d5486ff83b876e20759413e --- /dev/null +++ b/tasks/preservim__nerdtree-1056/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fec3e57ad23e4c268d07181d6afb858925b647a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fec3e57ad23e4c268d07181d6afb858925b647a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fec3e57ad23e4c268d07181d6afb858925b647a1 \ + && 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/preservim__nerdtree-1056/instruction.md b/tasks/preservim__nerdtree-1056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a5b5106d240b95109ced6e624ecc59c623d5adf --- /dev/null +++ b/tasks/preservim__nerdtree-1056/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Menu option, 'copy path to clipboard' is aware of VIM clipboard option + +## Description + +VIM noob here, so code might not be optimal. + +My setup is as follows. +NVIM v0.5.0-95-g2e14dffbb, Linux Mint 19.2. + +I have this in init.vim +```vim +set clipboard=unnamedplus +``` +This enables me to share clipboard between VIM and X clipboard. + +The problem is that the menu option in NERDTree copies the file path to the "* register. +This means I can't access the value in the X clipboard. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fec3e57ad23e`. 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/preservim__nerdtree-1056/solution/patch.diff b/tasks/preservim__nerdtree-1056/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fb6bbedfd282e7b80e20ae5ffc1ca774f446931e --- /dev/null +++ b/tasks/preservim__nerdtree-1056/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 0a5de8a..4167df0 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -369,7 +369,11 @@ endfunction + function! NERDTreeCopyPath() + let l:nodePath = g:NERDTreeFileNode.GetSelected().path.str() + if has("clipboard") +- let @* = l:nodePath ++ if &clipboard == "unnamedplus" ++ let @+ = l:nodePath ++ else ++ let @* = l:nodePath ++ endif + call nerdtree#echo("The path [" . l:nodePath . "] was copied to your clipboard.") + else + call nerdtree#echo("The full path is: " . l:nodePath) diff --git a/tasks/preservim__nerdtree-1056/solution/solve.sh b/tasks/preservim__nerdtree-1056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1056/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/preservim__nerdtree-1056/task.toml b/tasks/preservim__nerdtree-1056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dbc1c636ec3b5cc1d89fc9bdf37bc9df2517cb9c --- /dev/null +++ b/tasks/preservim__nerdtree-1056/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1056" +description = "Menu option, 'copy path to clipboard' is aware of VIM clipboard option" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "fec3e57ad23e4c268d07181d6afb858925b647a1" +reference = "https://github.com/preservim/nerdtree/pull/1056" +source_access = "auto" +built_at = "2026-11-16T16:10:02.449249+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:05423a353dbc1acdbea20abe95b322c0a4bd1569171205bf6fe3d95f0b1269a9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-11-13T13:58:43Z" +diff_format = "unified" +context_files = [ + "nerdtree_plugin/fs_menu.vim", +] +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:02.570024+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d05725afbace921b60acb6cbc89ce44b496b07c850e4f69c4088e2c6962ead78" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1056/tests/capture.py b/tasks/preservim__nerdtree-1056/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1056/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/preservim__nerdtree-1056/tests/instruction.md b/tasks/preservim__nerdtree-1056/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a5b5106d240b95109ced6e624ecc59c623d5adf --- /dev/null +++ b/tasks/preservim__nerdtree-1056/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Menu option, 'copy path to clipboard' is aware of VIM clipboard option + +## Description + +VIM noob here, so code might not be optimal. + +My setup is as follows. +NVIM v0.5.0-95-g2e14dffbb, Linux Mint 19.2. + +I have this in init.vim +```vim +set clipboard=unnamedplus +``` +This enables me to share clipboard between VIM and X clipboard. + +The problem is that the menu option in NERDTree copies the file path to the "* register. +This means I can't access the value in the X clipboard. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fec3e57ad23e`. 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/preservim__nerdtree-1056/tests/oracle.patch b/tasks/preservim__nerdtree-1056/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fb6bbedfd282e7b80e20ae5ffc1ca774f446931e --- /dev/null +++ b/tasks/preservim__nerdtree-1056/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 0a5de8a..4167df0 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -369,7 +369,11 @@ endfunction + function! NERDTreeCopyPath() + let l:nodePath = g:NERDTreeFileNode.GetSelected().path.str() + if has("clipboard") +- let @* = l:nodePath ++ if &clipboard == "unnamedplus" ++ let @+ = l:nodePath ++ else ++ let @* = l:nodePath ++ endif + call nerdtree#echo("The path [" . l:nodePath . "] was copied to your clipboard.") + else + call nerdtree#echo("The full path is: " . l:nodePath) diff --git a/tasks/preservim__nerdtree-1056/tests/test.sh b/tasks/preservim__nerdtree-1056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..87a610710fe344ff5cfa0a37d960e046e1b7cd9a --- /dev/null +++ b/tasks/preservim__nerdtree-1056/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 fec3e57ad23e4c268d07181d6afb858925b647a1 > "$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/preservim__nerdtree-1056/tests/verifier.py b/tasks/preservim__nerdtree-1056/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1056/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/preservim__nerdtree-1060/environment/Dockerfile b/tasks/preservim__nerdtree-1060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..013a3f7cab0df2c5405aa8b79a0dd24fe6f47d06 --- /dev/null +++ b/tasks/preservim__nerdtree-1060/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8d9b8dae67c5a6affbfd0304e0949ce9e79065ea 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8d9b8dae67c5a6affbfd0304e0949ce9e79065ea \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8d9b8dae67c5a6affbfd0304e0949ce9e79065ea \ + && 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/preservim__nerdtree-1060/instruction.md b/tasks/preservim__nerdtree-1060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1611e913025a71841f460dfed4c9656288673789 --- /dev/null +++ b/tasks/preservim__nerdtree-1060/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Add a NERDTreeToggleVCS command to the vcs plugin + +## Description + +### Description of Changes + +Added a new command NERDTreeToggleVCS to the vcs plugin that behaves exactly like NERDTreeToggle except attempt to root at VCS root when creating the tree for the first time. + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d9b8dae67c5`. 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/preservim__nerdtree-1060/solution/patch.diff b/tasks/preservim__nerdtree-1060/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9616be63192f9c3ecdd0017850a40cfb7403ce6a --- /dev/null +++ b/tasks/preservim__nerdtree-1060/solution/patch.diff @@ -0,0 +1,60 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ac12c9f..fe5d51a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -7,7 +7,8 @@ + in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> +- ++#### 6.3 ++- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/scrooloose/nerdtree/pull/1060) + #### 6.2 + - **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/scrooloose/nerdtree/pull/1056) + - **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 32b0b5d..e88a680 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -125,6 +125,14 @@ The following features and functionality are provided by the NERDTree: + again. If no NERDTree exists for this tab then this command acts the + same as the |:NERDTree| command. + ++:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* ++ Like |:NERDTreeToggle|, but searches up the directory tree to find the top of ++ the version control system repository, and roots the NERDTree there. It ++ works with Git, Subversion, Mercurial, Bazaar, and Darcs repositories. A ++ couple of examples: > ++ :NERDTreeToggleVCS /home/marty/nerdtree/doc (opens /home/marty/nerdtree) ++ :NERDTreeToggleVCS (opens root of repository containing CWD) ++ + :NERDTreeFocus *:NERDTreeFocus* + Opens (or reopens) the NERDTree if it is not currently visible; + otherwise, the cursor is moved to the already-open NERDTree. +diff --git a/nerdtree_plugin/vcs.vim b/nerdtree_plugin/vcs.vim +index c30579a..d9901b8 100644 +--- a/nerdtree_plugin/vcs.vim ++++ b/nerdtree_plugin/vcs.vim +@@ -11,6 +11,7 @@ + " + " ============================================================================ + command! -n=? -complete=dir -bar NERDTreeVCS :call CreateTabTreeVCS('') ++command! -n=? -complete=dir -bar NERDTreeToggleVCS :call ToggleTabTreeVCS('') + + " FUNCTION: s:CreateTabTreeVCS(a:name) {{{1 + function! s:CreateTabTreeVCS(name) +@@ -19,6 +20,14 @@ function! s:CreateTabTreeVCS(name) + call g:NERDTreeCreator.createTabTree(empty(l:path) ? "" : l:path._str()) + endfunction + ++" FUNCTION: s:ToggleTabTreeVCS(a:name) {{{1 ++" Behaves the same as ToggleTabTree except roots directory at VCS root ++function! s:ToggleTabTreeVCS(name) ++ let l:path = g:NERDTreeCreator._pathForString(a:name) ++ let l:path = s:FindParentVCSRoot(l:path) ++ call g:NERDTreeCreator.toggleTabTree(empty(l:path) ? "" : l:path._str()) ++endfunction ++ + " FUNCTION: s:FindParentVCSRoot(a:path) {{{1 + " Finds the root version control system folder of the given path. If a:path is + " not part of a repository, return the original path. diff --git a/tasks/preservim__nerdtree-1060/solution/solve.sh b/tasks/preservim__nerdtree-1060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1060/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/preservim__nerdtree-1060/task.toml b/tasks/preservim__nerdtree-1060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68aecf63032fb5723957ef11f8931754c2a4ebc4 --- /dev/null +++ b/tasks/preservim__nerdtree-1060/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1060" +description = "Add a NERDTreeToggleVCS command to the vcs plugin" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "8d9b8dae67c5a6affbfd0304e0949ce9e79065ea" +reference = "https://github.com/preservim/nerdtree/pull/1060" +source_access = "auto" +built_at = "2026-11-16T16:10:02.447936+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:56d094083a102456bce5ea16c2909c754c8981ef9478beab4d24a9556b60a6d7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2019-11-22T16:26:26Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "doc/NERDTree.txt", + "nerdtree_plugin/vcs.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +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:02.570571+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:275c22da74f52bea9656e4b0c783fb3058024ef47ad8998b52bfa4dd07b07f9b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1060/tests/capture.py b/tasks/preservim__nerdtree-1060/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1060/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/preservim__nerdtree-1060/tests/instruction.md b/tasks/preservim__nerdtree-1060/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1611e913025a71841f460dfed4c9656288673789 --- /dev/null +++ b/tasks/preservim__nerdtree-1060/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Add a NERDTreeToggleVCS command to the vcs plugin + +## Description + +### Description of Changes + +Added a new command NERDTreeToggleVCS to the vcs plugin that behaves exactly like NERDTreeToggle except attempt to root at VCS root when creating the tree for the first time. + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d9b8dae67c5`. 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/preservim__nerdtree-1060/tests/oracle.patch b/tasks/preservim__nerdtree-1060/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9616be63192f9c3ecdd0017850a40cfb7403ce6a --- /dev/null +++ b/tasks/preservim__nerdtree-1060/tests/oracle.patch @@ -0,0 +1,60 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ac12c9f..fe5d51a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -7,7 +7,8 @@ + in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> +- ++#### 6.3 ++- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/scrooloose/nerdtree/pull/1060) + #### 6.2 + - **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/scrooloose/nerdtree/pull/1056) + - **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 32b0b5d..e88a680 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -125,6 +125,14 @@ The following features and functionality are provided by the NERDTree: + again. If no NERDTree exists for this tab then this command acts the + same as the |:NERDTree| command. + ++:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* ++ Like |:NERDTreeToggle|, but searches up the directory tree to find the top of ++ the version control system repository, and roots the NERDTree there. It ++ works with Git, Subversion, Mercurial, Bazaar, and Darcs repositories. A ++ couple of examples: > ++ :NERDTreeToggleVCS /home/marty/nerdtree/doc (opens /home/marty/nerdtree) ++ :NERDTreeToggleVCS (opens root of repository containing CWD) ++ + :NERDTreeFocus *:NERDTreeFocus* + Opens (or reopens) the NERDTree if it is not currently visible; + otherwise, the cursor is moved to the already-open NERDTree. +diff --git a/nerdtree_plugin/vcs.vim b/nerdtree_plugin/vcs.vim +index c30579a..d9901b8 100644 +--- a/nerdtree_plugin/vcs.vim ++++ b/nerdtree_plugin/vcs.vim +@@ -11,6 +11,7 @@ + " + " ============================================================================ + command! -n=? -complete=dir -bar NERDTreeVCS :call CreateTabTreeVCS('') ++command! -n=? -complete=dir -bar NERDTreeToggleVCS :call ToggleTabTreeVCS('') + + " FUNCTION: s:CreateTabTreeVCS(a:name) {{{1 + function! s:CreateTabTreeVCS(name) +@@ -19,6 +20,14 @@ function! s:CreateTabTreeVCS(name) + call g:NERDTreeCreator.createTabTree(empty(l:path) ? "" : l:path._str()) + endfunction + ++" FUNCTION: s:ToggleTabTreeVCS(a:name) {{{1 ++" Behaves the same as ToggleTabTree except roots directory at VCS root ++function! s:ToggleTabTreeVCS(name) ++ let l:path = g:NERDTreeCreator._pathForString(a:name) ++ let l:path = s:FindParentVCSRoot(l:path) ++ call g:NERDTreeCreator.toggleTabTree(empty(l:path) ? "" : l:path._str()) ++endfunction ++ + " FUNCTION: s:FindParentVCSRoot(a:path) {{{1 + " Finds the root version control system folder of the given path. If a:path is + " not part of a repository, return the original path. diff --git a/tasks/preservim__nerdtree-1060/tests/test.sh b/tasks/preservim__nerdtree-1060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6db99802bcb07749ab58117f6ad8d6f79fbfe6cb --- /dev/null +++ b/tasks/preservim__nerdtree-1060/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 8d9b8dae67c5a6affbfd0304e0949ce9e79065ea > "$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/preservim__nerdtree-1060/tests/verifier.py b/tasks/preservim__nerdtree-1060/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1060/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/preservim__nerdtree-1072/environment/Dockerfile b/tasks/preservim__nerdtree-1072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a05e42427e116f49682f05f4aa5fbaf838a49f66 --- /dev/null +++ b/tasks/preservim__nerdtree-1072/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97fb849a29d74a9cceeca92472f770d81473c780 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97fb849a29d74a9cceeca92472f770d81473c780 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97fb849a29d74a9cceeca92472f770d81473c780 \ + && 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/preservim__nerdtree-1072/instruction.md b/tasks/preservim__nerdtree-1072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..990445840bca255ea772a70937efccc09146aa88 --- /dev/null +++ b/tasks/preservim__nerdtree-1072/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update links to repository with new org namespace + +## Description + +This should be a no-op as far as the plugin is concerned. I don't know what your changelog protocol is for things like this so I didn't enter one. Let me know if I should. + +These links are not broken yet, but someday they might and particularly for people cloning the repository or adding it to their plugin managers it would be nice if they got the canonical location in the first go. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97fb849a29d7`. 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/preservim__nerdtree-1072/solution/patch.diff b/tasks/preservim__nerdtree-1072/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..119f753934f1f48854cbda63f8cdbeb031db76de --- /dev/null +++ b/tasks/preservim__nerdtree-1072/solution/patch.diff @@ -0,0 +1,384 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index cec006c..f052a2c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -9,151 +9,151 @@ + --> + #### 6.4 + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) +-- **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/scrooloose/nerdtree/pull/1067) ++- **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/preservim/nerdtree/pull/1067) + #### 6.3 +-- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/scrooloose/nerdtree/pull/1060) ++- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/preservim/nerdtree/pull/1060) + #### 6.2 +-- **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/scrooloose/nerdtree/pull/1056) +-- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) ++- **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/preservim/nerdtree/pull/1056) ++- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/preservim/nerdtree/pull/1032) + #### 6.1 +-- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) +-- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) +-- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) +-- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) +-- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) ++- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/preservim/nerdtree/pull/1049) ++- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/preservim/nerdtree/pull/1048) ++- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/preservim/nerdtree/pull/1047) ++- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/preservim/nerdtree/pull/1045) ++- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/preservim/nerdtree/pull/1043) + #### 6.0 +-- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) +-- **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) ++- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/preservim/nerdtree/pull/1040) ++- **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/preservim/nerdtree/pull/1035) + #### 5.3 +-- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/scrooloose/nerdtree/pull/1038) +-- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/scrooloose/nerdtree/pull/1037) +-- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/scrooloose/nerdtree/pull/1031) +-- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/scrooloose/nerdtree/pull/1029) ++- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/preservim/nerdtree/pull/1038) ++- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/preservim/nerdtree/pull/1037) ++- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/preservim/nerdtree/pull/1031) ++- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/preservim/nerdtree/pull/1029) + #### 5.2 +-- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/scrooloose/nerdtree/pull/1026) +-- **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +-- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/scrooloose/nerdtree/pull/1019) +-- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/scrooloose/nerdtree/pull/1017) +-- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) +-- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) +-- **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/scrooloose/nerdtree/pull/1014) +-- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) [#1013](https://github.com/scrooloose/nerdtree/pull/1013) ++- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/preservim/nerdtree/pull/1026) ++- **.8**: Revert [#1019](https://github.com/preservim/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/preservim/nerdtree/pull/1021) ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/preservim/nerdtree/pull/1019) ++- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/preservim/nerdtree/pull/1017) ++- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/preservim/nerdtree/pull/1016) ++- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/preservim/nerdtree/pull/1015) ++- **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/preservim/nerdtree/pull/1014) ++- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) [#1013](https://github.com/preservim/nerdtree/pull/1013) + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) +-- **.0**: Expand functionality of `` mapping. (PhilRunninger) [#1011](https://github.com/scrooloose/nerdtree/pull/1011) ++- **.0**: Expand functionality of `` mapping. (PhilRunninger) [#1011](https://github.com/preservim/nerdtree/pull/1011) + #### 5.1 +-- **.3**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) [#1009](https://github.com/scrooloose/nerdtree/pull/1009) +-- **.2**: Fix NERDTree opening with the wrong size. (PhilRunninger) [#1008](https://github.com/scrooloose/nerdtree/pull/1008) +-- **.1**: Update Changelog and create PR Template (PhilRunninger) [#1007](https://github.com/scrooloose/nerdtree/pull/1007) ++- **.3**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) [#1009](https://github.com/preservim/nerdtree/pull/1009) ++- **.2**: Fix NERDTree opening with the wrong size. (PhilRunninger) [#1008](https://github.com/preservim/nerdtree/pull/1008) ++- **.1**: Update Changelog and create PR Template (PhilRunninger) [#1007](https://github.com/preservim/nerdtree/pull/1007) + - **.0**: Too many changes for one patch... +- - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) [#1005](https://github.com/scrooloose/nerdtree/pull/1005) +- - Add a "copy path to clipboard" menu option (PhilRunninger) [#1002](https://github.com/scrooloose/nerdtree/pull/1002) +- - Enable root refresh on "vim ." a different way than [#999](https://github.com/scrooloose/nerdtree/pull/999). (PhilRunninger) [#1001](https://github.com/scrooloose/nerdtree/pull/1001) +- - Fix refreshroot (PhilRunninger) [#999](https://github.com/scrooloose/nerdtree/pull/999) +- - Change version check to look for 703 not 730 (vhalis) [#994](https://github.com/scrooloose/nerdtree/pull/994) +- - Change minimum vim (PhilRunninger) [#991](https://github.com/scrooloose/nerdtree/pull/991) +- - Allow multi-character DirArrows (PhilRunninger) [#985](https://github.com/scrooloose/nerdtree/pull/985) +- - Remove redraw! while still clearing last message empty string. (PhilRunninger) [#979](https://github.com/scrooloose/nerdtree/pull/979) +- - fix `_initChildren` function value set to numChildrenCached error (terryding77) [#969](https://github.com/scrooloose/nerdtree/pull/969) +- - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) [#967](https://github.com/scrooloose/nerdtree/pull/967) +- - Remove the **Please wait... DONE** messages. (PhilRunninger) [#966](https://github.com/scrooloose/nerdtree/pull/966) +- - Smarter delimiter default (PhilRunninger) [#963](https://github.com/scrooloose/nerdtree/pull/963) +- - Update directory .vimdc readme example (spencerdcarlson) [#961](https://github.com/scrooloose/nerdtree/pull/961) +- - Preview bookmarks (PhilRunninger) [#956](https://github.com/scrooloose/nerdtree/pull/956) +- - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) [#955](https://github.com/scrooloose/nerdtree/pull/955) +- - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) [#954](https://github.com/scrooloose/nerdtree/pull/954) +- - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) [#952](https://github.com/scrooloose/nerdtree/pull/952) +- - Set a maximum window size when zooming. (PhilRunninger) [#950](https://github.com/scrooloose/nerdtree/pull/950) +- - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) [#949](https://github.com/scrooloose/nerdtree/pull/949) +- - Escape a backslash so it can be used in a key mapping. (PhilRunninger) [#948](https://github.com/scrooloose/nerdtree/pull/948) +- - Add a NERDTreeMinimalMenu feature (tuzz) [#938](https://github.com/scrooloose/nerdtree/pull/938) +- - fixed root path error for windows (zcodes) [#935](https://github.com/scrooloose/nerdtree/pull/935) +- - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) [#929](https://github.com/scrooloose/nerdtree/pull/929) +- - Document NERDTreeNodeDelimiter [#912](https://github.com/scrooloose/nerdtree/pull/912) (PhilRunninger) [#926](https://github.com/scrooloose/nerdtree/pull/926) +- - Allow modification of menu keybindings (Leandros) [#923](https://github.com/scrooloose/nerdtree/pull/923) +- - Add two more disqualifications for isCascadable(). (PhilRunninger) [#914](https://github.com/scrooloose/nerdtree/pull/914) +- - Allow highlighting more than one flag. (kristijanhusak) [#908](https://github.com/scrooloose/nerdtree/pull/908) +- - Support sorting files and directories by modification time. (PhilRunninger) [#901](https://github.com/scrooloose/nerdtree/pull/901) +- - Parse . and .. from path string with trailing slash. (PhilRunninger) [#899](https://github.com/scrooloose/nerdtree/pull/899) +- - Force sort to recalculate the cached sortKey. (PhilRunninger) [#898](https://github.com/scrooloose/nerdtree/pull/898) +- - Add NERDTreeRefreshRoot command (wgfm) [#897](https://github.com/scrooloose/nerdtree/pull/897) +- - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) [#896](https://github.com/scrooloose/nerdtree/pull/896) +- - Catch all errors, not just NERDTree errors. (PhilRunninger) [#894](https://github.com/scrooloose/nerdtree/pull/894) +- - Fix typo in help file (lvoisin) [#892](https://github.com/scrooloose/nerdtree/pull/892) +- - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) [#889](https://github.com/scrooloose/nerdtree/pull/889) +- - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) [#888](https://github.com/scrooloose/nerdtree/pull/888) +- - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) [#887](https://github.com/scrooloose/nerdtree/pull/887) +- - Fix the / motions, which currently fail with cascades (lifecrisis) [#886](https://github.com/scrooloose/nerdtree/pull/886) +- - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) [#882](https://github.com/scrooloose/nerdtree/pull/882) +- - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) [#878](https://github.com/scrooloose/nerdtree/pull/878) +- - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) [#877](https://github.com/scrooloose/nerdtree/pull/877) +- - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) [#875](https://github.com/scrooloose/nerdtree/pull/875) +- - Fix opening sub-directories that have commas in their name. (PhilRunninger) [#873](https://github.com/scrooloose/nerdtree/pull/873) +- - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) [#872](https://github.com/scrooloose/nerdtree/pull/872) +- - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) [#871](https://github.com/scrooloose/nerdtree/pull/871) +- - Unzoom NERDTree when opening a file (PhilRunninger) [#870](https://github.com/scrooloose/nerdtree/pull/870) +- - Support unusual characters in file and directory names (PhilRunninger) [#868](https://github.com/scrooloose/nerdtree/pull/868) +- - Reword renamed-buffer prompt to be more clear (aflock) [#867](https://github.com/scrooloose/nerdtree/pull/867) +- - Default to placing cursor on root when closing bookmark table (lifecrisis) [#866](https://github.com/scrooloose/nerdtree/pull/866) +- - Fix issues with sorting of nodes (PhilRunninger) [#856](https://github.com/scrooloose/nerdtree/pull/856) +- - Better OSX detection (bubba-h57) [#853](https://github.com/scrooloose/nerdtree/pull/853) +- - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) [#852](https://github.com/scrooloose/nerdtree/pull/852) +- - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) [#851](https://github.com/scrooloose/nerdtree/pull/851) +- - Add code to sort mappings in quickhelp (lifecrisis) [#849](https://github.com/scrooloose/nerdtree/pull/849) +- - Use ":clearjumps" in new NERDTree windows (lifecrisis) [#844](https://github.com/scrooloose/nerdtree/pull/844) +- - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) [#840](https://github.com/scrooloose/nerdtree/pull/840) +- - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) [#838](https://github.com/scrooloose/nerdtree/pull/838) +- - Make the NERDTree buffer writable when rendering it. (PhilRunninger) [#837](https://github.com/scrooloose/nerdtree/pull/837) +- - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) [#835](https://github.com/scrooloose/nerdtree/pull/835) +- - Replace strcharpart() with substitute() for backward compatibility (bravestarr) [#834](https://github.com/scrooloose/nerdtree/pull/834) +- - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) [#833](https://github.com/scrooloose/nerdtree/pull/833) +- - Clear output when NERDTree menu is aborted (lifecrisis) [#832](https://github.com/scrooloose/nerdtree/pull/832) +- - Display a path with multi-byte characters correctly when it is truncated (bravestarr) [#830](https://github.com/scrooloose/nerdtree/pull/830) +- - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) [#824](https://github.com/scrooloose/nerdtree/pull/824) +- - If node isn't open, count children on disk before deleting. (PhilRunninger) [#822](https://github.com/scrooloose/nerdtree/pull/822) +- - Add new variable g:NERDTreeRemoveFileCmd (kutsan) [#816](https://github.com/scrooloose/nerdtree/pull/816) +- - Use a better check for existence of the NERDTree buffer. (PhilRunninger) [#814](https://github.com/scrooloose/nerdtree/pull/814) +- - Fix focussing previous buffer when closing NERDTree (mrubli) [#801](https://github.com/scrooloose/nerdtree/pull/801) +- - Update the docs for "NERDTreeStatusline" (lifecrisis) [#796](https://github.com/scrooloose/nerdtree/pull/796) +- - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) [#795](https://github.com/scrooloose/nerdtree/pull/795) +- - Revert the bugfix from pull request [#785](https://github.com/scrooloose/nerdtree/pull/785) (lifecrisis) [#794](https://github.com/scrooloose/nerdtree/pull/794) +- - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) [#786](https://github.com/scrooloose/nerdtree/pull/786) +- - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) [#785](https://github.com/scrooloose/nerdtree/pull/785) +- - Add modelines (lifecrisis) [#782](https://github.com/scrooloose/nerdtree/pull/782) +- - Change the type of completion used by NERDTreeFind (lifecrisis) [#781](https://github.com/scrooloose/nerdtree/pull/781) +- - change NERDTreeFind with args (zhenyangze) [#778](https://github.com/scrooloose/nerdtree/pull/778) +- - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) [#777](https://github.com/scrooloose/nerdtree/pull/777) +- - remove useless substitute when `file =~# "/$"` (skyblueee) [#773](https://github.com/scrooloose/nerdtree/pull/773) +- - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) [#772](https://github.com/scrooloose/nerdtree/pull/772) +- - Make the "o" mapping consistent with "x" (lifecrisis) [#769](https://github.com/scrooloose/nerdtree/pull/769) +- - Fix a problem with the "x" handler (lifecrisis) [#768](https://github.com/scrooloose/nerdtree/pull/768) +- - Clean up the handler for the "x" mapping (lifecrisis) [#767](https://github.com/scrooloose/nerdtree/pull/767) +- - Revert change to tab opening method (lifecrisis) [#766](https://github.com/scrooloose/nerdtree/pull/766) +- - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) [#765](https://github.com/scrooloose/nerdtree/pull/765) +- - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) [#759](https://github.com/scrooloose/nerdtree/pull/759) +- - Update doc with already existing mapping variables (asnr) [#699](https://github.com/scrooloose/nerdtree/pull/699) +- - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) [#696](https://github.com/scrooloose/nerdtree/pull/696) +- - Correct NERDTreeIgnore pattern in doc (cntoplolicon) [#648](https://github.com/scrooloose/nerdtree/pull/648) +- - Remove empty segments when splitting path (sooth-sayer) [#574](https://github.com/scrooloose/nerdtree/pull/574) +- - Suppress autocmds less agressively (wincent) [#578](https://github.com/scrooloose/nerdtree/pull/578) [#691](https://github.com/scrooloose/nerdtree/pull/691) ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) [#1005](https://github.com/preservim/nerdtree/pull/1005) ++ - Add a "copy path to clipboard" menu option (PhilRunninger) [#1002](https://github.com/preservim/nerdtree/pull/1002) ++ - Enable root refresh on "vim ." a different way than [#999](https://github.com/preservim/nerdtree/pull/999). (PhilRunninger) [#1001](https://github.com/preservim/nerdtree/pull/1001) ++ - Fix refreshroot (PhilRunninger) [#999](https://github.com/preservim/nerdtree/pull/999) ++ - Change version check to look for 703 not 730 (vhalis) [#994](https://github.com/preservim/nerdtree/pull/994) ++ - Change minimum vim (PhilRunninger) [#991](https://github.com/preservim/nerdtree/pull/991) ++ - Allow multi-character DirArrows (PhilRunninger) [#985](https://github.com/preservim/nerdtree/pull/985) ++ - Remove redraw! while still clearing last message empty string. (PhilRunninger) [#979](https://github.com/preservim/nerdtree/pull/979) ++ - fix `_initChildren` function value set to numChildrenCached error (terryding77) [#969](https://github.com/preservim/nerdtree/pull/969) ++ - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) [#967](https://github.com/preservim/nerdtree/pull/967) ++ - Remove the **Please wait... DONE** messages. (PhilRunninger) [#966](https://github.com/preservim/nerdtree/pull/966) ++ - Smarter delimiter default (PhilRunninger) [#963](https://github.com/preservim/nerdtree/pull/963) ++ - Update directory .vimdc readme example (spencerdcarlson) [#961](https://github.com/preservim/nerdtree/pull/961) ++ - Preview bookmarks (PhilRunninger) [#956](https://github.com/preservim/nerdtree/pull/956) ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) [#955](https://github.com/preservim/nerdtree/pull/955) ++ - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) [#954](https://github.com/preservim/nerdtree/pull/954) ++ - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) [#952](https://github.com/preservim/nerdtree/pull/952) ++ - Set a maximum window size when zooming. (PhilRunninger) [#950](https://github.com/preservim/nerdtree/pull/950) ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) [#949](https://github.com/preservim/nerdtree/pull/949) ++ - Escape a backslash so it can be used in a key mapping. (PhilRunninger) [#948](https://github.com/preservim/nerdtree/pull/948) ++ - Add a NERDTreeMinimalMenu feature (tuzz) [#938](https://github.com/preservim/nerdtree/pull/938) ++ - fixed root path error for windows (zcodes) [#935](https://github.com/preservim/nerdtree/pull/935) ++ - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) [#929](https://github.com/preservim/nerdtree/pull/929) ++ - Document NERDTreeNodeDelimiter [#912](https://github.com/preservim/nerdtree/pull/912) (PhilRunninger) [#926](https://github.com/preservim/nerdtree/pull/926) ++ - Allow modification of menu keybindings (Leandros) [#923](https://github.com/preservim/nerdtree/pull/923) ++ - Add two more disqualifications for isCascadable(). (PhilRunninger) [#914](https://github.com/preservim/nerdtree/pull/914) ++ - Allow highlighting more than one flag. (kristijanhusak) [#908](https://github.com/preservim/nerdtree/pull/908) ++ - Support sorting files and directories by modification time. (PhilRunninger) [#901](https://github.com/preservim/nerdtree/pull/901) ++ - Parse . and .. from path string with trailing slash. (PhilRunninger) [#899](https://github.com/preservim/nerdtree/pull/899) ++ - Force sort to recalculate the cached sortKey. (PhilRunninger) [#898](https://github.com/preservim/nerdtree/pull/898) ++ - Add NERDTreeRefreshRoot command (wgfm) [#897](https://github.com/preservim/nerdtree/pull/897) ++ - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) [#896](https://github.com/preservim/nerdtree/pull/896) ++ - Catch all errors, not just NERDTree errors. (PhilRunninger) [#894](https://github.com/preservim/nerdtree/pull/894) ++ - Fix typo in help file (lvoisin) [#892](https://github.com/preservim/nerdtree/pull/892) ++ - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) [#889](https://github.com/preservim/nerdtree/pull/889) ++ - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) [#888](https://github.com/preservim/nerdtree/pull/888) ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) [#887](https://github.com/preservim/nerdtree/pull/887) ++ - Fix the / motions, which currently fail with cascades (lifecrisis) [#886](https://github.com/preservim/nerdtree/pull/886) ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) [#882](https://github.com/preservim/nerdtree/pull/882) ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) [#878](https://github.com/preservim/nerdtree/pull/878) ++ - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) [#877](https://github.com/preservim/nerdtree/pull/877) ++ - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) [#875](https://github.com/preservim/nerdtree/pull/875) ++ - Fix opening sub-directories that have commas in their name. (PhilRunninger) [#873](https://github.com/preservim/nerdtree/pull/873) ++ - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) [#872](https://github.com/preservim/nerdtree/pull/872) ++ - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) [#871](https://github.com/preservim/nerdtree/pull/871) ++ - Unzoom NERDTree when opening a file (PhilRunninger) [#870](https://github.com/preservim/nerdtree/pull/870) ++ - Support unusual characters in file and directory names (PhilRunninger) [#868](https://github.com/preservim/nerdtree/pull/868) ++ - Reword renamed-buffer prompt to be more clear (aflock) [#867](https://github.com/preservim/nerdtree/pull/867) ++ - Default to placing cursor on root when closing bookmark table (lifecrisis) [#866](https://github.com/preservim/nerdtree/pull/866) ++ - Fix issues with sorting of nodes (PhilRunninger) [#856](https://github.com/preservim/nerdtree/pull/856) ++ - Better OSX detection (bubba-h57) [#853](https://github.com/preservim/nerdtree/pull/853) ++ - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) [#852](https://github.com/preservim/nerdtree/pull/852) ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) [#851](https://github.com/preservim/nerdtree/pull/851) ++ - Add code to sort mappings in quickhelp (lifecrisis) [#849](https://github.com/preservim/nerdtree/pull/849) ++ - Use ":clearjumps" in new NERDTree windows (lifecrisis) [#844](https://github.com/preservim/nerdtree/pull/844) ++ - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) [#840](https://github.com/preservim/nerdtree/pull/840) ++ - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) [#838](https://github.com/preservim/nerdtree/pull/838) ++ - Make the NERDTree buffer writable when rendering it. (PhilRunninger) [#837](https://github.com/preservim/nerdtree/pull/837) ++ - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) [#835](https://github.com/preservim/nerdtree/pull/835) ++ - Replace strcharpart() with substitute() for backward compatibility (bravestarr) [#834](https://github.com/preservim/nerdtree/pull/834) ++ - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) [#833](https://github.com/preservim/nerdtree/pull/833) ++ - Clear output when NERDTree menu is aborted (lifecrisis) [#832](https://github.com/preservim/nerdtree/pull/832) ++ - Display a path with multi-byte characters correctly when it is truncated (bravestarr) [#830](https://github.com/preservim/nerdtree/pull/830) ++ - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) [#824](https://github.com/preservim/nerdtree/pull/824) ++ - If node isn't open, count children on disk before deleting. (PhilRunninger) [#822](https://github.com/preservim/nerdtree/pull/822) ++ - Add new variable g:NERDTreeRemoveFileCmd (kutsan) [#816](https://github.com/preservim/nerdtree/pull/816) ++ - Use a better check for existence of the NERDTree buffer. (PhilRunninger) [#814](https://github.com/preservim/nerdtree/pull/814) ++ - Fix focussing previous buffer when closing NERDTree (mrubli) [#801](https://github.com/preservim/nerdtree/pull/801) ++ - Update the docs for "NERDTreeStatusline" (lifecrisis) [#796](https://github.com/preservim/nerdtree/pull/796) ++ - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) [#795](https://github.com/preservim/nerdtree/pull/795) ++ - Revert the bugfix from pull request [#785](https://github.com/preservim/nerdtree/pull/785) (lifecrisis) [#794](https://github.com/preservim/nerdtree/pull/794) ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) [#786](https://github.com/preservim/nerdtree/pull/786) ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) [#785](https://github.com/preservim/nerdtree/pull/785) ++ - Add modelines (lifecrisis) [#782](https://github.com/preservim/nerdtree/pull/782) ++ - Change the type of completion used by NERDTreeFind (lifecrisis) [#781](https://github.com/preservim/nerdtree/pull/781) ++ - change NERDTreeFind with args (zhenyangze) [#778](https://github.com/preservim/nerdtree/pull/778) ++ - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) [#777](https://github.com/preservim/nerdtree/pull/777) ++ - remove useless substitute when `file =~# "/$"` (skyblueee) [#773](https://github.com/preservim/nerdtree/pull/773) ++ - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) [#772](https://github.com/preservim/nerdtree/pull/772) ++ - Make the "o" mapping consistent with "x" (lifecrisis) [#769](https://github.com/preservim/nerdtree/pull/769) ++ - Fix a problem with the "x" handler (lifecrisis) [#768](https://github.com/preservim/nerdtree/pull/768) ++ - Clean up the handler for the "x" mapping (lifecrisis) [#767](https://github.com/preservim/nerdtree/pull/767) ++ - Revert change to tab opening method (lifecrisis) [#766](https://github.com/preservim/nerdtree/pull/766) ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) [#765](https://github.com/preservim/nerdtree/pull/765) ++ - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) [#759](https://github.com/preservim/nerdtree/pull/759) ++ - Update doc with already existing mapping variables (asnr) [#699](https://github.com/preservim/nerdtree/pull/699) ++ - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) [#696](https://github.com/preservim/nerdtree/pull/696) ++ - Correct NERDTreeIgnore pattern in doc (cntoplolicon) [#648](https://github.com/preservim/nerdtree/pull/648) ++ - Remove empty segments when splitting path (sooth-sayer) [#574](https://github.com/preservim/nerdtree/pull/574) ++ - Suppress autocmds less agressively (wincent) [#578](https://github.com/preservim/nerdtree/pull/578) [#691](https://github.com/preservim/nerdtree/pull/691) + - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (josephfrazier) [#676](https://github.com/scrooloose/nerdtree/pull/676) ++ - Fix markdown headers in readme (josephfrazier) [#676](https://github.com/preservim/nerdtree/pull/676) + - Don't touch `@o` and `@h` registers when rendering +- - Fix bug with files and directories with dollar signs (alegen) [#649](https://github.com/scrooloose/nerdtree/pull/649) +- - Reuse/reopen existing window trees where possible [#244](https://github.com/scrooloose/nerdtree/pull/244) ++ - Fix bug with files and directories with dollar signs (alegen) [#649](https://github.com/preservim/nerdtree/pull/649) ++ - Reuse/reopen existing window trees where possible [#244](https://github.com/preservim/nerdtree/pull/244) + - Remove NERDTree.previousBuf() +- - Change color of arrow (Leeiio) [#630](https://github.com/scrooloose/nerdtree/pull/630) +- - Improved a tip in README.markdown (ggicci) [#628](https://github.com/scrooloose/nerdtree/pull/628) +- - Shorten delete confimration of empty directory to `y` (mikeperri) [#530](https://github.com/scrooloose/nerdtree/pull/530) +- - Fix API call to open directory tree in window (devm33) [#533](https://github.com/scrooloose/nerdtree/pull/533) +- - Change default arrows on non-Windows platforms (gwilk) [#546](https://github.com/scrooloose/nerdtree/pull/546) +- - Update to README - combine cd and git clone (zwhitchcox) [#584](https://github.com/scrooloose/nerdtree/pull/584) +- - Update to README - Tip: start NERDTree when vim starts (therealplato) [#593](https://github.com/scrooloose/nerdtree/pull/593) +- - Escape filename when moving an open buffer (zacharyvoase) [#595](https://github.com/scrooloose/nerdtree/pull/595) +- - Fixed incorrect :helptags command in README (curran) [#619](https://github.com/scrooloose/nerdtree/pull/619) +- - Fixed incomplete escaping of folder arrows (adityanatraj) [#548](https://github.com/scrooloose/nerdtree/pull/548) +- - Added NERDTreeCascadeSingleChildDir option (juanibiapina) [#558](https://github.com/scrooloose/nerdtree/pull/558) ++ - Change color of arrow (Leeiio) [#630](https://github.com/preservim/nerdtree/pull/630) ++ - Improved a tip in README.markdown (ggicci) [#628](https://github.com/preservim/nerdtree/pull/628) ++ - Shorten delete confimration of empty directory to `y` (mikeperri) [#530](https://github.com/preservim/nerdtree/pull/530) ++ - Fix API call to open directory tree in window (devm33) [#533](https://github.com/preservim/nerdtree/pull/533) ++ - Change default arrows on non-Windows platforms (gwilk) [#546](https://github.com/preservim/nerdtree/pull/546) ++ - Update to README - combine cd and git clone (zwhitchcox) [#584](https://github.com/preservim/nerdtree/pull/584) ++ - Update to README - Tip: start NERDTree when vim starts (therealplato) [#593](https://github.com/preservim/nerdtree/pull/593) ++ - Escape filename when moving an open buffer (zacharyvoase) [#595](https://github.com/preservim/nerdtree/pull/595) ++ - Fixed incorrect :helptags command in README (curran) [#619](https://github.com/preservim/nerdtree/pull/619) ++ - Fixed incomplete escaping of folder arrows (adityanatraj) [#548](https://github.com/preservim/nerdtree/pull/548) ++ - Added NERDTreeCascadeSingleChildDir option (juanibiapina) [#558](https://github.com/preservim/nerdtree/pull/558) + - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (SkylerLipthay) [#231](https://github.com/scrooloose/nerdtree/pull/231) ++ - Add support for copy command in Windows (SkylerLipthay) [#231](https://github.com/preservim/nerdtree/pull/231) + - Fixed typo in README.markdown - :Helptags -> :helptags + - Rename "primary" and "secondary" trees to "tab" and "window" trees. + - Move a bunch of buffer level variables into the NERDTree and UI classes. +diff --git a/README.markdown b/README.markdown +index 9e53952..a3fe4fe 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -12,7 +12,7 @@ This plugin can also be extended with custom mappings using a special API. The + details of this API and of other NERDTree features are described in the + included documentation. + +-![NERDTree Screenshot](https://github.com/scrooloose/nerdtree/raw/master/screenshot.png) ++![NERDTree Screenshot](https://github.com/preservim/nerdtree/raw/master/screenshot.png) + + Installation + ------------ +@@ -24,7 +24,7 @@ Below are just some of the methods for installing NERDTree. Do not follow all of + If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: + + ```bash +-git clone https://github.com/scrooloose/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree + vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q + ``` + +@@ -34,7 +34,7 @@ Otherwise, these are some of the several 3rd-party plugin managers you can choos + + In the terminal, + ```bash +-git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree ++git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree + ``` + In your vimrc, + ```vim +@@ -48,23 +48,23 @@ Then reload vim, run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. + #### [Vundle.vim](https://github.com/VundleVim/Vundle.vim) + ```vim + call vundle#begin() +-Plugin 'scrooloose/nerdtree' ++Plugin 'preservim/nerdtree' + call vundle#end() + ``` + + #### [vim-plug](https://github.com/junegunn/vim-plug) + ```vim + call plug#begin() +-Plug 'scrooloose/nerdtree' ++Plug 'preservim/nerdtree' + call plug#end() + ``` + + #### [apt-vim](https://github.com/egalpin/apt-vim) + ```bash +-apt-vim install -y https://github.com/scrooloose/nerdtree.git ++apt-vim install -y https://github.com/preservim/nerdtree.git + ``` + +-F.A.Q. (here, and in the [Wiki](https://github.com/scrooloose/nerdtree/wiki)) ++F.A.Q. (here, and in the [Wiki](https://github.com/preservim/nerdtree/wiki)) + ------ + + #### Is there any support for `git` flags? +@@ -133,7 +133,7 @@ autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isT + --- + #### Can I have different highlighting for different file extensions? + +-See here: https://github.com/scrooloose/nerdtree/issues/433#issuecomment-92590696 ++See here: https://github.com/preservim/nerdtree/issues/433#issuecomment-92590696 + + --- + #### How can I change default arrows? +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index be0011d..857e682 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -1238,7 +1238,7 @@ This character is used to separate the file or directory name from the rest of + the characters in the line of text. It allows filenames to contain special + characters that are otherwise used in the NERDTree, such as square brackets, + braces, trailing asterisk, and leading space. For more details, see the +-responsible pull request: https://github.com/scrooloose/nerdtree/pull/868. ++responsible pull request: https://github.com/preservim/nerdtree/pull/868. + + The default value of this variable depends on the features compiled into your + vim and the values of |NERDTreeDirArrowCollapsible| and +@@ -1498,11 +1498,11 @@ in the fridge for later ;) + Martyzilla recruited two other unwitting accomplices to become his minions in + his quest to conquer the Vim plugin world. While he may still love to receive + your emails, the best way to send suggestions, bug reports, and questions is +-to submit an issue at http://github.com/scrooloose/nerdtree/issues. ++to submit an issue at http://github.com/preservim/nerdtree/issues. + + The latest stable and development versions are on Github. +- Stable: http://github.com/scrooloose/nerdtree (master branch) +- Development: http://github.com/scrooloose/nerdtree/branches ++ Stable: http://github.com/preservim/nerdtree (master branch) ++ Development: http://github.com/preservim/nerdtree/branches + + Title Credit: + * http://ascii.co.uk/art/tree diff --git a/tasks/preservim__nerdtree-1072/solution/solve.sh b/tasks/preservim__nerdtree-1072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1072/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/preservim__nerdtree-1072/task.toml b/tasks/preservim__nerdtree-1072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0cc3c82c7f32393be6f78954cb4c9bbde4bbdd3 --- /dev/null +++ b/tasks/preservim__nerdtree-1072/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1072" +description = "Update links to repository with new org namespace" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "97fb849a29d74a9cceeca92472f770d81473c780" +reference = "https://github.com/preservim/nerdtree/pull/1072" +source_access = "auto" +built_at = "2026-11-16T16:10:02.446289+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a3d652c2e59a525af4fe14aa4853dc6025e9f0b9b6df83c32acb66dee82f6996" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-02T14:55:18Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", + "doc/NERDTree.txt", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 288 +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:02.571233+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2ab77ef6a0201962cd9aeba238317f7ebd256a96773f9031f7d38f91707913fb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1072/tests/capture.py b/tasks/preservim__nerdtree-1072/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1072/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/preservim__nerdtree-1072/tests/instruction.md b/tasks/preservim__nerdtree-1072/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..990445840bca255ea772a70937efccc09146aa88 --- /dev/null +++ b/tasks/preservim__nerdtree-1072/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update links to repository with new org namespace + +## Description + +This should be a no-op as far as the plugin is concerned. I don't know what your changelog protocol is for things like this so I didn't enter one. Let me know if I should. + +These links are not broken yet, but someday they might and particularly for people cloning the repository or adding it to their plugin managers it would be nice if they got the canonical location in the first go. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97fb849a29d7`. 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/preservim__nerdtree-1072/tests/oracle.patch b/tasks/preservim__nerdtree-1072/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..119f753934f1f48854cbda63f8cdbeb031db76de --- /dev/null +++ b/tasks/preservim__nerdtree-1072/tests/oracle.patch @@ -0,0 +1,384 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index cec006c..f052a2c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -9,151 +9,151 @@ + --> + #### 6.4 + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) +-- **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/scrooloose/nerdtree/pull/1067) ++- **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/preservim/nerdtree/pull/1067) + #### 6.3 +-- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/scrooloose/nerdtree/pull/1060) ++- **.0**: Add new command that behaves like NERDTreeToggle but defaults to the root of a VCS repository. (willfindlay) [#1060](https://github.com/preservim/nerdtree/pull/1060) + #### 6.2 +-- **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/scrooloose/nerdtree/pull/1056) +-- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/scrooloose/nerdtree/pull/1032) ++- **.1**: Menu option, 'copy path to clipboard' is aware of VIM clipboard option (jhzn) [#1056](https://github.com/preservim/nerdtree/pull/1056) ++- **.0**: Support tab-specific CWDs (PhilRunninger) [#1032](https://github.com/preservim/nerdtree/pull/1032) + #### 6.1 +-- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/scrooloose/nerdtree/pull/1049) +-- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/scrooloose/nerdtree/pull/1048) +-- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/scrooloose/nerdtree/pull/1047) +-- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/scrooloose/nerdtree/pull/1045) +-- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/scrooloose/nerdtree/pull/1043) ++- **.4**: Add VIM built-in package management to read me file. (pesarkhobeee) [#1049](https://github.com/preservim/nerdtree/pull/1049) ++- **.3**: Save/Set screen state also on WinLeave and WinEnter. (PhilRunninger) [#1048](https://github.com/preservim/nerdtree/pull/1048) ++- **.2**: Wrap saveScreenState's statements in a try-catch block. (PhilRunninger) [#1047](https://github.com/preservim/nerdtree/pull/1047) ++- **.1**: Catch errors when trying to read CHANGELOG.md. (PhilRunninger) [#1045](https://github.com/preservim/nerdtree/pull/1045) ++- **.0**: If file path doesn't exist, :NERDTreeFind its parent directory instead. (PhilRunninger) [#1043](https://github.com/preservim/nerdtree/pull/1043) + #### 6.0 +-- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/scrooloose/nerdtree/pull/1040) +-- **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/scrooloose/nerdtree/pull/1035) ++- **.1**: Reintroduce necessary variable mistakenly removed. (PhilRunninger) [#1040](https://github.com/preservim/nerdtree/pull/1040) ++- **.0**: Make the behavior of window splits consistent (dragonxlwang, PhilRunninger) [#1035](https://github.com/preservim/nerdtree/pull/1035) + #### 5.3 +-- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/scrooloose/nerdtree/pull/1038) +-- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/scrooloose/nerdtree/pull/1037) +-- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/scrooloose/nerdtree/pull/1031) +-- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/scrooloose/nerdtree/pull/1029) ++- **.3**: Fix (p)ath not displaying in the minimal menu (tuzz) [#1038](https://github.com/preservim/nerdtree/pull/1038) ++- **.2**: Enable events when closing NerdTree window. (PhilRunninger) [#1037](https://github.com/preservim/nerdtree/pull/1037) ++- **.1**: Fix the `e` key mapping to use netrw if desired (PhilRunninger) [#1031](https://github.com/preservim/nerdtree/pull/1031) ++- **.0**: Add file extension and size to sorting capabilities (PhilRunninger) [#1029](https://github.com/preservim/nerdtree/pull/1029) + #### 5.2 +-- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/scrooloose/nerdtree/pull/1026) +-- **.8**: Revert [#1019](https://github.com/scrooloose/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/scrooloose/nerdtree/pull/1021) +-- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/scrooloose/nerdtree/pull/1019) +-- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/scrooloose/nerdtree/pull/1017) +-- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/scrooloose/nerdtree/pull/1016) +-- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/scrooloose/nerdtree/pull/1015) +-- **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/scrooloose/nerdtree/pull/1014) +-- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) [#1013](https://github.com/scrooloose/nerdtree/pull/1013) ++- **.9**: Suppress events for intermediate window/tab/buffer changes (PhilRunninger) [#1026](https://github.com/preservim/nerdtree/pull/1026) ++- **.8**: Revert [#1019](https://github.com/preservim/nerdtree/pull/1019) to fix nvim artifacts and flickering. (PhilRunninger) [#1021](https://github.com/preservim/nerdtree/pull/1021) ++- **.7**: Use :mode only in neovim. MacVim still needs to use :redraw! (PhilRunninger) [#1019](https://github.com/preservim/nerdtree/pull/1019) ++- **.6**: In CHANGELOG.md and PR template, make reference to PR a true HTML link. (PhilRunninger) [#1017](https://github.com/preservim/nerdtree/pull/1017) ++- **.5**: Use `:mode` instead of `:redraw!` when updating menu. (PhilRunninger) [#1016](https://github.com/preservim/nerdtree/pull/1016) ++- **.4**: When searching for root line num, stop at end of file. (PhilRunninger) [#1015](https://github.com/preservim/nerdtree/pull/1015) ++- **.3**: Fix `` key map on the bookmark (lkebin) [#1014](https://github.com/preservim/nerdtree/pull/1014) ++- **.2**: Make Enter work on the `.. ( up a dir )` line (PhilRunninger) [#1013](https://github.com/preservim/nerdtree/pull/1013) + - **.1**: Fix nerdtree#version() on Windows. (PhilRunninger) +-- **.0**: Expand functionality of `` mapping. (PhilRunninger) [#1011](https://github.com/scrooloose/nerdtree/pull/1011) ++- **.0**: Expand functionality of `` mapping. (PhilRunninger) [#1011](https://github.com/preservim/nerdtree/pull/1011) + #### 5.1 +-- **.3**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) [#1009](https://github.com/scrooloose/nerdtree/pull/1009) +-- **.2**: Fix NERDTree opening with the wrong size. (PhilRunninger) [#1008](https://github.com/scrooloose/nerdtree/pull/1008) +-- **.1**: Update Changelog and create PR Template (PhilRunninger) [#1007](https://github.com/scrooloose/nerdtree/pull/1007) ++- **.3**: Remove @mentions from PR template and change log. They weren't working. (PhilRunninger) [#1009](https://github.com/preservim/nerdtree/pull/1009) ++- **.2**: Fix NERDTree opening with the wrong size. (PhilRunninger) [#1008](https://github.com/preservim/nerdtree/pull/1008) ++- **.1**: Update Changelog and create PR Template (PhilRunninger) [#1007](https://github.com/preservim/nerdtree/pull/1007) + - **.0**: Too many changes for one patch... +- - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) [#1005](https://github.com/scrooloose/nerdtree/pull/1005) +- - Add a "copy path to clipboard" menu option (PhilRunninger) [#1002](https://github.com/scrooloose/nerdtree/pull/1002) +- - Enable root refresh on "vim ." a different way than [#999](https://github.com/scrooloose/nerdtree/pull/999). (PhilRunninger) [#1001](https://github.com/scrooloose/nerdtree/pull/1001) +- - Fix refreshroot (PhilRunninger) [#999](https://github.com/scrooloose/nerdtree/pull/999) +- - Change version check to look for 703 not 730 (vhalis) [#994](https://github.com/scrooloose/nerdtree/pull/994) +- - Change minimum vim (PhilRunninger) [#991](https://github.com/scrooloose/nerdtree/pull/991) +- - Allow multi-character DirArrows (PhilRunninger) [#985](https://github.com/scrooloose/nerdtree/pull/985) +- - Remove redraw! while still clearing last message empty string. (PhilRunninger) [#979](https://github.com/scrooloose/nerdtree/pull/979) +- - fix `_initChildren` function value set to numChildrenCached error (terryding77) [#969](https://github.com/scrooloose/nerdtree/pull/969) +- - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) [#967](https://github.com/scrooloose/nerdtree/pull/967) +- - Remove the **Please wait... DONE** messages. (PhilRunninger) [#966](https://github.com/scrooloose/nerdtree/pull/966) +- - Smarter delimiter default (PhilRunninger) [#963](https://github.com/scrooloose/nerdtree/pull/963) +- - Update directory .vimdc readme example (spencerdcarlson) [#961](https://github.com/scrooloose/nerdtree/pull/961) +- - Preview bookmarks (PhilRunninger) [#956](https://github.com/scrooloose/nerdtree/pull/956) +- - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) [#955](https://github.com/scrooloose/nerdtree/pull/955) +- - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) [#954](https://github.com/scrooloose/nerdtree/pull/954) +- - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) [#952](https://github.com/scrooloose/nerdtree/pull/952) +- - Set a maximum window size when zooming. (PhilRunninger) [#950](https://github.com/scrooloose/nerdtree/pull/950) +- - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) [#949](https://github.com/scrooloose/nerdtree/pull/949) +- - Escape a backslash so it can be used in a key mapping. (PhilRunninger) [#948](https://github.com/scrooloose/nerdtree/pull/948) +- - Add a NERDTreeMinimalMenu feature (tuzz) [#938](https://github.com/scrooloose/nerdtree/pull/938) +- - fixed root path error for windows (zcodes) [#935](https://github.com/scrooloose/nerdtree/pull/935) +- - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) [#929](https://github.com/scrooloose/nerdtree/pull/929) +- - Document NERDTreeNodeDelimiter [#912](https://github.com/scrooloose/nerdtree/pull/912) (PhilRunninger) [#926](https://github.com/scrooloose/nerdtree/pull/926) +- - Allow modification of menu keybindings (Leandros) [#923](https://github.com/scrooloose/nerdtree/pull/923) +- - Add two more disqualifications for isCascadable(). (PhilRunninger) [#914](https://github.com/scrooloose/nerdtree/pull/914) +- - Allow highlighting more than one flag. (kristijanhusak) [#908](https://github.com/scrooloose/nerdtree/pull/908) +- - Support sorting files and directories by modification time. (PhilRunninger) [#901](https://github.com/scrooloose/nerdtree/pull/901) +- - Parse . and .. from path string with trailing slash. (PhilRunninger) [#899](https://github.com/scrooloose/nerdtree/pull/899) +- - Force sort to recalculate the cached sortKey. (PhilRunninger) [#898](https://github.com/scrooloose/nerdtree/pull/898) +- - Add NERDTreeRefreshRoot command (wgfm) [#897](https://github.com/scrooloose/nerdtree/pull/897) +- - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) [#896](https://github.com/scrooloose/nerdtree/pull/896) +- - Catch all errors, not just NERDTree errors. (PhilRunninger) [#894](https://github.com/scrooloose/nerdtree/pull/894) +- - Fix typo in help file (lvoisin) [#892](https://github.com/scrooloose/nerdtree/pull/892) +- - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) [#889](https://github.com/scrooloose/nerdtree/pull/889) +- - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) [#888](https://github.com/scrooloose/nerdtree/pull/888) +- - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) [#887](https://github.com/scrooloose/nerdtree/pull/887) +- - Fix the / motions, which currently fail with cascades (lifecrisis) [#886](https://github.com/scrooloose/nerdtree/pull/886) +- - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) [#882](https://github.com/scrooloose/nerdtree/pull/882) +- - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) [#878](https://github.com/scrooloose/nerdtree/pull/878) +- - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) [#877](https://github.com/scrooloose/nerdtree/pull/877) +- - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) [#875](https://github.com/scrooloose/nerdtree/pull/875) +- - Fix opening sub-directories that have commas in their name. (PhilRunninger) [#873](https://github.com/scrooloose/nerdtree/pull/873) +- - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) [#872](https://github.com/scrooloose/nerdtree/pull/872) +- - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) [#871](https://github.com/scrooloose/nerdtree/pull/871) +- - Unzoom NERDTree when opening a file (PhilRunninger) [#870](https://github.com/scrooloose/nerdtree/pull/870) +- - Support unusual characters in file and directory names (PhilRunninger) [#868](https://github.com/scrooloose/nerdtree/pull/868) +- - Reword renamed-buffer prompt to be more clear (aflock) [#867](https://github.com/scrooloose/nerdtree/pull/867) +- - Default to placing cursor on root when closing bookmark table (lifecrisis) [#866](https://github.com/scrooloose/nerdtree/pull/866) +- - Fix issues with sorting of nodes (PhilRunninger) [#856](https://github.com/scrooloose/nerdtree/pull/856) +- - Better OSX detection (bubba-h57) [#853](https://github.com/scrooloose/nerdtree/pull/853) +- - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) [#852](https://github.com/scrooloose/nerdtree/pull/852) +- - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) [#851](https://github.com/scrooloose/nerdtree/pull/851) +- - Add code to sort mappings in quickhelp (lifecrisis) [#849](https://github.com/scrooloose/nerdtree/pull/849) +- - Use ":clearjumps" in new NERDTree windows (lifecrisis) [#844](https://github.com/scrooloose/nerdtree/pull/844) +- - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) [#840](https://github.com/scrooloose/nerdtree/pull/840) +- - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) [#838](https://github.com/scrooloose/nerdtree/pull/838) +- - Make the NERDTree buffer writable when rendering it. (PhilRunninger) [#837](https://github.com/scrooloose/nerdtree/pull/837) +- - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) [#835](https://github.com/scrooloose/nerdtree/pull/835) +- - Replace strcharpart() with substitute() for backward compatibility (bravestarr) [#834](https://github.com/scrooloose/nerdtree/pull/834) +- - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) [#833](https://github.com/scrooloose/nerdtree/pull/833) +- - Clear output when NERDTree menu is aborted (lifecrisis) [#832](https://github.com/scrooloose/nerdtree/pull/832) +- - Display a path with multi-byte characters correctly when it is truncated (bravestarr) [#830](https://github.com/scrooloose/nerdtree/pull/830) +- - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) [#824](https://github.com/scrooloose/nerdtree/pull/824) +- - If node isn't open, count children on disk before deleting. (PhilRunninger) [#822](https://github.com/scrooloose/nerdtree/pull/822) +- - Add new variable g:NERDTreeRemoveFileCmd (kutsan) [#816](https://github.com/scrooloose/nerdtree/pull/816) +- - Use a better check for existence of the NERDTree buffer. (PhilRunninger) [#814](https://github.com/scrooloose/nerdtree/pull/814) +- - Fix focussing previous buffer when closing NERDTree (mrubli) [#801](https://github.com/scrooloose/nerdtree/pull/801) +- - Update the docs for "NERDTreeStatusline" (lifecrisis) [#796](https://github.com/scrooloose/nerdtree/pull/796) +- - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) [#795](https://github.com/scrooloose/nerdtree/pull/795) +- - Revert the bugfix from pull request [#785](https://github.com/scrooloose/nerdtree/pull/785) (lifecrisis) [#794](https://github.com/scrooloose/nerdtree/pull/794) +- - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) [#786](https://github.com/scrooloose/nerdtree/pull/786) +- - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) [#785](https://github.com/scrooloose/nerdtree/pull/785) +- - Add modelines (lifecrisis) [#782](https://github.com/scrooloose/nerdtree/pull/782) +- - Change the type of completion used by NERDTreeFind (lifecrisis) [#781](https://github.com/scrooloose/nerdtree/pull/781) +- - change NERDTreeFind with args (zhenyangze) [#778](https://github.com/scrooloose/nerdtree/pull/778) +- - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) [#777](https://github.com/scrooloose/nerdtree/pull/777) +- - remove useless substitute when `file =~# "/$"` (skyblueee) [#773](https://github.com/scrooloose/nerdtree/pull/773) +- - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) [#772](https://github.com/scrooloose/nerdtree/pull/772) +- - Make the "o" mapping consistent with "x" (lifecrisis) [#769](https://github.com/scrooloose/nerdtree/pull/769) +- - Fix a problem with the "x" handler (lifecrisis) [#768](https://github.com/scrooloose/nerdtree/pull/768) +- - Clean up the handler for the "x" mapping (lifecrisis) [#767](https://github.com/scrooloose/nerdtree/pull/767) +- - Revert change to tab opening method (lifecrisis) [#766](https://github.com/scrooloose/nerdtree/pull/766) +- - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) [#765](https://github.com/scrooloose/nerdtree/pull/765) +- - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) [#759](https://github.com/scrooloose/nerdtree/pull/759) +- - Update doc with already existing mapping variables (asnr) [#699](https://github.com/scrooloose/nerdtree/pull/699) +- - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) [#696](https://github.com/scrooloose/nerdtree/pull/696) +- - Correct NERDTreeIgnore pattern in doc (cntoplolicon) [#648](https://github.com/scrooloose/nerdtree/pull/648) +- - Remove empty segments when splitting path (sooth-sayer) [#574](https://github.com/scrooloose/nerdtree/pull/574) +- - Suppress autocmds less agressively (wincent) [#578](https://github.com/scrooloose/nerdtree/pull/578) [#691](https://github.com/scrooloose/nerdtree/pull/691) ++ - Refresh a dir_node if the file wasn't found in it, and look once more. (PhilRunninger) [#1005](https://github.com/preservim/nerdtree/pull/1005) ++ - Add a "copy path to clipboard" menu option (PhilRunninger) [#1002](https://github.com/preservim/nerdtree/pull/1002) ++ - Enable root refresh on "vim ." a different way than [#999](https://github.com/preservim/nerdtree/pull/999). (PhilRunninger) [#1001](https://github.com/preservim/nerdtree/pull/1001) ++ - Fix refreshroot (PhilRunninger) [#999](https://github.com/preservim/nerdtree/pull/999) ++ - Change version check to look for 703 not 730 (vhalis) [#994](https://github.com/preservim/nerdtree/pull/994) ++ - Change minimum vim (PhilRunninger) [#991](https://github.com/preservim/nerdtree/pull/991) ++ - Allow multi-character DirArrows (PhilRunninger) [#985](https://github.com/preservim/nerdtree/pull/985) ++ - Remove redraw! while still clearing last message empty string. (PhilRunninger) [#979](https://github.com/preservim/nerdtree/pull/979) ++ - fix `_initChildren` function value set to numChildrenCached error (terryding77) [#969](https://github.com/preservim/nerdtree/pull/969) ++ - On Windows, do a case-insensitive comparison of paths. (PhilRunninger) [#967](https://github.com/preservim/nerdtree/pull/967) ++ - Remove the **Please wait... DONE** messages. (PhilRunninger) [#966](https://github.com/preservim/nerdtree/pull/966) ++ - Smarter delimiter default (PhilRunninger) [#963](https://github.com/preservim/nerdtree/pull/963) ++ - Update directory .vimdc readme example (spencerdcarlson) [#961](https://github.com/preservim/nerdtree/pull/961) ++ - Preview bookmarks (PhilRunninger) [#956](https://github.com/preservim/nerdtree/pull/956) ++ - Add new value to NERDTreeQuitOnOpen to close bookmark table (PhilRunninger) [#955](https://github.com/preservim/nerdtree/pull/955) ++ - Add an :EditBookmarks command to edit the bookmarks file (PhilRunninger) [#954](https://github.com/preservim/nerdtree/pull/954) ++ - Before copying, turn off &shellslash. Restore after copy is finished. (PhilRunninger) [#952](https://github.com/preservim/nerdtree/pull/952) ++ - Set a maximum window size when zooming. (PhilRunninger) [#950](https://github.com/preservim/nerdtree/pull/950) ++ - Confirm the wipeout of a unsaved buffer whose file has been renamed. (PhilRunninger) [#949](https://github.com/preservim/nerdtree/pull/949) ++ - Escape a backslash so it can be used in a key mapping. (PhilRunninger) [#948](https://github.com/preservim/nerdtree/pull/948) ++ - Add a NERDTreeMinimalMenu feature (tuzz) [#938](https://github.com/preservim/nerdtree/pull/938) ++ - fixed root path error for windows (zcodes) [#935](https://github.com/preservim/nerdtree/pull/935) ++ - Restore getDirChildren for use in nerdtree-project-plugin. (PhilRunninger) [#929](https://github.com/preservim/nerdtree/pull/929) ++ - Document NERDTreeNodeDelimiter [#912](https://github.com/preservim/nerdtree/pull/912) (PhilRunninger) [#926](https://github.com/preservim/nerdtree/pull/926) ++ - Allow modification of menu keybindings (Leandros) [#923](https://github.com/preservim/nerdtree/pull/923) ++ - Add two more disqualifications for isCascadable(). (PhilRunninger) [#914](https://github.com/preservim/nerdtree/pull/914) ++ - Allow highlighting more than one flag. (kristijanhusak) [#908](https://github.com/preservim/nerdtree/pull/908) ++ - Support sorting files and directories by modification time. (PhilRunninger) [#901](https://github.com/preservim/nerdtree/pull/901) ++ - Parse . and .. from path string with trailing slash. (PhilRunninger) [#899](https://github.com/preservim/nerdtree/pull/899) ++ - Force sort to recalculate the cached sortKey. (PhilRunninger) [#898](https://github.com/preservim/nerdtree/pull/898) ++ - Add NERDTreeRefreshRoot command (wgfm) [#897](https://github.com/preservim/nerdtree/pull/897) ++ - Call Resolve on the file's path when calling :NERDTreeFind. (PhilRunninger) [#896](https://github.com/preservim/nerdtree/pull/896) ++ - Catch all errors, not just NERDTree errors. (PhilRunninger) [#894](https://github.com/preservim/nerdtree/pull/894) ++ - Fix typo in help file (lvoisin) [#892](https://github.com/preservim/nerdtree/pull/892) ++ - Make NERDTreeCreator set the `'nolist'` option (lifecrisis) [#889](https://github.com/preservim/nerdtree/pull/889) ++ - Refresh buffers after `m`, `m` operation on a folder (PhilRunninger) [#888](https://github.com/preservim/nerdtree/pull/888) ++ - Use a better arg for FINDSTR when using the m,l command in Windows. (PhilRunninger) [#887](https://github.com/preservim/nerdtree/pull/887) ++ - Fix the / motions, which currently fail with cascades (lifecrisis) [#886](https://github.com/preservim/nerdtree/pull/886) ++ - Function "s:UI.getLineNum()" doesn't always work on cascades. (lifecrisis) [#882](https://github.com/preservim/nerdtree/pull/882) ++ - NERDTreeCWD: reset CWD if changed by NERDTreeFocus (PhilRunninger) [#878](https://github.com/preservim/nerdtree/pull/878) ++ - Use tabnext instead of gt to allow users to remap gt. (PhilRunninger) [#877](https://github.com/preservim/nerdtree/pull/877) ++ - Do a case sensitive comparison of new/existing buffers. (PhilRunninger) [#875](https://github.com/preservim/nerdtree/pull/875) ++ - Fix opening sub-directories that have commas in their name. (PhilRunninger) [#873](https://github.com/preservim/nerdtree/pull/873) ++ - Add new command to open NERDTree in the root of a VCS repository. (PhilRunninger) [#872](https://github.com/preservim/nerdtree/pull/872) ++ - Make sure the path to the bookmarks file exists before writing it. (PhilRunninger) [#871](https://github.com/preservim/nerdtree/pull/871) ++ - Unzoom NERDTree when opening a file (PhilRunninger) [#870](https://github.com/preservim/nerdtree/pull/870) ++ - Support unusual characters in file and directory names (PhilRunninger) [#868](https://github.com/preservim/nerdtree/pull/868) ++ - Reword renamed-buffer prompt to be more clear (aflock) [#867](https://github.com/preservim/nerdtree/pull/867) ++ - Default to placing cursor on root when closing bookmark table (lifecrisis) [#866](https://github.com/preservim/nerdtree/pull/866) ++ - Fix issues with sorting of nodes (PhilRunninger) [#856](https://github.com/preservim/nerdtree/pull/856) ++ - Better OSX detection (bubba-h57) [#853](https://github.com/preservim/nerdtree/pull/853) ++ - Bugfix - ensure keymaps dictionary exists before using it (mnussbaum) [#852](https://github.com/preservim/nerdtree/pull/852) ++ - Decrease startup-time by avoiding linear-time iteration over key mappings (mnussbaum) [#851](https://github.com/preservim/nerdtree/pull/851) ++ - Add code to sort mappings in quickhelp (lifecrisis) [#849](https://github.com/preservim/nerdtree/pull/849) ++ - Use ":clearjumps" in new NERDTree windows (lifecrisis) [#844](https://github.com/preservim/nerdtree/pull/844) ++ - Like m-c did before, create parent directories if needed on m-m. (PhilRunninger) [#840](https://github.com/preservim/nerdtree/pull/840) ++ - BUGFIX: Repair a problem with the `'u'` mapping. (lifecrisis) [#838](https://github.com/preservim/nerdtree/pull/838) ++ - Make the NERDTree buffer writable when rendering it. (PhilRunninger) [#837](https://github.com/preservim/nerdtree/pull/837) ++ - Code cleanup: Remove unsupported bookmark table mappings (lifecrisis) [#835](https://github.com/preservim/nerdtree/pull/835) ++ - Replace strcharpart() with substitute() for backward compatibility (bravestarr) [#834](https://github.com/preservim/nerdtree/pull/834) ++ - Fixed error `unknown function strcharpart` for older versions of Vim (hav4ik) [#833](https://github.com/preservim/nerdtree/pull/833) ++ - Clear output when NERDTree menu is aborted (lifecrisis) [#832](https://github.com/preservim/nerdtree/pull/832) ++ - Display a path with multi-byte characters correctly when it is truncated (bravestarr) [#830](https://github.com/preservim/nerdtree/pull/830) ++ - Support revealing file and executing file with xdg-open for Linux (ngnmhieu) [#824](https://github.com/preservim/nerdtree/pull/824) ++ - If node isn't open, count children on disk before deleting. (PhilRunninger) [#822](https://github.com/preservim/nerdtree/pull/822) ++ - Add new variable g:NERDTreeRemoveFileCmd (kutsan) [#816](https://github.com/preservim/nerdtree/pull/816) ++ - Use a better check for existence of the NERDTree buffer. (PhilRunninger) [#814](https://github.com/preservim/nerdtree/pull/814) ++ - Fix focussing previous buffer when closing NERDTree (mrubli) [#801](https://github.com/preservim/nerdtree/pull/801) ++ - Update the docs for "NERDTreeStatusline" (lifecrisis) [#796](https://github.com/preservim/nerdtree/pull/796) ++ - BUGFIX: Unstable behavior in the "getPath()" method (lifecrisis) [#795](https://github.com/preservim/nerdtree/pull/795) ++ - Revert the bugfix from pull request [#785](https://github.com/preservim/nerdtree/pull/785) (lifecrisis) [#794](https://github.com/preservim/nerdtree/pull/794) ++ - BUGFIX: Allow ":NERDTreeFind" to discover hidden files (lifecrisis) [#786](https://github.com/preservim/nerdtree/pull/786) ++ - BUGFIX: Allow ":NERDTreeFind" to reveal new files (lifecrisis) [#785](https://github.com/preservim/nerdtree/pull/785) ++ - Add modelines (lifecrisis) [#782](https://github.com/preservim/nerdtree/pull/782) ++ - Change the type of completion used by NERDTreeFind (lifecrisis) [#781](https://github.com/preservim/nerdtree/pull/781) ++ - change NERDTreeFind with args (zhenyangze) [#778](https://github.com/preservim/nerdtree/pull/778) ++ - Style Choice: Using confirm() when deleting a bookmark (lifecrisis) [#777](https://github.com/preservim/nerdtree/pull/777) ++ - remove useless substitute when `file =~# "/$"` (skyblueee) [#773](https://github.com/preservim/nerdtree/pull/773) ++ - remove useless removeLeadingSpaces in _stripMarkup (skyblueee) [#772](https://github.com/preservim/nerdtree/pull/772) ++ - Make the "o" mapping consistent with "x" (lifecrisis) [#769](https://github.com/preservim/nerdtree/pull/769) ++ - Fix a problem with the "x" handler (lifecrisis) [#768](https://github.com/preservim/nerdtree/pull/768) ++ - Clean up the handler for the "x" mapping (lifecrisis) [#767](https://github.com/preservim/nerdtree/pull/767) ++ - Revert change to tab opening method (lifecrisis) [#766](https://github.com/preservim/nerdtree/pull/766) ++ - BUGFIX: Add back support for "b:NERDTreeRoot" (lifecrisis) [#765](https://github.com/preservim/nerdtree/pull/765) ++ - Fix broken "t" and "T" mappings, tabs now open at end (lifecrisis) [#759](https://github.com/preservim/nerdtree/pull/759) ++ - Update doc with already existing mapping variables (asnr) [#699](https://github.com/preservim/nerdtree/pull/699) ++ - Fix the broken g:NERDTreeBookmarksSort setting (lifecrisis) [#696](https://github.com/preservim/nerdtree/pull/696) ++ - Correct NERDTreeIgnore pattern in doc (cntoplolicon) [#648](https://github.com/preservim/nerdtree/pull/648) ++ - Remove empty segments when splitting path (sooth-sayer) [#574](https://github.com/preservim/nerdtree/pull/574) ++ - Suppress autocmds less agressively (wincent) [#578](https://github.com/preservim/nerdtree/pull/578) [#691](https://github.com/preservim/nerdtree/pull/691) + - Add an Issues template to ask for more info initially. +- - Fix markdown headers in readme (josephfrazier) [#676](https://github.com/scrooloose/nerdtree/pull/676) ++ - Fix markdown headers in readme (josephfrazier) [#676](https://github.com/preservim/nerdtree/pull/676) + - Don't touch `@o` and `@h` registers when rendering +- - Fix bug with files and directories with dollar signs (alegen) [#649](https://github.com/scrooloose/nerdtree/pull/649) +- - Reuse/reopen existing window trees where possible [#244](https://github.com/scrooloose/nerdtree/pull/244) ++ - Fix bug with files and directories with dollar signs (alegen) [#649](https://github.com/preservim/nerdtree/pull/649) ++ - Reuse/reopen existing window trees where possible [#244](https://github.com/preservim/nerdtree/pull/244) + - Remove NERDTree.previousBuf() +- - Change color of arrow (Leeiio) [#630](https://github.com/scrooloose/nerdtree/pull/630) +- - Improved a tip in README.markdown (ggicci) [#628](https://github.com/scrooloose/nerdtree/pull/628) +- - Shorten delete confimration of empty directory to `y` (mikeperri) [#530](https://github.com/scrooloose/nerdtree/pull/530) +- - Fix API call to open directory tree in window (devm33) [#533](https://github.com/scrooloose/nerdtree/pull/533) +- - Change default arrows on non-Windows platforms (gwilk) [#546](https://github.com/scrooloose/nerdtree/pull/546) +- - Update to README - combine cd and git clone (zwhitchcox) [#584](https://github.com/scrooloose/nerdtree/pull/584) +- - Update to README - Tip: start NERDTree when vim starts (therealplato) [#593](https://github.com/scrooloose/nerdtree/pull/593) +- - Escape filename when moving an open buffer (zacharyvoase) [#595](https://github.com/scrooloose/nerdtree/pull/595) +- - Fixed incorrect :helptags command in README (curran) [#619](https://github.com/scrooloose/nerdtree/pull/619) +- - Fixed incomplete escaping of folder arrows (adityanatraj) [#548](https://github.com/scrooloose/nerdtree/pull/548) +- - Added NERDTreeCascadeSingleChildDir option (juanibiapina) [#558](https://github.com/scrooloose/nerdtree/pull/558) ++ - Change color of arrow (Leeiio) [#630](https://github.com/preservim/nerdtree/pull/630) ++ - Improved a tip in README.markdown (ggicci) [#628](https://github.com/preservim/nerdtree/pull/628) ++ - Shorten delete confimration of empty directory to `y` (mikeperri) [#530](https://github.com/preservim/nerdtree/pull/530) ++ - Fix API call to open directory tree in window (devm33) [#533](https://github.com/preservim/nerdtree/pull/533) ++ - Change default arrows on non-Windows platforms (gwilk) [#546](https://github.com/preservim/nerdtree/pull/546) ++ - Update to README - combine cd and git clone (zwhitchcox) [#584](https://github.com/preservim/nerdtree/pull/584) ++ - Update to README - Tip: start NERDTree when vim starts (therealplato) [#593](https://github.com/preservim/nerdtree/pull/593) ++ - Escape filename when moving an open buffer (zacharyvoase) [#595](https://github.com/preservim/nerdtree/pull/595) ++ - Fixed incorrect :helptags command in README (curran) [#619](https://github.com/preservim/nerdtree/pull/619) ++ - Fixed incomplete escaping of folder arrows (adityanatraj) [#548](https://github.com/preservim/nerdtree/pull/548) ++ - Added NERDTreeCascadeSingleChildDir option (juanibiapina) [#558](https://github.com/preservim/nerdtree/pull/558) + - Replace strchars() with backward compatible workaround. +- - Add support for copy command in Windows (SkylerLipthay) [#231](https://github.com/scrooloose/nerdtree/pull/231) ++ - Add support for copy command in Windows (SkylerLipthay) [#231](https://github.com/preservim/nerdtree/pull/231) + - Fixed typo in README.markdown - :Helptags -> :helptags + - Rename "primary" and "secondary" trees to "tab" and "window" trees. + - Move a bunch of buffer level variables into the NERDTree and UI classes. +diff --git a/README.markdown b/README.markdown +index 9e53952..a3fe4fe 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -12,7 +12,7 @@ This plugin can also be extended with custom mappings using a special API. The + details of this API and of other NERDTree features are described in the + included documentation. + +-![NERDTree Screenshot](https://github.com/scrooloose/nerdtree/raw/master/screenshot.png) ++![NERDTree Screenshot](https://github.com/preservim/nerdtree/raw/master/screenshot.png) + + Installation + ------------ +@@ -24,7 +24,7 @@ Below are just some of the methods for installing NERDTree. Do not follow all of + If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: + + ```bash +-git clone https://github.com/scrooloose/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree + vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q + ``` + +@@ -34,7 +34,7 @@ Otherwise, these are some of the several 3rd-party plugin managers you can choos + + In the terminal, + ```bash +-git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree ++git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree + ``` + In your vimrc, + ```vim +@@ -48,23 +48,23 @@ Then reload vim, run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. + #### [Vundle.vim](https://github.com/VundleVim/Vundle.vim) + ```vim + call vundle#begin() +-Plugin 'scrooloose/nerdtree' ++Plugin 'preservim/nerdtree' + call vundle#end() + ``` + + #### [vim-plug](https://github.com/junegunn/vim-plug) + ```vim + call plug#begin() +-Plug 'scrooloose/nerdtree' ++Plug 'preservim/nerdtree' + call plug#end() + ``` + + #### [apt-vim](https://github.com/egalpin/apt-vim) + ```bash +-apt-vim install -y https://github.com/scrooloose/nerdtree.git ++apt-vim install -y https://github.com/preservim/nerdtree.git + ``` + +-F.A.Q. (here, and in the [Wiki](https://github.com/scrooloose/nerdtree/wiki)) ++F.A.Q. (here, and in the [Wiki](https://github.com/preservim/nerdtree/wiki)) + ------ + + #### Is there any support for `git` flags? +@@ -133,7 +133,7 @@ autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isT + --- + #### Can I have different highlighting for different file extensions? + +-See here: https://github.com/scrooloose/nerdtree/issues/433#issuecomment-92590696 ++See here: https://github.com/preservim/nerdtree/issues/433#issuecomment-92590696 + + --- + #### How can I change default arrows? +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index be0011d..857e682 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -1238,7 +1238,7 @@ This character is used to separate the file or directory name from the rest of + the characters in the line of text. It allows filenames to contain special + characters that are otherwise used in the NERDTree, such as square brackets, + braces, trailing asterisk, and leading space. For more details, see the +-responsible pull request: https://github.com/scrooloose/nerdtree/pull/868. ++responsible pull request: https://github.com/preservim/nerdtree/pull/868. + + The default value of this variable depends on the features compiled into your + vim and the values of |NERDTreeDirArrowCollapsible| and +@@ -1498,11 +1498,11 @@ in the fridge for later ;) + Martyzilla recruited two other unwitting accomplices to become his minions in + his quest to conquer the Vim plugin world. While he may still love to receive + your emails, the best way to send suggestions, bug reports, and questions is +-to submit an issue at http://github.com/scrooloose/nerdtree/issues. ++to submit an issue at http://github.com/preservim/nerdtree/issues. + + The latest stable and development versions are on Github. +- Stable: http://github.com/scrooloose/nerdtree (master branch) +- Development: http://github.com/scrooloose/nerdtree/branches ++ Stable: http://github.com/preservim/nerdtree (master branch) ++ Development: http://github.com/preservim/nerdtree/branches + + Title Credit: + * http://ascii.co.uk/art/tree diff --git a/tasks/preservim__nerdtree-1072/tests/test.sh b/tasks/preservim__nerdtree-1072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..370235d461963ad659034042b59fb59991a76793 --- /dev/null +++ b/tasks/preservim__nerdtree-1072/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 97fb849a29d74a9cceeca92472f770d81473c780 > "$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/preservim__nerdtree-1072/tests/verifier.py b/tasks/preservim__nerdtree-1072/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1072/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/preservim__nerdtree-1075/environment/Dockerfile b/tasks/preservim__nerdtree-1075/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d24a26eaa18bca2ab52499e202f0817168c99098 --- /dev/null +++ b/tasks/preservim__nerdtree-1075/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8a14891241e3468f9c13deaa6cf88aebe53b519f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8a14891241e3468f9c13deaa6cf88aebe53b519f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8a14891241e3468f9c13deaa6cf88aebe53b519f \ + && 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/preservim__nerdtree-1075/instruction.md b/tasks/preservim__nerdtree-1075/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b255c5f8060ace2c45333305a9a2c29b19e61a --- /dev/null +++ b/tasks/preservim__nerdtree-1075/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Fix regex that finds keyword for minimal menu. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a14891241e3`. 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/preservim__nerdtree-1075/solution/patch.diff b/tasks/preservim__nerdtree-1075/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ab97f3a0ed61dcd8124b01e56f24c92ce640f05b --- /dev/null +++ b/tasks/preservim__nerdtree-1075/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 1da3cde..c8989ef 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) + - **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/preservim/nerdtree/pull/1067) +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index ca93efa..952c67b 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -62,7 +62,7 @@ function! s:MenuController._echoPrompt() + + if self.isMinimal() + let selection = self.menuItems[self.selection].text +- let keyword = matchstr(selection, '\([^ ]*') ++ let keyword = matchstr(selection, '[^ ]*([^ ]*') + + let shortcuts = map(copy(self.menuItems), "v:val['shortcut']") + let shortcuts[self.selection] = ' ' . keyword . ' ' diff --git a/tasks/preservim__nerdtree-1075/solution/solve.sh b/tasks/preservim__nerdtree-1075/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1075/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/preservim__nerdtree-1075/task.toml b/tasks/preservim__nerdtree-1075/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c3cc82730254a837dc126e22cabe7fca47f2f52e --- /dev/null +++ b/tasks/preservim__nerdtree-1075/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1075" +description = "Fix regex that finds keyword for minimal menu." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "8a14891241e3468f9c13deaa6cf88aebe53b519f" +reference = "https://github.com/preservim/nerdtree/pull/1075" +source_access = "auto" +built_at = "2026-11-16T16:10:02.415931+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:49ba3796092ed6a6909ec2e126cd1bd872f82c0e1951759058799269fb34c472" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-06T14:21:11Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/menu_controller.vim", +] +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:02.571754+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b86aa50168de24d284043941977fc9ecd641f3c64ecdea5911a48bb007a9c9b1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1075/tests/capture.py b/tasks/preservim__nerdtree-1075/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1075/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/preservim__nerdtree-1075/tests/instruction.md b/tasks/preservim__nerdtree-1075/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b255c5f8060ace2c45333305a9a2c29b19e61a --- /dev/null +++ b/tasks/preservim__nerdtree-1075/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Fix regex that finds keyword for minimal menu. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a14891241e3`. 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/preservim__nerdtree-1075/tests/oracle.patch b/tasks/preservim__nerdtree-1075/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ab97f3a0ed61dcd8124b01e56f24c92ce640f05b --- /dev/null +++ b/tasks/preservim__nerdtree-1075/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 1da3cde..c8989ef 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) + - **.0**: Allow use of function references as callbacks (HiPhish) [#1067](https://github.com/preservim/nerdtree/pull/1067) +diff --git a/lib/nerdtree/menu_controller.vim b/lib/nerdtree/menu_controller.vim +index ca93efa..952c67b 100644 +--- a/lib/nerdtree/menu_controller.vim ++++ b/lib/nerdtree/menu_controller.vim +@@ -62,7 +62,7 @@ function! s:MenuController._echoPrompt() + + if self.isMinimal() + let selection = self.menuItems[self.selection].text +- let keyword = matchstr(selection, '\([^ ]*') ++ let keyword = matchstr(selection, '[^ ]*([^ ]*') + + let shortcuts = map(copy(self.menuItems), "v:val['shortcut']") + let shortcuts[self.selection] = ' ' . keyword . ' ' diff --git a/tasks/preservim__nerdtree-1075/tests/test.sh b/tasks/preservim__nerdtree-1075/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bab1773b713dbd56ee7064a11c3fc0333308e4d0 --- /dev/null +++ b/tasks/preservim__nerdtree-1075/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 8a14891241e3468f9c13deaa6cf88aebe53b519f > "$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/preservim__nerdtree-1075/tests/verifier.py b/tasks/preservim__nerdtree-1075/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1075/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/preservim__nerdtree-1079/environment/Dockerfile b/tasks/preservim__nerdtree-1079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2916a815d12b2027162fd0513be18c2712091f68 --- /dev/null +++ b/tasks/preservim__nerdtree-1079/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ee79ecfb67e4403e54ea59c175ca4d39544395e8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ee79ecfb67e4403e54ea59c175ca4d39544395e8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ee79ecfb67e4403e54ea59c175ca4d39544395e8 \ + && 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/preservim__nerdtree-1079/instruction.md b/tasks/preservim__nerdtree-1079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f083e16ed577d3361fb41119d7989cbd3d11cd8 --- /dev/null +++ b/tasks/preservim__nerdtree-1079/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Prevent overwriting existing files/dirs on node move. (m-m) + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ee79ecfb67e4`. 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/preservim__nerdtree-1079/solution/patch.diff b/tasks/preservim__nerdtree-1079/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ddeafe15f9a6b37c8b5d4d3db83c848fcf6724b9 --- /dev/null +++ b/tasks/preservim__nerdtree-1079/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index c8989ef..d1c4500 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 3ecfa81..87ec0cf 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -196,6 +196,11 @@ function! NERDTreeMoveNode() + let curNode = g:NERDTreeFileNode.GetSelected() + let prompt = s:inputPrompt('move') + let newNodePath = input(prompt, curNode.path.str(), 'file') ++ while filereadable(newNodePath) ++ call nerdtree#echoWarning('This destination already exists. Try again.') ++ let newNodePath = input(prompt, curNode.path.str(), 'file') ++ endwhile ++ + + if newNodePath ==# '' + call nerdtree#echo('Node Renaming Aborted.') diff --git a/tasks/preservim__nerdtree-1079/solution/solve.sh b/tasks/preservim__nerdtree-1079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1079/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/preservim__nerdtree-1079/task.toml b/tasks/preservim__nerdtree-1079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..938c1bb6010bc18efcfdb11db2c14967366bb90b --- /dev/null +++ b/tasks/preservim__nerdtree-1079/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1079" +description = "Prevent overwriting existing files/dirs on node move. (m-m)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "ee79ecfb67e4403e54ea59c175ca4d39544395e8" +reference = "https://github.com/preservim/nerdtree/pull/1079" +source_access = "auto" +built_at = "2026-11-16T16:10:02.444650+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:40423c64c80bbaddbcf5623d055f6afc9ec6d11a692d0e71ad45b2bb419fb23c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-16T00:55:31Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "nerdtree_plugin/fs_menu.vim", +] +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:02.572268+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d52285727da9a87f88db1943dd703f0ca4616b3c4ab47f644b59a285e6e7d7c8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1079/tests/capture.py b/tasks/preservim__nerdtree-1079/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1079/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/preservim__nerdtree-1079/tests/instruction.md b/tasks/preservim__nerdtree-1079/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f083e16ed577d3361fb41119d7989cbd3d11cd8 --- /dev/null +++ b/tasks/preservim__nerdtree-1079/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Prevent overwriting existing files/dirs on node move. (m-m) + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ee79ecfb67e4`. 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/preservim__nerdtree-1079/tests/oracle.patch b/tasks/preservim__nerdtree-1079/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ddeafe15f9a6b37c8b5d4d3db83c848fcf6724b9 --- /dev/null +++ b/tasks/preservim__nerdtree-1079/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index c8989ef..d1c4500 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) + - **.1**: Ensure backward compatibility. v:t_func is not available before Vim 8.0 (Phil Runninger) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 3ecfa81..87ec0cf 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -196,6 +196,11 @@ function! NERDTreeMoveNode() + let curNode = g:NERDTreeFileNode.GetSelected() + let prompt = s:inputPrompt('move') + let newNodePath = input(prompt, curNode.path.str(), 'file') ++ while filereadable(newNodePath) ++ call nerdtree#echoWarning('This destination already exists. Try again.') ++ let newNodePath = input(prompt, curNode.path.str(), 'file') ++ endwhile ++ + + if newNodePath ==# '' + call nerdtree#echo('Node Renaming Aborted.') diff --git a/tasks/preservim__nerdtree-1079/tests/test.sh b/tasks/preservim__nerdtree-1079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..86b7fda521f6920b27f47acae5e8ed86858bb3ce --- /dev/null +++ b/tasks/preservim__nerdtree-1079/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 ee79ecfb67e4403e54ea59c175ca4d39544395e8 > "$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/preservim__nerdtree-1079/tests/verifier.py b/tasks/preservim__nerdtree-1079/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1079/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/preservim__nerdtree-1080/environment/Dockerfile b/tasks/preservim__nerdtree-1080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d93b1f95e594b1ca9f3ee864aa5ef03c5054dcec --- /dev/null +++ b/tasks/preservim__nerdtree-1080/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 901aba632bab6d984a5f651dd859bae8a180e30e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 901aba632bab6d984a5f651dd859bae8a180e30e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 901aba632bab6d984a5f651dd859bae8a180e30e \ + && 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/preservim__nerdtree-1080/instruction.md b/tasks/preservim__nerdtree-1080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffd5e55e8da4226cb1fd0699a8687b8646dab8c1 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Ensure events are (or aren't) being ignored correctly. + +## Description + +### Description of Changes + + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `901aba632bab`. 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/preservim__nerdtree-1080/solution/patch.diff b/tasks/preservim__nerdtree-1080/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cffa212a7cd7460514c3db097120d4c706e59872 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/solution/patch.diff @@ -0,0 +1,78 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d1c4500..7f7dcc1 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) + - **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 5c9af89..156b260 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -169,8 +169,11 @@ function! nerdtree#exec(cmd, ignoreAll) abort + if a:ignoreAll + set eventignore=all + endif +- exec a:cmd +- let &eventignore = old_ei ++ try ++ exec a:cmd ++ finally ++ let &eventignore = old_ei ++ endtry + endfunction + + " FUNCTION: nerdtree#has_opt(options, name) {{{2 +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 39e3f55..67fd3ce 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -333,14 +333,17 @@ function! s:Creator._tabpagevar(tabnr, var) + let old_ei = &eventignore + set eventignore=all + +- exec 'tabnext ' . a:tabnr +- let v = -1 +- if exists('t:' . a:var) +- exec 'let v = t:' . a:var +- endif +- exec 'tabnext ' . currentTab ++ try ++ exec 'tabnext ' . a:tabnr ++ let v = -1 ++ if exists('t:' . a:var) ++ exec 'let v = t:' . a:var ++ endif ++ exec 'tabnext ' . currentTab + +- let &eventignore = old_ei ++ finally ++ let &eventignore = old_ei ++ endtry + + return v + endfunction +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 87ec0cf..281116f 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -141,12 +141,12 @@ function! s:renameBuffer(bufNum, newNodeName, isDirectory) + let editStr = g:NERDTreePath.New(a:newNodeName).str({'format': 'Edit'}) + endif + " 1. ensure that a new buffer is loaded +- call nerdtree#exec('badd ' . quotedFileName, 1) ++ call nerdtree#exec('badd ' . quotedFileName, 0) + " 2. ensure that all windows which display the just deleted filename + " display a buffer for a new filename. + let s:originalTabNumber = tabpagenr() + let s:originalWindowNumber = winnr() +- call nerdtree#exec('tabdo windo if winbufnr(0) ==# ' . a:bufNum . " | exec ':e! " . editStr . "' | endif", 1) ++ call nerdtree#exec('tabdo windo if winbufnr(0) ==# ' . a:bufNum . " | exec ':e! " . editStr . "' | endif", 0) + call nerdtree#exec('tabnext ' . s:originalTabNumber, 1) + call nerdtree#exec(s:originalWindowNumber . 'wincmd w', 1) + " 3. We don't need a previous buffer anymore diff --git a/tasks/preservim__nerdtree-1080/solution/solve.sh b/tasks/preservim__nerdtree-1080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1080/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/preservim__nerdtree-1080/task.toml b/tasks/preservim__nerdtree-1080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9846005883520a288601411bcf35c8ddab19303 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1080" +description = "Ensure events are (or aren't) being ignored correctly." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "901aba632bab6d984a5f651dd859bae8a180e30e" +reference = "https://github.com/preservim/nerdtree/pull/1080" +source_access = "auto" +built_at = "2026-11-16T16:10:02.443268+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6134bf10f9af258e728d27ccf89dc65258e5699beb4ad200033e0b44938e7386" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-16T18:29:34Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", + "lib/nerdtree/creator.vim", + "nerdtree_plugin/fs_menu.vim", +] +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:02.572812+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:08ecb3747a039de8f8d2a4d2f972cab649fe262a71683650eab9c9c9c5afe6d6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1080/tests/capture.py b/tasks/preservim__nerdtree-1080/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1080/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/preservim__nerdtree-1080/tests/instruction.md b/tasks/preservim__nerdtree-1080/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffd5e55e8da4226cb1fd0699a8687b8646dab8c1 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Ensure events are (or aren't) being ignored correctly. + +## Description + +### Description of Changes + + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `901aba632bab`. 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/preservim__nerdtree-1080/tests/oracle.patch b/tasks/preservim__nerdtree-1080/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cffa212a7cd7460514c3db097120d4c706e59872 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/tests/oracle.patch @@ -0,0 +1,78 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d1c4500..7f7dcc1 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) + - **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) + - **.2**: Lint vimscript, fix errors and warnings, add CI job to review PRs (Caleb Maclennan) [#1071](https://github.com/preservim/nerdtree/pull/1071) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 5c9af89..156b260 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -169,8 +169,11 @@ function! nerdtree#exec(cmd, ignoreAll) abort + if a:ignoreAll + set eventignore=all + endif +- exec a:cmd +- let &eventignore = old_ei ++ try ++ exec a:cmd ++ finally ++ let &eventignore = old_ei ++ endtry + endfunction + + " FUNCTION: nerdtree#has_opt(options, name) {{{2 +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 39e3f55..67fd3ce 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -333,14 +333,17 @@ function! s:Creator._tabpagevar(tabnr, var) + let old_ei = &eventignore + set eventignore=all + +- exec 'tabnext ' . a:tabnr +- let v = -1 +- if exists('t:' . a:var) +- exec 'let v = t:' . a:var +- endif +- exec 'tabnext ' . currentTab ++ try ++ exec 'tabnext ' . a:tabnr ++ let v = -1 ++ if exists('t:' . a:var) ++ exec 'let v = t:' . a:var ++ endif ++ exec 'tabnext ' . currentTab + +- let &eventignore = old_ei ++ finally ++ let &eventignore = old_ei ++ endtry + + return v + endfunction +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 87ec0cf..281116f 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -141,12 +141,12 @@ function! s:renameBuffer(bufNum, newNodeName, isDirectory) + let editStr = g:NERDTreePath.New(a:newNodeName).str({'format': 'Edit'}) + endif + " 1. ensure that a new buffer is loaded +- call nerdtree#exec('badd ' . quotedFileName, 1) ++ call nerdtree#exec('badd ' . quotedFileName, 0) + " 2. ensure that all windows which display the just deleted filename + " display a buffer for a new filename. + let s:originalTabNumber = tabpagenr() + let s:originalWindowNumber = winnr() +- call nerdtree#exec('tabdo windo if winbufnr(0) ==# ' . a:bufNum . " | exec ':e! " . editStr . "' | endif", 1) ++ call nerdtree#exec('tabdo windo if winbufnr(0) ==# ' . a:bufNum . " | exec ':e! " . editStr . "' | endif", 0) + call nerdtree#exec('tabnext ' . s:originalTabNumber, 1) + call nerdtree#exec(s:originalWindowNumber . 'wincmd w', 1) + " 3. We don't need a previous buffer anymore diff --git a/tasks/preservim__nerdtree-1080/tests/test.sh b/tasks/preservim__nerdtree-1080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8786f0e678909e575144cd9a34103ff94b435273 --- /dev/null +++ b/tasks/preservim__nerdtree-1080/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 901aba632bab6d984a5f651dd859bae8a180e30e > "$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/preservim__nerdtree-1080/tests/verifier.py b/tasks/preservim__nerdtree-1080/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1080/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/preservim__nerdtree-1081/environment/Dockerfile b/tasks/preservim__nerdtree-1081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6474db1c4af992bf5f86d9263b7091fc26fbd5f2 --- /dev/null +++ b/tasks/preservim__nerdtree-1081/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 26740d1157dc1befe2a088052e10cf00436a5003 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 26740d1157dc1befe2a088052e10cf00436a5003 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 26740d1157dc1befe2a088052e10cf00436a5003 \ + && 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/preservim__nerdtree-1081/instruction.md b/tasks/preservim__nerdtree-1081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4fe0a0d6422eeb34af7440587584ca14916b435a --- /dev/null +++ b/tasks/preservim__nerdtree-1081/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** [BUGFIX] Shows error for empty filenames (vim-startify) + +## Description + +### Description of Changes + +There was a fix in #1043 which improves the behavior for non saved filenames. Those are not on disk, but also not empty. This lead to an issue #1059 where actual "empty files" like created with vim-startify or stdin lead to an error. This change fixes this by adapting the order of the tests. It'll print "no file for the current buffer" for empty files. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26740d1157dc`. 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/preservim__nerdtree-1081/solution/patch.diff b/tasks/preservim__nerdtree-1081/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bb639d54dee2ea35df265b37d41fae0bacb981f4 --- /dev/null +++ b/tasks/preservim__nerdtree-1081/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 7f7dcc1..2576d47 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.6:** NERDTreeFind shows expected message if file doesn't exist e.g. with vim-startify (andys8). [#1081](https://github.com/preservim/nerdtree/pull/1081) + - **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) + - **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 400e52d..57af126 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,15 +284,16 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) abort + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') +- if !filereadable(l:pathStr) +- let l:pathStr = fnamemodify(l:pathStr, ':h') +- endif + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') + return + endif + ++ if !filereadable(l:pathStr) ++ let l:pathStr = fnamemodify(l:pathStr, ':h') ++ endif ++ + try + let l:pathStr = g:NERDTreePath.Resolve(l:pathStr) + let l:pathObj = g:NERDTreePath.New(l:pathStr) diff --git a/tasks/preservim__nerdtree-1081/solution/solve.sh b/tasks/preservim__nerdtree-1081/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1081/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/preservim__nerdtree-1081/task.toml b/tasks/preservim__nerdtree-1081/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e882c62e9e621fbde2d845101075267a596c68f8 --- /dev/null +++ b/tasks/preservim__nerdtree-1081/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1081" +description = "[BUGFIX] Shows error for empty filenames (vim-startify)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "26740d1157dc1befe2a088052e10cf00436a5003" +reference = "https://github.com/preservim/nerdtree/pull/1081" +source_access = "auto" +built_at = "2026-11-16T16:10:02.441801+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c702682d460a693ccc8ebd1d1f1ca329982179970331b806ce91ca52fb3296e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-28T01:37:48Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", +] +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:02.573327+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:92bad29ce9ff2dfcf04389d588a514b684aba20533cb290db2af1ad6fbeebe03" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1081/tests/capture.py b/tasks/preservim__nerdtree-1081/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1081/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/preservim__nerdtree-1081/tests/instruction.md b/tasks/preservim__nerdtree-1081/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4fe0a0d6422eeb34af7440587584ca14916b435a --- /dev/null +++ b/tasks/preservim__nerdtree-1081/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** [BUGFIX] Shows error for empty filenames (vim-startify) + +## Description + +### Description of Changes + +There was a fix in #1043 which improves the behavior for non saved filenames. Those are not on disk, but also not empty. This lead to an issue #1059 where actual "empty files" like created with vim-startify or stdin lead to an error. This change fixes this by adapting the order of the tests. It'll print "no file for the current buffer" for empty files. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `26740d1157dc`. 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/preservim__nerdtree-1081/tests/oracle.patch b/tasks/preservim__nerdtree-1081/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bb639d54dee2ea35df265b37d41fae0bacb981f4 --- /dev/null +++ b/tasks/preservim__nerdtree-1081/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 7f7dcc1..2576d47 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.4 ++- **.6:** NERDTreeFind shows expected message if file doesn't exist e.g. with vim-startify (andys8). [#1081](https://github.com/preservim/nerdtree/pull/1081) + - **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) + - **.4**: Prevent overwriting existing files/dirs on node move. (PhilRunninger) [#1079](https://github.com/preservim/nerdtree/pull/1079) + - **.3**: Fix regex that finds keyword for minimal menu. (PhilRunninger) [#1075](https://github.com/preservim/nerdtree/pull/1075) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 400e52d..57af126 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,15 +284,16 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) abort + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') +- if !filereadable(l:pathStr) +- let l:pathStr = fnamemodify(l:pathStr, ':h') +- endif + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') + return + endif + ++ if !filereadable(l:pathStr) ++ let l:pathStr = fnamemodify(l:pathStr, ':h') ++ endif ++ + try + let l:pathStr = g:NERDTreePath.Resolve(l:pathStr) + let l:pathObj = g:NERDTreePath.New(l:pathStr) diff --git a/tasks/preservim__nerdtree-1081/tests/test.sh b/tasks/preservim__nerdtree-1081/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b7b7545dd37bc6f607f898022f9fc455bcc8c85 --- /dev/null +++ b/tasks/preservim__nerdtree-1081/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 26740d1157dc1befe2a088052e10cf00436a5003 > "$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/preservim__nerdtree-1081/tests/verifier.py b/tasks/preservim__nerdtree-1081/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1081/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/preservim__nerdtree-1083/environment/Dockerfile b/tasks/preservim__nerdtree-1083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59709275c2b91aa1a26a6e4229001f10bf208289 --- /dev/null +++ b/tasks/preservim__nerdtree-1083/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f7b09634ba2305d19cd4c73988452698c93f74d3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f7b09634ba2305d19cd4c73988452698c93f74d3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f7b09634ba2305d19cd4c73988452698c93f74d3 \ + && 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/preservim__nerdtree-1083/instruction.md b/tasks/preservim__nerdtree-1083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70384a0a1b04140f3838876b73eebde497d4e25b --- /dev/null +++ b/tasks/preservim__nerdtree-1083/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** :NERDTreeToggle always sets NERDTree root. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f7b09634ba23`. 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/preservim__nerdtree-1083/solution/patch.diff b/tasks/preservim__nerdtree-1083/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ab4d186d8b0e544564fdb9ab8ffc187f7852b76f --- /dev/null +++ b/tasks/preservim__nerdtree-1083/solution/patch.diff @@ -0,0 +1,59 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index edbcfae..e163c6c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -7,6 +7,8 @@ + in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.5 ++- **.0**: `NERDTreeToggle ` always sets NERDTree root. (PhilRunninger) [#1083](https://github.com/preservim/nerdtree/pull/1083) + #### 6.4 + - **.6**: NERDTreeFind shows expected message if file doesn't exist e.g. with vim-startify (andys8). [#1081](https://github.com/preservim/nerdtree/pull/1081) + - **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 857e682..e2dd56a 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -122,8 +122,9 @@ The following features and functionality are provided by the NERDTree: + + :NERDTreeToggle [ | ] *:NERDTreeToggle* + If a NERDTree already exists for this tab, it is reopened and rendered +- again. If no NERDTree exists for this tab then this command acts the +- same as the |:NERDTree| command. ++ again. If or is given, the root of NERDTree ++ is set to that path. If no NERDTree exists for this tab then this command ++ acts the same as the |:NERDTree| command. + + :NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* + Like |:NERDTreeToggle|, but searches up the directory tree to find the top of +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 67fd3ce..e2b3fa0 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -355,17 +355,20 @@ function! s:Creator.ToggleTabTree(dir) + endfunction + + " FUNCTION: s:Creator.toggleTabTree(dir) {{{1 +-" Toggles the NERD tree. I.e the NERD tree is open, it is closed, if it is +-" closed it is restored or initialized (if it doesnt exist) ++" Toggles the NERD tree. I.e if the NERD tree is open, it is closed. If it is ++" closed, it is restored or initialized. If dir is not empty, it will be set ++" as the new root. + " + " Args: +-" dir: the full path for the root node (is only used if the NERD tree is being +-" initialized. ++" dir: the full path for the root node (is used if the NERD tree is being ++" initialized, or to change the root to a new dir.) + function! s:Creator.toggleTabTree(dir) + if g:NERDTree.ExistsForTab() + if !g:NERDTree.IsOpen() + call self._createTreeWin() +- if !&hidden ++ if !empty(a:dir) ++ call self.createTabTree(a:dir) ++ elseif !&hidden + call b:NERDTree.render() + endif + call b:NERDTree.ui.restoreScreenState() diff --git a/tasks/preservim__nerdtree-1083/solution/solve.sh b/tasks/preservim__nerdtree-1083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1083/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/preservim__nerdtree-1083/task.toml b/tasks/preservim__nerdtree-1083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b82d2af3e24d5f5c4d7b38d5e0786ade3355884f --- /dev/null +++ b/tasks/preservim__nerdtree-1083/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1083" +description = ":NERDTreeToggle always sets NERDTree root." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "f7b09634ba2305d19cd4c73988452698c93f74d3" +reference = "https://github.com/preservim/nerdtree/pull/1083" +source_access = "auto" +built_at = "2026-11-16T16:10:02.440460+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8ff4a65879677348d66cf8cf9faceab2fa298135badd267cbc9a5ef065e1f114" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-01-28T08:59:25Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "doc/NERDTree.txt", + "lib/nerdtree/creator.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +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:02.573842+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9eaea731344ca8c7beb81742c2bc3632565694f3ae5749a1a3248c95e5fb916c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1083/tests/capture.py b/tasks/preservim__nerdtree-1083/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1083/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/preservim__nerdtree-1083/tests/instruction.md b/tasks/preservim__nerdtree-1083/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70384a0a1b04140f3838876b73eebde497d4e25b --- /dev/null +++ b/tasks/preservim__nerdtree-1083/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** :NERDTreeToggle always sets NERDTree root. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f7b09634ba23`. 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/preservim__nerdtree-1083/tests/oracle.patch b/tasks/preservim__nerdtree-1083/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ab4d186d8b0e544564fdb9ab8ffc187f7852b76f --- /dev/null +++ b/tasks/preservim__nerdtree-1083/tests/oracle.patch @@ -0,0 +1,59 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index edbcfae..e163c6c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -7,6 +7,8 @@ + in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.5 ++- **.0**: `NERDTreeToggle ` always sets NERDTree root. (PhilRunninger) [#1083](https://github.com/preservim/nerdtree/pull/1083) + #### 6.4 + - **.6**: NERDTreeFind shows expected message if file doesn't exist e.g. with vim-startify (andys8). [#1081](https://github.com/preservim/nerdtree/pull/1081) + - **.5**: Ensure events are (or aren't) being ignored correctly. (PhilRunninger) [#1080](https://github.com/preservim/nerdtree/pull/1080) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 857e682..e2dd56a 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -122,8 +122,9 @@ The following features and functionality are provided by the NERDTree: + + :NERDTreeToggle [ | ] *:NERDTreeToggle* + If a NERDTree already exists for this tab, it is reopened and rendered +- again. If no NERDTree exists for this tab then this command acts the +- same as the |:NERDTree| command. ++ again. If or is given, the root of NERDTree ++ is set to that path. If no NERDTree exists for this tab then this command ++ acts the same as the |:NERDTree| command. + + :NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* + Like |:NERDTreeToggle|, but searches up the directory tree to find the top of +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 67fd3ce..e2b3fa0 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -355,17 +355,20 @@ function! s:Creator.ToggleTabTree(dir) + endfunction + + " FUNCTION: s:Creator.toggleTabTree(dir) {{{1 +-" Toggles the NERD tree. I.e the NERD tree is open, it is closed, if it is +-" closed it is restored or initialized (if it doesnt exist) ++" Toggles the NERD tree. I.e if the NERD tree is open, it is closed. If it is ++" closed, it is restored or initialized. If dir is not empty, it will be set ++" as the new root. + " + " Args: +-" dir: the full path for the root node (is only used if the NERD tree is being +-" initialized. ++" dir: the full path for the root node (is used if the NERD tree is being ++" initialized, or to change the root to a new dir.) + function! s:Creator.toggleTabTree(dir) + if g:NERDTree.ExistsForTab() + if !g:NERDTree.IsOpen() + call self._createTreeWin() +- if !&hidden ++ if !empty(a:dir) ++ call self.createTabTree(a:dir) ++ elseif !&hidden + call b:NERDTree.render() + endif + call b:NERDTree.ui.restoreScreenState() diff --git a/tasks/preservim__nerdtree-1083/tests/test.sh b/tasks/preservim__nerdtree-1083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3dd935e27b0b7c4695f74a76c52d8d648d2e55f --- /dev/null +++ b/tasks/preservim__nerdtree-1083/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 f7b09634ba2305d19cd4c73988452698c93f74d3 > "$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/preservim__nerdtree-1083/tests/verifier.py b/tasks/preservim__nerdtree-1083/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1083/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/preservim__nerdtree-1087/environment/Dockerfile b/tasks/preservim__nerdtree-1087/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..01ad270df8e0967afad7f903e3411fefa0896df2 --- /dev/null +++ b/tasks/preservim__nerdtree-1087/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 85103aa60732f50319febebdd10d954bf9782cfb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 85103aa60732f50319febebdd10d954bf9782cfb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 85103aa60732f50319febebdd10d954bf9782cfb \ + && 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/preservim__nerdtree-1087/instruction.md b/tasks/preservim__nerdtree-1087/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa2d7cf296e349bc9905dbcffdc2380e8854e9fa --- /dev/null +++ b/tasks/preservim__nerdtree-1087/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [add] How to install using dein.vim + +## Description + +### Description of Changes + +Hi, maintainer. +I added how to install using dein.vim. +Could you check this Pull Request? + +#### Reference + +> https://github.com/Shougo/dein.vim + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `85103aa60732`. 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/preservim__nerdtree-1087/solution/patch.diff b/tasks/preservim__nerdtree-1087/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..de08fa4309149f4a1d38b2308e79d4134448ecdd --- /dev/null +++ b/tasks/preservim__nerdtree-1087/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ed79ff4..a80acf2 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.6 ++- **.1**: [add] How to install using dein.vim [#1087](https://github.com/preservim/nerdtree/pull/1087) + - **.0**: Add the ability to turn off directory arrows (PhilRunninger) [#1085](https://github.com/preservim/nerdtree/pull/1085) + #### 6.5 + - **.0**: `NERDTreeToggle ` always sets NERDTree root. (PhilRunninger) [#1083](https://github.com/preservim/nerdtree/pull/1083) +diff --git a/README.markdown b/README.markdown +index cd03b51..09173a6 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -59,6 +59,13 @@ Plug 'preservim/nerdtree' + call plug#end() + ``` + ++#### [dein.vim](https://github.com/Shougo/dein.vim) ++```vim ++call dein#begin() ++call dein#add('preservim/nerdtree') ++call dein#end() ++``` ++ + #### [apt-vim](https://github.com/egalpin/apt-vim) + ```bash + apt-vim install -y https://github.com/preservim/nerdtree.git diff --git a/tasks/preservim__nerdtree-1087/solution/solve.sh b/tasks/preservim__nerdtree-1087/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1087/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/preservim__nerdtree-1087/task.toml b/tasks/preservim__nerdtree-1087/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b18639824b39d66f085174b7f508a588fde7bcd3 --- /dev/null +++ b/tasks/preservim__nerdtree-1087/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1087" +description = "[add] How to install using dein.vim" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "85103aa60732f50319febebdd10d954bf9782cfb" +reference = "https://github.com/preservim/nerdtree/pull/1087" +source_access = "auto" +built_at = "2026-11-16T16:10:02.437257+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9aef504c36ccc8c39198e36286316aa235426526c81cb1cb1c160a025327fd76" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-02-07T19:00:13Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", +] +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:02.574460+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f7092bb7b42f0c5a8321bde5ba140579669985b144427bb044c6fc8f1c2dc745" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1087/tests/capture.py b/tasks/preservim__nerdtree-1087/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1087/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/preservim__nerdtree-1087/tests/instruction.md b/tasks/preservim__nerdtree-1087/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa2d7cf296e349bc9905dbcffdc2380e8854e9fa --- /dev/null +++ b/tasks/preservim__nerdtree-1087/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** [add] How to install using dein.vim + +## Description + +### Description of Changes + +Hi, maintainer. +I added how to install using dein.vim. +Could you check this Pull Request? + +#### Reference + +> https://github.com/Shougo/dein.vim + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `85103aa60732`. 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/preservim__nerdtree-1087/tests/oracle.patch b/tasks/preservim__nerdtree-1087/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..de08fa4309149f4a1d38b2308e79d4134448ecdd --- /dev/null +++ b/tasks/preservim__nerdtree-1087/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index ed79ff4..a80acf2 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.6 ++- **.1**: [add] How to install using dein.vim [#1087](https://github.com/preservim/nerdtree/pull/1087) + - **.0**: Add the ability to turn off directory arrows (PhilRunninger) [#1085](https://github.com/preservim/nerdtree/pull/1085) + #### 6.5 + - **.0**: `NERDTreeToggle ` always sets NERDTree root. (PhilRunninger) [#1083](https://github.com/preservim/nerdtree/pull/1083) +diff --git a/README.markdown b/README.markdown +index cd03b51..09173a6 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -59,6 +59,13 @@ Plug 'preservim/nerdtree' + call plug#end() + ``` + ++#### [dein.vim](https://github.com/Shougo/dein.vim) ++```vim ++call dein#begin() ++call dein#add('preservim/nerdtree') ++call dein#end() ++``` ++ + #### [apt-vim](https://github.com/egalpin/apt-vim) + ```bash + apt-vim install -y https://github.com/preservim/nerdtree.git diff --git a/tasks/preservim__nerdtree-1087/tests/test.sh b/tasks/preservim__nerdtree-1087/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..191eb4647cd2dd2505a3b17987ca37974935a12e --- /dev/null +++ b/tasks/preservim__nerdtree-1087/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 85103aa60732f50319febebdd10d954bf9782cfb > "$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/preservim__nerdtree-1087/tests/verifier.py b/tasks/preservim__nerdtree-1087/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1087/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/preservim__nerdtree-1090/environment/Dockerfile b/tasks/preservim__nerdtree-1090/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..60ebf305c97371497863eb39a5b5d060feb56958 --- /dev/null +++ b/tasks/preservim__nerdtree-1090/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 07612557ebb4118ef4a337faa7033d0270773c71 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 07612557ebb4118ef4a337faa7033d0270773c71 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 07612557ebb4118ef4a337faa7033d0270773c71 \ + && 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/preservim__nerdtree-1090/instruction.md b/tasks/preservim__nerdtree-1090/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e22105f3278fbb9f0702a5446285713de4d778d --- /dev/null +++ b/tasks/preservim__nerdtree-1090/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Open the parent directory when revealing a non-existent file + +## Description + +Right now it just reveals the directory but leaves it closed. + +Related to #1043 + +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. + +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `07612557ebb4`. 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/preservim__nerdtree-1090/solution/patch.diff b/tasks/preservim__nerdtree-1090/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7ffda9ab1c8e6fd4b711d9ca74a9f24f910e1377 --- /dev/null +++ b/tasks/preservim__nerdtree-1090/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6309a71..54eef60 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.7 ++- **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 + - **.1**: [add] How to install using dein.vim (kazukazuinaina) [#1087](https://github.com/preservim/nerdtree/pull/1087) + - **.0**: Add the ability to turn off directory arrows (PhilRunninger) [#1085](https://github.com/preservim/nerdtree/pull/1085) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 57af126..aef1b04 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,6 +284,7 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) abort + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') ++ let l:revealOpts = {} + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') +@@ -292,6 +293,7 @@ function! s:findAndRevealPath(pathStr) abort + + if !filereadable(l:pathStr) + let l:pathStr = fnamemodify(l:pathStr, ':h') ++ let l:revealOpts['open'] = 1 + endif + + try +@@ -327,7 +329,7 @@ function! s:findAndRevealPath(pathStr) abort + call b:NERDTree.ui.setShowHidden(1) + endif + +- let l:node = b:NERDTree.root.reveal(l:pathObj) ++ let l:node = b:NERDTree.root.reveal(l:pathObj, l:revealOpts) + call b:NERDTree.render() + call l:node.putCursorHere(1, 0) + endfunction diff --git a/tasks/preservim__nerdtree-1090/solution/solve.sh b/tasks/preservim__nerdtree-1090/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1090/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/preservim__nerdtree-1090/task.toml b/tasks/preservim__nerdtree-1090/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..599b8b15aba99092215813c7e4c1a48e659ca545 --- /dev/null +++ b/tasks/preservim__nerdtree-1090/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1090" +description = "Open the parent directory when revealing a non-existent file" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "07612557ebb4118ef4a337faa7033d0270773c71" +reference = "https://github.com/preservim/nerdtree/pull/1090" +source_access = "auto" +built_at = "2026-11-16T16:10:02.417464+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6e171c54a5da5bb90012994306a18b6c8899d2eac8e75d665cca32473c15bdb5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-02-20T14:10:20Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", +] +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:02.575002+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:82e178536d72b4c1210d1d470056e4f32a2759121202f502c5c883bfe303520e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1090/tests/capture.py b/tasks/preservim__nerdtree-1090/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1090/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/preservim__nerdtree-1090/tests/instruction.md b/tasks/preservim__nerdtree-1090/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e22105f3278fbb9f0702a5446285713de4d778d --- /dev/null +++ b/tasks/preservim__nerdtree-1090/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Open the parent directory when revealing a non-existent file + +## Description + +Right now it just reveals the directory but leaves it closed. + +Related to #1043 + +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. + +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `07612557ebb4`. 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/preservim__nerdtree-1090/tests/oracle.patch b/tasks/preservim__nerdtree-1090/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7ffda9ab1c8e6fd4b711d9ca74a9f24f910e1377 --- /dev/null +++ b/tasks/preservim__nerdtree-1090/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6309a71..54eef60 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.7 ++- **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 + - **.1**: [add] How to install using dein.vim (kazukazuinaina) [#1087](https://github.com/preservim/nerdtree/pull/1087) + - **.0**: Add the ability to turn off directory arrows (PhilRunninger) [#1085](https://github.com/preservim/nerdtree/pull/1085) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 57af126..aef1b04 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -284,6 +284,7 @@ endfunction + " FUNCTION: s:findAndRevealPath(pathStr) {{{1 + function! s:findAndRevealPath(pathStr) abort + let l:pathStr = !empty(a:pathStr) ? a:pathStr : expand('%:p') ++ let l:revealOpts = {} + + if empty(l:pathStr) + call nerdtree#echoWarning('no file for the current buffer') +@@ -292,6 +293,7 @@ function! s:findAndRevealPath(pathStr) abort + + if !filereadable(l:pathStr) + let l:pathStr = fnamemodify(l:pathStr, ':h') ++ let l:revealOpts['open'] = 1 + endif + + try +@@ -327,7 +329,7 @@ function! s:findAndRevealPath(pathStr) abort + call b:NERDTree.ui.setShowHidden(1) + endif + +- let l:node = b:NERDTree.root.reveal(l:pathObj) ++ let l:node = b:NERDTree.root.reveal(l:pathObj, l:revealOpts) + call b:NERDTree.render() + call l:node.putCursorHere(1, 0) + endfunction diff --git a/tasks/preservim__nerdtree-1090/tests/test.sh b/tasks/preservim__nerdtree-1090/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..36621e7a07394bef79f0d0ba9297f0bff2c09283 --- /dev/null +++ b/tasks/preservim__nerdtree-1090/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 07612557ebb4118ef4a337faa7033d0270773c71 > "$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/preservim__nerdtree-1090/tests/verifier.py b/tasks/preservim__nerdtree-1090/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1090/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/preservim__nerdtree-1094/environment/Dockerfile b/tasks/preservim__nerdtree-1094/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..503b3b18e558e32ce0a4788f336d541849f21fcf --- /dev/null +++ b/tasks/preservim__nerdtree-1094/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e67324fdea7a192c7ce1b4c6b3c3b9f82f11eee7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e67324fdea7a192c7ce1b4c6b3c3b9f82f11eee7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e67324fdea7a192c7ce1b4c6b3c3b9f82f11eee7 \ + && 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/preservim__nerdtree-1094/instruction.md b/tasks/preservim__nerdtree-1094/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a62222d9a98b8cda8aa91d8421fa08c138cc889 --- /dev/null +++ b/tasks/preservim__nerdtree-1094/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** File Move: Escape existing directory name when looking for open files. + +## Description + +### Description of Changes + + +When a directory is renamed, all open buffers are examined to see if they live in that directory. If any such files are open, the user is asked if the files should be renamed/reopened. The problem raised in the issue is caused by said examination. The string does not have its backslashes escaped, which causes a numbered subdirectory, `\2` for example, to be treated as a regex back reference, which doesn't exist. The solution is to make sure the backslashes are escaped before doing this examination. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e67324fdea7a`. 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/preservim__nerdtree-1094/solution/patch.diff b/tasks/preservim__nerdtree-1094/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..78fb619bbb1852ecbc70816303a27f0a6b5fdb0c --- /dev/null +++ b/tasks/preservim__nerdtree-1094/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 54eef60..77b86e8 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 + - **.1**: [add] How to install using dein.vim (kazukazuinaina) [#1087](https://github.com/preservim/nerdtree/pull/1087) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 281116f..a1fa2ee 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -209,7 +209,8 @@ function! NERDTreeMoveNode() + + try + if curNode.path.isDirectory +- let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") =~# curNode.path.str() . "/.*"') ++ let l:curPath = escape(curNode.path.str(),'\') . (nerdtree#runningWindows()?'\\':'/') . '.*' ++ let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") =~# "'.escape(l:curPath,'\').'"') + else + let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") ==# curNode.path.str()') + endif diff --git a/tasks/preservim__nerdtree-1094/solution/solve.sh b/tasks/preservim__nerdtree-1094/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1094/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/preservim__nerdtree-1094/task.toml b/tasks/preservim__nerdtree-1094/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8e05d70faab42951c78484529f738145b9174fd0 --- /dev/null +++ b/tasks/preservim__nerdtree-1094/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1094" +description = "File Move: Escape existing directory name when looking for open files." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "e67324fdea7a192c7ce1b4c6b3c3b9f82f11eee7" +reference = "https://github.com/preservim/nerdtree/pull/1094" +source_access = "auto" +built_at = "2026-11-16T16:10:02.435878+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5282f446c7eb0b74c811fd770b5add3465e74896c02cbe63153d4df238f4e353" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-03-24T19:08:06Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "nerdtree_plugin/fs_menu.vim", +] +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:02.575552+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f6b1e1163606ebc820012b2d1c285f85c05bc55b0b13d28992ace963b338d52" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1094/tests/capture.py b/tasks/preservim__nerdtree-1094/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1094/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/preservim__nerdtree-1094/tests/instruction.md b/tasks/preservim__nerdtree-1094/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a62222d9a98b8cda8aa91d8421fa08c138cc889 --- /dev/null +++ b/tasks/preservim__nerdtree-1094/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** File Move: Escape existing directory name when looking for open files. + +## Description + +### Description of Changes + + +When a directory is renamed, all open buffers are examined to see if they live in that directory. If any such files are open, the user is asked if the files should be renamed/reopened. The problem raised in the issue is caused by said examination. The string does not have its backslashes escaped, which causes a numbered subdirectory, `\2` for example, to be treated as a regex back reference, which doesn't exist. The solution is to make sure the backslashes are escaped before doing this examination. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e67324fdea7a`. 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/preservim__nerdtree-1094/tests/oracle.patch b/tasks/preservim__nerdtree-1094/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..78fb619bbb1852ecbc70816303a27f0a6b5fdb0c --- /dev/null +++ b/tasks/preservim__nerdtree-1094/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 54eef60..77b86e8 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 + - **.1**: [add] How to install using dein.vim (kazukazuinaina) [#1087](https://github.com/preservim/nerdtree/pull/1087) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 281116f..a1fa2ee 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -209,7 +209,8 @@ function! NERDTreeMoveNode() + + try + if curNode.path.isDirectory +- let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") =~# curNode.path.str() . "/.*"') ++ let l:curPath = escape(curNode.path.str(),'\') . (nerdtree#runningWindows()?'\\':'/') . '.*' ++ let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") =~# "'.escape(l:curPath,'\').'"') + else + let l:openBuffers = filter(range(1,bufnr('$')),'bufexists(v:val) && fnamemodify(bufname(v:val),":p") ==# curNode.path.str()') + endif diff --git a/tasks/preservim__nerdtree-1094/tests/test.sh b/tasks/preservim__nerdtree-1094/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..47599404ca55758401ed4629657d99e72c4ada93 --- /dev/null +++ b/tasks/preservim__nerdtree-1094/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 e67324fdea7a192c7ce1b4c6b3c3b9f82f11eee7 > "$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/preservim__nerdtree-1094/tests/verifier.py b/tasks/preservim__nerdtree-1094/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1094/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/preservim__nerdtree-1095/environment/Dockerfile b/tasks/preservim__nerdtree-1095/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ba8e3a7eadff70e72350f978feefcfeba93f31dc --- /dev/null +++ b/tasks/preservim__nerdtree-1095/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 495b4e781ad83d9290f1ba0838217f6a4255768a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 495b4e781ad83d9290f1ba0838217f6a4255768a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 495b4e781ad83d9290f1ba0838217f6a4255768a \ + && 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/preservim__nerdtree-1095/instruction.md b/tasks/preservim__nerdtree-1095/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec6585ab8a3a39a25a6b000f366457a876056b82 --- /dev/null +++ b/tasks/preservim__nerdtree-1095/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Fix infinity loop in FindParentVCSRoot + +## Description + +## Description of Changes + +Fix infinity loop in FindParentVCSRoot + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `495b4e781ad8`. 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/preservim__nerdtree-1095/solution/patch.diff b/tasks/preservim__nerdtree-1095/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..28d9d5c0f311c3ed70adb15801f5e9cd5f43451f --- /dev/null +++ b/tasks/preservim__nerdtree-1095/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 77b86e8..e318315 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 +diff --git a/nerdtree_plugin/vcs.vim b/nerdtree_plugin/vcs.vim +index 36d5427..d20e35e 100644 +--- a/nerdtree_plugin/vcs.vim ++++ b/nerdtree_plugin/vcs.vim +@@ -34,7 +34,7 @@ endfunction + function! s:FindParentVCSRoot(path) + let l:path = a:path + while !empty(l:path) && +- \ l:path._str() !~# '^\(\a:\\\|\/\)$' && ++ \ l:path._str() !~# '^\(\a:[\\\/]\|\/\)$' && + \ !isdirectory(l:path._str() . '/.git') && + \ !isdirectory(l:path._str() . '/.svn') && + \ !isdirectory(l:path._str() . '/.hg') && +@@ -42,6 +42,6 @@ function! s:FindParentVCSRoot(path) + \ !isdirectory(l:path._str() . '/_darcs') + let l:path = l:path.getParent() + endwhile +- return (empty(l:path) || l:path._str() =~# '^\(\a:\\\|\/\)$') ? a:path : l:path ++ return (empty(l:path) || l:path._str() =~# '^\(\a:[\\\/]\|\/\)$') ? a:path : l:path + endfunction + diff --git a/tasks/preservim__nerdtree-1095/solution/solve.sh b/tasks/preservim__nerdtree-1095/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1095/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/preservim__nerdtree-1095/task.toml b/tasks/preservim__nerdtree-1095/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..418035d99c992eb7b8629bb683189270b229bd8a --- /dev/null +++ b/tasks/preservim__nerdtree-1095/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1095" +description = "Fix infinity loop in FindParentVCSRoot" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "495b4e781ad83d9290f1ba0838217f6a4255768a" +reference = "https://github.com/preservim/nerdtree/pull/1095" +source_access = "auto" +built_at = "2026-11-16T16:10:02.434562+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3a7d033d81110a081efe57be02ebc6e0c2161342dce2e116cdbf6bc945395652" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-03-26T20:33:12Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "nerdtree_plugin/vcs.vim", +] +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:02.576068+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3950e6d71334a2ad5298f922fa6965aa9f53d4a9db55e25e53bfedd187254122" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1095/tests/capture.py b/tasks/preservim__nerdtree-1095/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1095/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/preservim__nerdtree-1095/tests/instruction.md b/tasks/preservim__nerdtree-1095/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ec6585ab8a3a39a25a6b000f366457a876056b82 --- /dev/null +++ b/tasks/preservim__nerdtree-1095/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Fix infinity loop in FindParentVCSRoot + +## Description + +## Description of Changes + +Fix infinity loop in FindParentVCSRoot + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `495b4e781ad8`. 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/preservim__nerdtree-1095/tests/oracle.patch b/tasks/preservim__nerdtree-1095/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..28d9d5c0f311c3ed70adb15801f5e9cd5f43451f --- /dev/null +++ b/tasks/preservim__nerdtree-1095/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 77b86e8..e318315 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) + #### 6.6 +diff --git a/nerdtree_plugin/vcs.vim b/nerdtree_plugin/vcs.vim +index 36d5427..d20e35e 100644 +--- a/nerdtree_plugin/vcs.vim ++++ b/nerdtree_plugin/vcs.vim +@@ -34,7 +34,7 @@ endfunction + function! s:FindParentVCSRoot(path) + let l:path = a:path + while !empty(l:path) && +- \ l:path._str() !~# '^\(\a:\\\|\/\)$' && ++ \ l:path._str() !~# '^\(\a:[\\\/]\|\/\)$' && + \ !isdirectory(l:path._str() . '/.git') && + \ !isdirectory(l:path._str() . '/.svn') && + \ !isdirectory(l:path._str() . '/.hg') && +@@ -42,6 +42,6 @@ function! s:FindParentVCSRoot(path) + \ !isdirectory(l:path._str() . '/_darcs') + let l:path = l:path.getParent() + endwhile +- return (empty(l:path) || l:path._str() =~# '^\(\a:\\\|\/\)$') ? a:path : l:path ++ return (empty(l:path) || l:path._str() =~# '^\(\a:[\\\/]\|\/\)$') ? a:path : l:path + endfunction + diff --git a/tasks/preservim__nerdtree-1095/tests/test.sh b/tasks/preservim__nerdtree-1095/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2aa094bc345a7c857f2246a6724f06431e9c3e2b --- /dev/null +++ b/tasks/preservim__nerdtree-1095/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 495b4e781ad83d9290f1ba0838217f6a4255768a > "$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/preservim__nerdtree-1095/tests/verifier.py b/tasks/preservim__nerdtree-1095/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1095/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/preservim__nerdtree-1098/environment/Dockerfile b/tasks/preservim__nerdtree-1098/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b11fd03c76ac820de9cfe3f785987bd3b0c9626b --- /dev/null +++ b/tasks/preservim__nerdtree-1098/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 343508e9fd981928f1e830c71c9d8b2a54edb7dd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 343508e9fd981928f1e830c71c9d8b2a54edb7dd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 343508e9fd981928f1e830c71c9d8b2a54edb7dd \ + && 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/preservim__nerdtree-1098/instruction.md b/tasks/preservim__nerdtree-1098/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..113c4f783c0767801b9717806d622bd20d409d1e --- /dev/null +++ b/tasks/preservim__nerdtree-1098/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Fix vsplit to not open empty buffer + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `343508e9fd98`. 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/preservim__nerdtree-1098/solution/patch.diff b/tasks/preservim__nerdtree-1098/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7f0a62fcbfc4ee64be394eccb9a9b2a8ba8431da --- /dev/null +++ b/tasks/preservim__nerdtree-1098/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e318315..c81612c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index d8dba34..0d9f9ba 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -195,7 +195,7 @@ function! s:Opener._newVSplit() + endif + + call nerdtree#exec('wincmd p', 1) +- call nerdtree#exec('vnew', 1) ++ call nerdtree#exec('vsplit', 1) + + let l:currentWindowNumber = winnr() + diff --git a/tasks/preservim__nerdtree-1098/solution/solve.sh b/tasks/preservim__nerdtree-1098/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1098/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/preservim__nerdtree-1098/task.toml b/tasks/preservim__nerdtree-1098/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..70bb483f8a9fa11fc03fb92e4c83efb11295a720 --- /dev/null +++ b/tasks/preservim__nerdtree-1098/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1098" +description = "Fix vsplit to not open empty buffer" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "343508e9fd981928f1e830c71c9d8b2a54edb7dd" +reference = "https://github.com/preservim/nerdtree/pull/1098" +source_access = "auto" +built_at = "2026-11-16T16:10:02.433262+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9ba13519b77fe7276dc3e92211967256b8a11bfb3af290140276ee2be782c70f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-04-01T05:21:38Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/opener.vim", +] +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:02.576591+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ab8be0364fe52a45e19b6981be1bf39bb3107c179ea4a5735019810ad82d29d4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1098/tests/capture.py b/tasks/preservim__nerdtree-1098/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1098/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/preservim__nerdtree-1098/tests/instruction.md b/tasks/preservim__nerdtree-1098/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..113c4f783c0767801b9717806d622bd20d409d1e --- /dev/null +++ b/tasks/preservim__nerdtree-1098/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Fix vsplit to not open empty buffer + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `343508e9fd98`. 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/preservim__nerdtree-1098/tests/oracle.patch b/tasks/preservim__nerdtree-1098/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7f0a62fcbfc4ee64be394eccb9a9b2a8ba8431da --- /dev/null +++ b/tasks/preservim__nerdtree-1098/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e318315..c81612c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) + - **.0**: Open the parent directory when revealing a non-existent file with :NERDTreeFind (bouk) [#1090](https://github.com/preservim/nerdtree/pull/1090) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index d8dba34..0d9f9ba 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -195,7 +195,7 @@ function! s:Opener._newVSplit() + endif + + call nerdtree#exec('wincmd p', 1) +- call nerdtree#exec('vnew', 1) ++ call nerdtree#exec('vsplit', 1) + + let l:currentWindowNumber = winnr() + diff --git a/tasks/preservim__nerdtree-1098/tests/test.sh b/tasks/preservim__nerdtree-1098/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..be1b8a649ee5a5026ed4b9cdd9ee065466defa9d --- /dev/null +++ b/tasks/preservim__nerdtree-1098/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 343508e9fd981928f1e830c71c9d8b2a54edb7dd > "$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/preservim__nerdtree-1098/tests/verifier.py b/tasks/preservim__nerdtree-1098/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1098/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/preservim__nerdtree-1099/environment/Dockerfile b/tasks/preservim__nerdtree-1099/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..60c71e390dc38db68df8cf7f75c57e6b3a399a6c --- /dev/null +++ b/tasks/preservim__nerdtree-1099/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 832bbaa729da2d0e4ccf0e0e45388e0c1ece9ce7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 832bbaa729da2d0e4ccf0e0e45388e0c1ece9ce7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 832bbaa729da2d0e4ccf0e0e45388e0c1ece9ce7 \ + && 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/preservim__nerdtree-1099/instruction.md b/tasks/preservim__nerdtree-1099/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f2f6e0ac9049b18ff54608e9c5612dacf1c19d5 --- /dev/null +++ b/tasks/preservim__nerdtree-1099/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add missing calls to the shellescape() function + +## Description + +### Description of Changes + +This is a security fix for `nerdtree_plugin/fs_menu.vim` that adds several missing calls to `shellescape()` that are actually required. It also adds missing `shellescape()` calls in two other places. This is necessary to prevent shell command injection. + +It is quite an unlikely exploit, however. + +**N.B.** I suggest that other calls to `system()` throughout the NERDTree code be audited for correct usage of `shellescape()`. Some of them seem to use a custom escaping function that may or may not be correct. These probably should be converted to use the `shellescape()` function. + +See commit messages for more details about some of the ancillary changes. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `832bbaa729da`. 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/preservim__nerdtree-1099/solution/patch.diff b/tasks/preservim__nerdtree-1099/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4efe2c62923556d4082149fc59e034b4f1cf4f3d --- /dev/null +++ b/tasks/preservim__nerdtree-1099/solution/patch.diff @@ -0,0 +1,114 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index c81612c..22d6c5c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 6a23c7b..8334219 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -199,7 +199,7 @@ function! s:Path.copy(dest) + let cmd_prefix = (self.isDirectory ? g:NERDTreeCopyDirCmd : g:NERDTreeCopyFileCmd) + endif + +- let cmd = cmd_prefix . ' ' . escape(self.str(), self._escChars()) . ' ' . escape(a:dest, self._escChars()) ++ let cmd = cmd_prefix . ' ' . shellescape(self.str()) . ' ' . shellescape(a:dest) + let success = system(cmd) + if v:shell_error !=# 0 + throw "NERDTree.CopyError: Could not copy '". self.str() ."' to: '" . a:dest . "'" +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index a1fa2ee..9750976 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -388,44 +388,67 @@ endfunction + + " FUNCTION: NERDTreeQuickLook() {{{1 + function! NERDTreeQuickLook() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("qlmanage -p 2>/dev/null '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('qlmanage -p 2>/dev/null ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeRevealInFinder() {{{1 + function! NERDTreeRevealInFinder() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("open -R '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('open -R ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeExecuteFile() {{{1 + function! NERDTreeExecuteFile() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("open '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('open ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeRevealFileLinux() {{{1 + function! NERDTreeRevealFileLinux() +- let treenode = g:NERDTreeFileNode.GetSelected() +- let parentnode = treenode.parent +- if parentnode !=# {} +- call system("xdg-open '" . parentnode.path.str() . "' &") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ " Handle the edge case of "/", which has no parent. ++ if l:node.path.str() ==# '/' ++ call system('xdg-open /') ++ return ++ endif ++ ++ if empty(l:node.parent) ++ return + endif ++ ++ call system('xdg-open ' . shellescape(l:node.parent.path.str())) + endfunction + + " FUNCTION: NERDTreeExecuteFileLinux() {{{1 + function! NERDTreeExecuteFileLinux() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("xdg-open '" . treenode.path.str() . "' &") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('xdg-open ' . shellescape(l:node.path.str())) + endfunction + + " vim: set sw=4 sts=4 et fdm=marker: +- diff --git a/tasks/preservim__nerdtree-1099/solution/solve.sh b/tasks/preservim__nerdtree-1099/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1099/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/preservim__nerdtree-1099/task.toml b/tasks/preservim__nerdtree-1099/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7293f3195a41e73a83eefa1d82e40c694c4436cc --- /dev/null +++ b/tasks/preservim__nerdtree-1099/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1099" +description = "Add missing calls to the shellescape() function" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "832bbaa729da2d0e4ccf0e0e45388e0c1ece9ce7" +reference = "https://github.com/preservim/nerdtree/pull/1099" +source_access = "auto" +built_at = "2026-11-16T16:10:02.418964+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d9c493862b419c7cae922def8e8df23b00f7ebfc0ebb1573321a91b8ff4a30f8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-04-10T01:37:56Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/path.vim", + "nerdtree_plugin/fs_menu.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 60 +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:02.577154+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3d4cb5deb01c842d44bb8fa36fea895c74c0b99e9f4626a22b7f25c78d7a2c30" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1099/tests/capture.py b/tasks/preservim__nerdtree-1099/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1099/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/preservim__nerdtree-1099/tests/instruction.md b/tasks/preservim__nerdtree-1099/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f2f6e0ac9049b18ff54608e9c5612dacf1c19d5 --- /dev/null +++ b/tasks/preservim__nerdtree-1099/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add missing calls to the shellescape() function + +## Description + +### Description of Changes + +This is a security fix for `nerdtree_plugin/fs_menu.vim` that adds several missing calls to `shellescape()` that are actually required. It also adds missing `shellescape()` calls in two other places. This is necessary to prevent shell command injection. + +It is quite an unlikely exploit, however. + +**N.B.** I suggest that other calls to `system()` throughout the NERDTree code be audited for correct usage of `shellescape()`. Some of them seem to use a custom escaping function that may or may not be correct. These probably should be converted to use the `shellescape()` function. + +See commit messages for more details about some of the ancillary changes. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `832bbaa729da`. 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/preservim__nerdtree-1099/tests/oracle.patch b/tasks/preservim__nerdtree-1099/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4efe2c62923556d4082149fc59e034b4f1cf4f3d --- /dev/null +++ b/tasks/preservim__nerdtree-1099/tests/oracle.patch @@ -0,0 +1,114 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index c81612c..22d6c5c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) + - **.1**: File Move: Escape existing directory name when looking for open files. (PhilRunninger) [#1094](https://github.com/preservim/nerdtree/pull/1094) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 6a23c7b..8334219 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -199,7 +199,7 @@ function! s:Path.copy(dest) + let cmd_prefix = (self.isDirectory ? g:NERDTreeCopyDirCmd : g:NERDTreeCopyFileCmd) + endif + +- let cmd = cmd_prefix . ' ' . escape(self.str(), self._escChars()) . ' ' . escape(a:dest, self._escChars()) ++ let cmd = cmd_prefix . ' ' . shellescape(self.str()) . ' ' . shellescape(a:dest) + let success = system(cmd) + if v:shell_error !=# 0 + throw "NERDTree.CopyError: Could not copy '". self.str() ."' to: '" . a:dest . "'" +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index a1fa2ee..9750976 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -388,44 +388,67 @@ endfunction + + " FUNCTION: NERDTreeQuickLook() {{{1 + function! NERDTreeQuickLook() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("qlmanage -p 2>/dev/null '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('qlmanage -p 2>/dev/null ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeRevealInFinder() {{{1 + function! NERDTreeRevealInFinder() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("open -R '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('open -R ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeExecuteFile() {{{1 + function! NERDTreeExecuteFile() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("open '" . treenode.path.str() . "'") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('open ' . shellescape(l:node.path.str())) + endfunction + + " FUNCTION: NERDTreeRevealFileLinux() {{{1 + function! NERDTreeRevealFileLinux() +- let treenode = g:NERDTreeFileNode.GetSelected() +- let parentnode = treenode.parent +- if parentnode !=# {} +- call system("xdg-open '" . parentnode.path.str() . "' &") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ " Handle the edge case of "/", which has no parent. ++ if l:node.path.str() ==# '/' ++ call system('xdg-open /') ++ return ++ endif ++ ++ if empty(l:node.parent) ++ return + endif ++ ++ call system('xdg-open ' . shellescape(l:node.parent.path.str())) + endfunction + + " FUNCTION: NERDTreeExecuteFileLinux() {{{1 + function! NERDTreeExecuteFileLinux() +- let treenode = g:NERDTreeFileNode.GetSelected() +- if treenode !=# {} +- call system("xdg-open '" . treenode.path.str() . "' &") ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return + endif ++ ++ call system('xdg-open ' . shellescape(l:node.path.str())) + endfunction + + " vim: set sw=4 sts=4 et fdm=marker: +- diff --git a/tasks/preservim__nerdtree-1099/tests/test.sh b/tasks/preservim__nerdtree-1099/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed713ba24205852dca558139fa2f2180db979fed --- /dev/null +++ b/tasks/preservim__nerdtree-1099/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 832bbaa729da2d0e4ccf0e0e45388e0c1ece9ce7 > "$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/preservim__nerdtree-1099/tests/verifier.py b/tasks/preservim__nerdtree-1099/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1099/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/preservim__nerdtree-1101/environment/Dockerfile b/tasks/preservim__nerdtree-1101/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63b57e542a8168597f91afe7179b6ba84180b4ed --- /dev/null +++ b/tasks/preservim__nerdtree-1101/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f767dd34a0bda0a6db8efa43257c90981947f0ab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f767dd34a0bda0a6db8efa43257c90981947f0ab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f767dd34a0bda0a6db8efa43257c90981947f0ab \ + && 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/preservim__nerdtree-1101/instruction.md b/tasks/preservim__nerdtree-1101/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf47f76135c151dea8a87c4ad4b88fca0a7a1e6 --- /dev/null +++ b/tasks/preservim__nerdtree-1101/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Prevent unneeded tree creation in :NERDTreeToggle[VCS] + +## Description + +### Description of Changes + + +`NERDTreeToggleVCS` works by finding the root of the repository and passing it to the `NERDTreeToggle ` function. Pull request #1083 changed the way `NERDTreeToggle` works, such that when a path is specified, the NERDTree's root is always set to that path. The NERDTree is collapsed as it always is when setting a new root. + +This pull request tempers that behavior. If the path given (the repo's root in this case) is the same as the current NERDTree root, then don't recreate the tree. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f767dd34a0bd`. 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/preservim__nerdtree-1101/solution/patch.diff b/tasks/preservim__nerdtree-1101/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e49ffd3bb89d5dc75ce3a1def0e60c39cbb6dc93 --- /dev/null +++ b/tasks/preservim__nerdtree-1101/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 22d6c5c..6417b1a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.5**: Prevent unneeded tree creation in :NERDTreeToggle[VCS] (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index e2b3fa0..abaa8db 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -366,7 +366,7 @@ function! s:Creator.toggleTabTree(dir) + if g:NERDTree.ExistsForTab() + if !g:NERDTree.IsOpen() + call self._createTreeWin() +- if !empty(a:dir) ++ if !empty(a:dir) && a:dir !=# b:NERDTree.root.path.str() + call self.createTabTree(a:dir) + elseif !&hidden + call b:NERDTree.render() diff --git a/tasks/preservim__nerdtree-1101/solution/solve.sh b/tasks/preservim__nerdtree-1101/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1101/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/preservim__nerdtree-1101/task.toml b/tasks/preservim__nerdtree-1101/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..edef76327df2b66c5bc4f8e89862518d2b44431e --- /dev/null +++ b/tasks/preservim__nerdtree-1101/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1101" +description = "Prevent unneeded tree creation in :NERDTreeToggle[VCS] " + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "f767dd34a0bda0a6db8efa43257c90981947f0ab" +reference = "https://github.com/preservim/nerdtree/pull/1101" +source_access = "auto" +built_at = "2026-11-16T16:10:02.431915+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eb47e4a8316ad90e5d0b0b88b19303459a422e8a3f61b4cf5e281fcb11eedd85" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-04-13T21:05:27Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/creator.vim", +] +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:02.577805+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:246144d5872ac40c275980d02379a5d96d8e40c6a2f111291eb8e272b0dd30e0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1101/tests/capture.py b/tasks/preservim__nerdtree-1101/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1101/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/preservim__nerdtree-1101/tests/instruction.md b/tasks/preservim__nerdtree-1101/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf47f76135c151dea8a87c4ad4b88fca0a7a1e6 --- /dev/null +++ b/tasks/preservim__nerdtree-1101/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Prevent unneeded tree creation in :NERDTreeToggle[VCS] + +## Description + +### Description of Changes + + +`NERDTreeToggleVCS` works by finding the root of the repository and passing it to the `NERDTreeToggle ` function. Pull request #1083 changed the way `NERDTreeToggle` works, such that when a path is specified, the NERDTree's root is always set to that path. The NERDTree is collapsed as it always is when setting a new root. + +This pull request tempers that behavior. If the path given (the repo's root in this case) is the same as the current NERDTree root, then don't recreate the tree. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f767dd34a0bd`. 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/preservim__nerdtree-1101/tests/oracle.patch b/tasks/preservim__nerdtree-1101/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e49ffd3bb89d5dc75ce3a1def0e60c39cbb6dc93 --- /dev/null +++ b/tasks/preservim__nerdtree-1101/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 22d6c5c..6417b1a 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.5**: Prevent unneeded tree creation in :NERDTreeToggle[VCS] (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index e2b3fa0..abaa8db 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -366,7 +366,7 @@ function! s:Creator.toggleTabTree(dir) + if g:NERDTree.ExistsForTab() + if !g:NERDTree.IsOpen() + call self._createTreeWin() +- if !empty(a:dir) ++ if !empty(a:dir) && a:dir !=# b:NERDTree.root.path.str() + call self.createTabTree(a:dir) + elseif !&hidden + call b:NERDTree.render() diff --git a/tasks/preservim__nerdtree-1101/tests/test.sh b/tasks/preservim__nerdtree-1101/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd416e177150fbb8c89be3c416549f2277ae6199 --- /dev/null +++ b/tasks/preservim__nerdtree-1101/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 f767dd34a0bda0a6db8efa43257c90981947f0ab > "$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/preservim__nerdtree-1101/tests/verifier.py b/tasks/preservim__nerdtree-1101/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1101/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/preservim__nerdtree-1103/environment/Dockerfile b/tasks/preservim__nerdtree-1103/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f69ca84065a1dc7608dd3336eed9664c235f33c --- /dev/null +++ b/tasks/preservim__nerdtree-1103/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2d7cb043d475ffe7620a8d2d2cd5de7a1f0c6aa7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2d7cb043d475ffe7620a8d2d2cd5de7a1f0c6aa7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2d7cb043d475ffe7620a8d2d2cd5de7a1f0c6aa7 \ + && 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/preservim__nerdtree-1103/instruction.md b/tasks/preservim__nerdtree-1103/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc9f3d892ee76297dee53fbc155ae3e81bda77a6 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** If a file's already open in the window, don't edit it again. + +## Description + +### Description of Changes + + +The issue can be recreated without NERDTree using these commands that simulate what NERDTree does: + +```bash +$ echo "hello" > world.txt +$ vim +``` + +```vim +:set noconfirm +:e world.txt +:copy 0 +:vsplit +:e world.txt +``` + +The solution is to skip the second `:e world.txt` command if the file is already open in the new window. This fixes a regression introduced in #1098. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d7cb043d475`. 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/preservim__nerdtree-1103/solution/patch.diff b/tasks/preservim__nerdtree-1103/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..348cf7692a941742ca25dc39582b742c54c51f82 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6417b1a..2d744b3 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,7 +5,8 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 +-- **.5**: Prevent unneeded tree creation in :NERDTreeToggle[VCS] (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) ++- **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) ++- **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 8334219..3158bbf 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -295,7 +295,10 @@ endfunction + + " FUNCTION: Path.edit() {{{1 + function! s:Path.edit() +- exec 'edit ' . self.str({'format': 'Edit'}) ++ let l:bufname = self.str({'format': 'Edit'}) ++ if bufname() !=# l:bufname ++ exec 'edit ' . l:bufname ++ endif + endfunction + + " FUNCTION: Path.extractDriveLetter(fullpath) {{{1 diff --git a/tasks/preservim__nerdtree-1103/solution/solve.sh b/tasks/preservim__nerdtree-1103/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1103/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/preservim__nerdtree-1103/task.toml b/tasks/preservim__nerdtree-1103/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4466f6a759ed4df8585e7504030ebeefd7ebb247 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1103" +description = "If a file's already open in the window, don't edit it again." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "2d7cb043d475ffe7620a8d2d2cd5de7a1f0c6aa7" +reference = "https://github.com/preservim/nerdtree/pull/1103" +source_access = "auto" +built_at = "2026-11-16T16:10:02.429164+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6e118f3c913511251392c671195bbe6be7ed9936e6cf0ca7266680093d09718b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-04-15T04:55:13Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/path.vim", +] +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:02.578413+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:284d4bf7190cf64e4027bc7a4df42a82ae6a42bf8170a143edc4b47167a769e7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1103/tests/capture.py b/tasks/preservim__nerdtree-1103/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1103/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/preservim__nerdtree-1103/tests/instruction.md b/tasks/preservim__nerdtree-1103/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc9f3d892ee76297dee53fbc155ae3e81bda77a6 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** If a file's already open in the window, don't edit it again. + +## Description + +### Description of Changes + + +The issue can be recreated without NERDTree using these commands that simulate what NERDTree does: + +```bash +$ echo "hello" > world.txt +$ vim +``` + +```vim +:set noconfirm +:e world.txt +:copy 0 +:vsplit +:e world.txt +``` + +The solution is to skip the second `:e world.txt` command if the file is already open in the new window. This fixes a regression introduced in #1098. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2d7cb043d475`. 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/preservim__nerdtree-1103/tests/oracle.patch b/tasks/preservim__nerdtree-1103/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..348cf7692a941742ca25dc39582b742c54c51f82 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6417b1a..2d744b3 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,7 +5,8 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 +-- **.5**: Prevent unneeded tree creation in :NERDTreeToggle[VCS] (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) ++- **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) ++- **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) + - **.3**: Fix vsplit to not open empty buffers when opening previously closed file (AwkwardKore) [#1098](https://github.com/preservim/nerdtree/pull/1098) + - **.2**: Fix infinity loop (on winvim) in FindParentVCSRoot (Eugenij-W) [#1095](https://github.com/preservim/nerdtree/pull/1095) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 8334219..3158bbf 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -295,7 +295,10 @@ endfunction + + " FUNCTION: Path.edit() {{{1 + function! s:Path.edit() +- exec 'edit ' . self.str({'format': 'Edit'}) ++ let l:bufname = self.str({'format': 'Edit'}) ++ if bufname() !=# l:bufname ++ exec 'edit ' . l:bufname ++ endif + endfunction + + " FUNCTION: Path.extractDriveLetter(fullpath) {{{1 diff --git a/tasks/preservim__nerdtree-1103/tests/test.sh b/tasks/preservim__nerdtree-1103/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c76e91911512e81d6b9f972b60ec44a836109b53 --- /dev/null +++ b/tasks/preservim__nerdtree-1103/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 2d7cb043d475ffe7620a8d2d2cd5de7a1f0c6aa7 > "$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/preservim__nerdtree-1103/tests/verifier.py b/tasks/preservim__nerdtree-1103/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1103/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/preservim__nerdtree-1105/environment/Dockerfile b/tasks/preservim__nerdtree-1105/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3eb060a8f57d3009fe30838c1b85cbe63dfd237 --- /dev/null +++ b/tasks/preservim__nerdtree-1105/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0257d64248e43f3ff70e9a1fce3b2aa10ba57bb9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0257d64248e43f3ff70e9a1fce3b2aa10ba57bb9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0257d64248e43f3ff70e9a1fce3b2aa10ba57bb9 \ + && 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/preservim__nerdtree-1105/instruction.md b/tasks/preservim__nerdtree-1105/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ccb3f4fa85b3b47e784bd07bd9d786c12ae3f5a --- /dev/null +++ b/tasks/preservim__nerdtree-1105/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Put '%' argument in bufname() for backwards compatibility. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0257d64248e4`. 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/preservim__nerdtree-1105/solution/patch.diff b/tasks/preservim__nerdtree-1105/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3cf9a6ade4d8bd6edef8787120b90c97cdb3fe7e --- /dev/null +++ b/tasks/preservim__nerdtree-1105/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2d744b3..d0de2be 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.7**: Put '%' argument in bufname() for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) + - **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) + - **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 3158bbf..2ac8c71 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -296,7 +296,7 @@ endfunction + " FUNCTION: Path.edit() {{{1 + function! s:Path.edit() + let l:bufname = self.str({'format': 'Edit'}) +- if bufname() !=# l:bufname ++ if bufname('%') !=# l:bufname + exec 'edit ' . l:bufname + endif + endfunction diff --git a/tasks/preservim__nerdtree-1105/solution/solve.sh b/tasks/preservim__nerdtree-1105/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1105/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/preservim__nerdtree-1105/task.toml b/tasks/preservim__nerdtree-1105/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..27573589b036484d67dac400c234cea12f71c63b --- /dev/null +++ b/tasks/preservim__nerdtree-1105/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1105" +description = "Put '%' argument in bufname() for backwards compatibility." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "0257d64248e43f3ff70e9a1fce3b2aa10ba57bb9" +reference = "https://github.com/preservim/nerdtree/pull/1105" +source_access = "auto" +built_at = "2026-11-16T16:10:02.430539+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b24c68ab2ae45e648882d9dfc1f10b93d2568961bf1e3a8534aeb0489a66cfc0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-04-15T12:58:08Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/path.vim", +] +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:02.578978+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33d89072e16d6fd56997293fd4182467a9acce275f59473e62063200bc5b4499" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1105/tests/capture.py b/tasks/preservim__nerdtree-1105/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1105/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/preservim__nerdtree-1105/tests/instruction.md b/tasks/preservim__nerdtree-1105/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ccb3f4fa85b3b47e784bd07bd9d786c12ae3f5a --- /dev/null +++ b/tasks/preservim__nerdtree-1105/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Put '%' argument in bufname() for backwards compatibility. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0257d64248e4`. 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/preservim__nerdtree-1105/tests/oracle.patch b/tasks/preservim__nerdtree-1105/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3cf9a6ade4d8bd6edef8787120b90c97cdb3fe7e --- /dev/null +++ b/tasks/preservim__nerdtree-1105/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2d744b3..d0de2be 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.7**: Put '%' argument in bufname() for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) + - **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) + - **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 3158bbf..2ac8c71 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -296,7 +296,7 @@ endfunction + " FUNCTION: Path.edit() {{{1 + function! s:Path.edit() + let l:bufname = self.str({'format': 'Edit'}) +- if bufname() !=# l:bufname ++ if bufname('%') !=# l:bufname + exec 'edit ' . l:bufname + endif + endfunction diff --git a/tasks/preservim__nerdtree-1105/tests/test.sh b/tasks/preservim__nerdtree-1105/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3157e3a06daf4ba4cff342c220e5b13e54f255b7 --- /dev/null +++ b/tasks/preservim__nerdtree-1105/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 0257d64248e43f3ff70e9a1fce3b2aa10ba57bb9 > "$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/preservim__nerdtree-1105/tests/verifier.py b/tasks/preservim__nerdtree-1105/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1105/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/preservim__nerdtree-1118/environment/Dockerfile b/tasks/preservim__nerdtree-1118/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a138eaedf1c5be48bcc5d27ca56618de33f20129 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5e77fb2fef6720eabbfe957cf3a47f3f0a218e05 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5e77fb2fef6720eabbfe957cf3a47f3f0a218e05 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5e77fb2fef6720eabbfe957cf3a47f3f0a218e05 \ + && 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/preservim__nerdtree-1118/instruction.md b/tasks/preservim__nerdtree-1118/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..753b9b569e253359628d23d3372b53bd40549de2 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Force NERDTreeFocus to allow events to be fired when switching windows. + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5e77fb2fef67`. 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/preservim__nerdtree-1118/solution/patch.diff b/tasks/preservim__nerdtree-1118/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aa33a2764e5219dccab7ea82dc6dc791d15b5165 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 67f6435..2e1d430 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,8 +5,9 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 +-- **.8**: Fix example code for the NERDTreeAddKeyMap function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) +-- **.7**: Put '%' argument in bufname() for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) ++- **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) ++- **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) ++- **.7**: Put `'%'` argument in `bufname()` for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) + - **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) + - **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index a48f6a8..982db16 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -96,9 +96,9 @@ endfunction + + "FUNCTION: s:NERDTree.CursorToTreeWin(){{{1 + "Places the cursor in the nerd tree window +-function! s:NERDTree.CursorToTreeWin() ++function! s:NERDTree.CursorToTreeWin(...) + call g:NERDTree.MustBeOpen() +- call nerdtree#exec(g:NERDTree.GetWinNum() . 'wincmd w', 1) ++ call nerdtree#exec(g:NERDTree.GetWinNum() . 'wincmd w', a:0 >0 ? a:1 : 1) + endfunction + + " Function: s:NERDTree.ExistsForBuffer() {{{1 +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index 639f87b..ca8070d 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -217,7 +217,7 @@ endfunction + + function! NERDTreeFocus() + if g:NERDTree.IsOpen() +- call g:NERDTree.CursorToTreeWin() ++ call g:NERDTree.CursorToTreeWin(0) + else + call g:NERDTreeCreator.ToggleTabTree('') + endif diff --git a/tasks/preservim__nerdtree-1118/solution/solve.sh b/tasks/preservim__nerdtree-1118/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1118/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/preservim__nerdtree-1118/task.toml b/tasks/preservim__nerdtree-1118/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..50a27a5214277141a05f0397448e3c14652d0fe6 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1118" +description = "Force NERDTreeFocus to allow events to be fired when switching windows." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "5e77fb2fef6720eabbfe957cf3a47f3f0a218e05" +reference = "https://github.com/preservim/nerdtree/pull/1118" +source_access = "auto" +built_at = "2026-11-16T16:10:02.427767+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:509cfdd727f1ab4a2e6927bd5c0bb93cc2b79b53360ddd53c65d92f48912280d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-04T12:14:22Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/nerdtree.vim", + "plugin/NERD_tree.vim", +] +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:02.579505+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c7ca56a20caa62a1aa70efd0435e25e542c20b0cf296cf4ef866cff5543b15e6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1118/tests/capture.py b/tasks/preservim__nerdtree-1118/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1118/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/preservim__nerdtree-1118/tests/instruction.md b/tasks/preservim__nerdtree-1118/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..753b9b569e253359628d23d3372b53bd40549de2 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Force NERDTreeFocus to allow events to be fired when switching windows. + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5e77fb2fef67`. 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/preservim__nerdtree-1118/tests/oracle.patch b/tasks/preservim__nerdtree-1118/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..aa33a2764e5219dccab7ea82dc6dc791d15b5165 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 67f6435..2e1d430 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,8 +5,9 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 +-- **.8**: Fix example code for the NERDTreeAddKeyMap function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) +-- **.7**: Put '%' argument in bufname() for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) ++- **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) ++- **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) ++- **.7**: Put `'%'` argument in `bufname()` for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) + - **.6**: If a file's already open in the window, don't edit it again. (PhilRunninger) [#1103](https://github.com/preservim/nerdtree/pull/1103) + - **.5**: Prevent unneeded tree creation in `:NERDTreeToggle[VCS] ` (PhilRunninger) [#1101](https://github.com/preservim/nerdtree/pull/1101) + - **.4**: Add missing calls to the `shellescape()` function (lifecrisis) [#1099](https://github.com/preservim/nerdtree/pull/1099) +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index a48f6a8..982db16 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -96,9 +96,9 @@ endfunction + + "FUNCTION: s:NERDTree.CursorToTreeWin(){{{1 + "Places the cursor in the nerd tree window +-function! s:NERDTree.CursorToTreeWin() ++function! s:NERDTree.CursorToTreeWin(...) + call g:NERDTree.MustBeOpen() +- call nerdtree#exec(g:NERDTree.GetWinNum() . 'wincmd w', 1) ++ call nerdtree#exec(g:NERDTree.GetWinNum() . 'wincmd w', a:0 >0 ? a:1 : 1) + endfunction + + " Function: s:NERDTree.ExistsForBuffer() {{{1 +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index 639f87b..ca8070d 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -217,7 +217,7 @@ endfunction + + function! NERDTreeFocus() + if g:NERDTree.IsOpen() +- call g:NERDTree.CursorToTreeWin() ++ call g:NERDTree.CursorToTreeWin(0) + else + call g:NERDTreeCreator.ToggleTabTree('') + endif diff --git a/tasks/preservim__nerdtree-1118/tests/test.sh b/tasks/preservim__nerdtree-1118/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff5926523a5e41b87bbdfe8fa589ed3facc6f872 --- /dev/null +++ b/tasks/preservim__nerdtree-1118/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 5e77fb2fef6720eabbfe957cf3a47f3f0a218e05 > "$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/preservim__nerdtree-1118/tests/verifier.py b/tasks/preservim__nerdtree-1118/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1118/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/preservim__nerdtree-1120/environment/Dockerfile b/tasks/preservim__nerdtree-1120/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..335c695bc8c731b35f65724a219eb70fb281ddbc --- /dev/null +++ b/tasks/preservim__nerdtree-1120/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 30ad6da98482d8aee36d90c49711a8476b5e240a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 30ad6da98482d8aee36d90c49711a8476b5e240a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 30ad6da98482d8aee36d90c49711a8476b5e240a \ + && 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/preservim__nerdtree-1120/instruction.md b/tasks/preservim__nerdtree-1120/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9521038ae5e14aeff9efc1acbca29292d1cb9d53 --- /dev/null +++ b/tasks/preservim__nerdtree-1120/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Do not consider the tree root to be "cascadable" + +## Description + +### Description of Changes + +Do not consider the tree root to be "cascadable" + +This PR fixes an un-handled error condition. To reproduce: + +1. `mkdir -p foo/bar/` +2. `cd foo/` +3. `vim` +4. `:NERDTree` +5. Position cursor on `bar/` in the NERDTree and hit `x`. + +The result is a nasty error message because the handler for this command continues searching upward because it thinks the root `isCascadable()`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `30ad6da98482`. 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/preservim__nerdtree-1120/solution/patch.diff b/tasks/preservim__nerdtree-1120/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2aec1fa007a086780ebf81be1c43195a5d026b48 --- /dev/null +++ b/tasks/preservim__nerdtree-1120/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2e1d430..0bcf4d7 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) + - **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) + - **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) + - **.7**: Put `'%'` argument in `bufname()` for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index 88ac319..14d2996 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -377,11 +377,17 @@ endfunction + " 1. If cascaded, we don't know which dir is bookmarked or is a symlink. + " 2. If the parent is a symlink or is bookmarked, you end up with unparsable + " text, and NERDTree cannot get the path of any child node. ++" Also, return false if this directory is the tree root, which should never be ++" part of a cascade. + function! s:TreeDirNode.isCascadable() + if g:NERDTreeCascadeSingleChildDir ==# 0 + return 0 + endif + ++ if self.isRoot() ++ return 0 ++ endif ++ + if self.path.isSymLink + return 0 + endif diff --git a/tasks/preservim__nerdtree-1120/solution/solve.sh b/tasks/preservim__nerdtree-1120/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1120/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/preservim__nerdtree-1120/task.toml b/tasks/preservim__nerdtree-1120/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e6aa37faf456e0ab7d6eafd45e1c6e2c3fb26ca8 --- /dev/null +++ b/tasks/preservim__nerdtree-1120/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1120" +description = "Do not consider the tree root to be \"cascadable\"" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "30ad6da98482d8aee36d90c49711a8476b5e240a" +reference = "https://github.com/preservim/nerdtree/pull/1120" +source_access = "auto" +built_at = "2026-11-16T16:10:02.420510+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8cc34523738de544468497a4306ec376f82b65bd6313d92316c1d8870ea5bce5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-07T03:24:02Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/tree_dir_node.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +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:02.580149+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e0ac1f07fbd4fec250f72b8f37089c18ae197f583e30ef7d66f90440e5d25be4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1120/tests/capture.py b/tasks/preservim__nerdtree-1120/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1120/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/preservim__nerdtree-1120/tests/instruction.md b/tasks/preservim__nerdtree-1120/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9521038ae5e14aeff9efc1acbca29292d1cb9d53 --- /dev/null +++ b/tasks/preservim__nerdtree-1120/tests/instruction.md @@ -0,0 +1,36 @@ +# Issue + +**Title:** Do not consider the tree root to be "cascadable" + +## Description + +### Description of Changes + +Do not consider the tree root to be "cascadable" + +This PR fixes an un-handled error condition. To reproduce: + +1. `mkdir -p foo/bar/` +2. `cd foo/` +3. `vim` +4. `:NERDTree` +5. Position cursor on `bar/` in the NERDTree and hit `x`. + +The result is a nasty error message because the handler for this command continues searching upward because it thinks the root `isCascadable()`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `30ad6da98482`. 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/preservim__nerdtree-1120/tests/oracle.patch b/tasks/preservim__nerdtree-1120/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2aec1fa007a086780ebf81be1c43195a5d026b48 --- /dev/null +++ b/tasks/preservim__nerdtree-1120/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 2e1d430..0bcf4d7 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) + - **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) + - **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) + - **.7**: Put `'%'` argument in `bufname()` for backwards compatibility. (PhilRunninger) [#1105](https://github.com/preservim/nerdtree/pull/1105) +diff --git a/lib/nerdtree/tree_dir_node.vim b/lib/nerdtree/tree_dir_node.vim +index 88ac319..14d2996 100644 +--- a/lib/nerdtree/tree_dir_node.vim ++++ b/lib/nerdtree/tree_dir_node.vim +@@ -377,11 +377,17 @@ endfunction + " 1. If cascaded, we don't know which dir is bookmarked or is a symlink. + " 2. If the parent is a symlink or is bookmarked, you end up with unparsable + " text, and NERDTree cannot get the path of any child node. ++" Also, return false if this directory is the tree root, which should never be ++" part of a cascade. + function! s:TreeDirNode.isCascadable() + if g:NERDTreeCascadeSingleChildDir ==# 0 + return 0 + endif + ++ if self.isRoot() ++ return 0 ++ endif ++ + if self.path.isSymLink + return 0 + endif diff --git a/tasks/preservim__nerdtree-1120/tests/test.sh b/tasks/preservim__nerdtree-1120/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d42f472858066705c4538926b728b6a32d01801b --- /dev/null +++ b/tasks/preservim__nerdtree-1120/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 30ad6da98482d8aee36d90c49711a8476b5e240a > "$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/preservim__nerdtree-1120/tests/verifier.py b/tasks/preservim__nerdtree-1120/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1120/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/preservim__nerdtree-1122/environment/Dockerfile b/tasks/preservim__nerdtree-1122/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0a01cd40ad4d0397244d693a43748e178134e264 --- /dev/null +++ b/tasks/preservim__nerdtree-1122/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4cc6097ecb18b52c023a9487c2cf3220290ba0a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4cc6097ecb18b52c023a9487c2cf3220290ba0a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4cc6097ecb18b52c023a9487c2cf3220290ba0a1 \ + && 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/preservim__nerdtree-1122/instruction.md b/tasks/preservim__nerdtree-1122/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c9325aa2c8695306c7586ff46ea38a0701d3abe --- /dev/null +++ b/tasks/preservim__nerdtree-1122/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** * fix duplicated slash in s:Path.isUnder() (on windows OS) + +## Description + +Fix exception in NERDTreeFind. +On windows OS and **if the file is located in the root directory of the disk**, TreeDirNode.reveal() trow exception because Path.isUnder() duplicate slash **on root drive paths** (look like "c://"). + +### Description of Changes +~~using substitute() to add a slash.~~ +Rewrite NERDTreePath.isUnder() and NERDTreePath.isAncestor() for direct comparison of paths without transformations. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4cc6097ecb18`. 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/preservim__nerdtree-1122/solution/patch.diff b/tasks/preservim__nerdtree-1122/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4bbabf7d37f7c67322582b59ff6e641bf2de80cb --- /dev/null +++ b/tasks/preservim__nerdtree-1122/solution/patch.diff @@ -0,0 +1,84 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0bcf4d7..c68c8de 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) [#1122](https://github.com/preservim/nerdtree/pull/1122) + - **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) + - **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) + - **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index abaa8db..f845361 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -249,7 +249,11 @@ function! s:Creator._pathForString(str) + if dir =~# '^\.' + let dir = getcwd() . g:NERDTreePath.Slash() . dir + endif +- let dir = g:NERDTreePath.Resolve(dir) ++ ++ "hack to prevent removing slash if dir is the root of the file system. ++ if dir !=# '/' ++ let dir = g:NERDTreePath.Resolve(dir) ++ endif + + try + let path = g:NERDTreePath.New(dir) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 2ac8c71..61cdfa8 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -546,26 +546,36 @@ endfunction + " return 1 if this path is somewhere above the given path in the filesystem. + " + " a:path should be a dir +-function! s:Path.isAncestor(path) +- if !self.isDirectory +- return 0 +- endif +- +- let this = self.str() +- let that = a:path.str() +- return stridx(that, this) ==# 0 ++function! s:Path.isAncestor(child) ++ return a:child.isUnder(self) + endfunction + + " FUNCTION: Path.isUnder(path) {{{1 + " return 1 if this path is somewhere under the given path in the filesystem. +-function! s:Path.isUnder(path) +- if a:path.isDirectory ==# 0 ++function! s:Path.isUnder(parent) ++ if a:parent.isDirectory ==# 0 + return 0 + endif +- +- let this = self.str() +- let that = a:path.str() +- return stridx(this, that . s:Path.Slash()) ==# 0 ++ if nerdtree#runningWindows() && a:parent.drive !=# self.drive ++ return 0 ++ endif ++ let l:this_count = len(self.pathSegments) ++ if l:this_count ==# 0 ++ return 0 ++ endif ++ let l:that_count = len(a:parent.pathSegments) ++ if l:that_count ==# 0 ++ return 1 ++ endif ++ if l:that_count >= l:this_count ++ return 0 ++ endif ++ for i in range(0, l:that_count-1) ++ if self.pathSegments[i] !=# a:parent.pathSegments[i] ++ return 0 ++ endif ++ endfor ++ return 1 + endfunction + + " FUNCTION: Path.JoinPathStrings(...) {{{1 diff --git a/tasks/preservim__nerdtree-1122/solution/solve.sh b/tasks/preservim__nerdtree-1122/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1122/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/preservim__nerdtree-1122/task.toml b/tasks/preservim__nerdtree-1122/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fead92196cc0e1fe63b4eb8bf5dd8c04dd597635 --- /dev/null +++ b/tasks/preservim__nerdtree-1122/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1122" +description = "* fix duplicated slash in s:Path.isUnder() (on windows OS)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "4cc6097ecb18b52c023a9487c2cf3220290ba0a1" +reference = "https://github.com/preservim/nerdtree/pull/1122" +source_access = "auto" +built_at = "2026-11-16T16:10:02.426248+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:080b6aca80acc47be957618201383026d5a7ebf958bf45b0359d9406712f4fea" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-14T18:24:36Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/creator.vim", + "lib/nerdtree/path.vim", +] +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:02.580745+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:09920ee6dcc52e23acf67af221f479df9dd575a94d6475cf41aaaa24dd049e45" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1122/tests/capture.py b/tasks/preservim__nerdtree-1122/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1122/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/preservim__nerdtree-1122/tests/instruction.md b/tasks/preservim__nerdtree-1122/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c9325aa2c8695306c7586ff46ea38a0701d3abe --- /dev/null +++ b/tasks/preservim__nerdtree-1122/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** * fix duplicated slash in s:Path.isUnder() (on windows OS) + +## Description + +Fix exception in NERDTreeFind. +On windows OS and **if the file is located in the root directory of the disk**, TreeDirNode.reveal() trow exception because Path.isUnder() duplicate slash **on root drive paths** (look like "c://"). + +### Description of Changes +~~using substitute() to add a slash.~~ +Rewrite NERDTreePath.isUnder() and NERDTreePath.isAncestor() for direct comparison of paths without transformations. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4cc6097ecb18`. 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/preservim__nerdtree-1122/tests/oracle.patch b/tasks/preservim__nerdtree-1122/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4bbabf7d37f7c67322582b59ff6e641bf2de80cb --- /dev/null +++ b/tasks/preservim__nerdtree-1122/tests/oracle.patch @@ -0,0 +1,84 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0bcf4d7..c68c8de 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) [#1122](https://github.com/preservim/nerdtree/pull/1122) + - **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) + - **.9**: Force `:NERDTreeFocus` to allow events to be fired when switching windows. (PhilRunninger) [#1118](https://github.com/preservim/nerdtree/pull/1118) + - **.8**: Fix example code for the `NERDTreeAddKeyMap()` function. (PhilRunninger) [#1116](https://github.com/preservim/nerdtree/pull/1116) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index abaa8db..f845361 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -249,7 +249,11 @@ function! s:Creator._pathForString(str) + if dir =~# '^\.' + let dir = getcwd() . g:NERDTreePath.Slash() . dir + endif +- let dir = g:NERDTreePath.Resolve(dir) ++ ++ "hack to prevent removing slash if dir is the root of the file system. ++ if dir !=# '/' ++ let dir = g:NERDTreePath.Resolve(dir) ++ endif + + try + let path = g:NERDTreePath.New(dir) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 2ac8c71..61cdfa8 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -546,26 +546,36 @@ endfunction + " return 1 if this path is somewhere above the given path in the filesystem. + " + " a:path should be a dir +-function! s:Path.isAncestor(path) +- if !self.isDirectory +- return 0 +- endif +- +- let this = self.str() +- let that = a:path.str() +- return stridx(that, this) ==# 0 ++function! s:Path.isAncestor(child) ++ return a:child.isUnder(self) + endfunction + + " FUNCTION: Path.isUnder(path) {{{1 + " return 1 if this path is somewhere under the given path in the filesystem. +-function! s:Path.isUnder(path) +- if a:path.isDirectory ==# 0 ++function! s:Path.isUnder(parent) ++ if a:parent.isDirectory ==# 0 + return 0 + endif +- +- let this = self.str() +- let that = a:path.str() +- return stridx(this, that . s:Path.Slash()) ==# 0 ++ if nerdtree#runningWindows() && a:parent.drive !=# self.drive ++ return 0 ++ endif ++ let l:this_count = len(self.pathSegments) ++ if l:this_count ==# 0 ++ return 0 ++ endif ++ let l:that_count = len(a:parent.pathSegments) ++ if l:that_count ==# 0 ++ return 1 ++ endif ++ if l:that_count >= l:this_count ++ return 0 ++ endif ++ for i in range(0, l:that_count-1) ++ if self.pathSegments[i] !=# a:parent.pathSegments[i] ++ return 0 ++ endif ++ endfor ++ return 1 + endfunction + + " FUNCTION: Path.JoinPathStrings(...) {{{1 diff --git a/tasks/preservim__nerdtree-1122/tests/test.sh b/tasks/preservim__nerdtree-1122/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3171947b563e3e22a44727cfff15d33f4bf92267 --- /dev/null +++ b/tasks/preservim__nerdtree-1122/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 4cc6097ecb18b52c023a9487c2cf3220290ba0a1 > "$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/preservim__nerdtree-1122/tests/verifier.py b/tasks/preservim__nerdtree-1122/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1122/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/preservim__nerdtree-1128/environment/Dockerfile b/tasks/preservim__nerdtree-1128/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c0a5b65bf1d0a5cd6464f2dbcee430c9ebdfe037 --- /dev/null +++ b/tasks/preservim__nerdtree-1128/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f63132cade94e0937e51d55e4f9ddd33bec69e4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f63132cade94e0937e51d55e4f9ddd33bec69e4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f63132cade94e0937e51d55e4f9ddd33bec69e4e \ + && 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/preservim__nerdtree-1128/instruction.md b/tasks/preservim__nerdtree-1128/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0793e55fd531cca2508abf5734e1f0f1f171fbcb --- /dev/null +++ b/tasks/preservim__nerdtree-1128/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Add curly braces to the list of characters to be escaped. + +## Description + +### Description of Changes + + +The combination of the `globpath()` function and the **fish** shell requires some additional care when it comes to filename characters that need to be escaped. In particular, when a path containing curly braces is used in the `globpath()` function, it fails in the fish shell, but works fine in bash. If those braces are escaped, then it works in both shells. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f63132cade94`. 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/preservim__nerdtree-1128/solution/patch.diff b/tasks/preservim__nerdtree-1128/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..75e2d36cb1a8743aa8878d0dd54e04491cf9787c --- /dev/null +++ b/tasks/preservim__nerdtree-1128/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 7f95ecf..66d250c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.15**: Add curly braces to the list of characters to be escaped. (PhilRunninger) [#1128](https://github.com/preservim/nerdtree/pull/1128) + - **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) + - **.13**: `cmd.exe /c start "" ` for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. (Eugenij-W) [#1126](https://github.com/preservim/nerdtree/pull/1126) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 61cdfa8..d30dd51 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -332,7 +332,7 @@ function! s:Path._escChars() + return " `\|\"#%&,?()\*^<>$" + endif + +- return " \\`\|\"#%&,?()\*^<>[]$" ++ return " \\`\|\"#%&,?()\*^<>[]{}$" + endfunction + + " FUNCTION: Path.getDir() {{{1 diff --git a/tasks/preservim__nerdtree-1128/solution/solve.sh b/tasks/preservim__nerdtree-1128/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1128/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/preservim__nerdtree-1128/task.toml b/tasks/preservim__nerdtree-1128/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..084fce95f34daf73c576c97b40034a424589e96e --- /dev/null +++ b/tasks/preservim__nerdtree-1128/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1128" +description = "Add curly braces to the list of characters to be escaped." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "f63132cade94e0937e51d55e4f9ddd33bec69e4e" +reference = "https://github.com/preservim/nerdtree/pull/1128" +source_access = "auto" +built_at = "2026-11-16T16:10:02.423419+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e2c9c0e96ecbf093373e925ec9b9723d54ebd9f52c30d0f54d545c9fdd3d7f19" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-26T04:15:18Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/path.vim", +] +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:02.581263+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c4eba1dee8f8d3f12b6eb48804593c09acf1a6848c63af84175fb7ec91d07ca2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1128/tests/capture.py b/tasks/preservim__nerdtree-1128/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1128/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/preservim__nerdtree-1128/tests/instruction.md b/tasks/preservim__nerdtree-1128/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0793e55fd531cca2508abf5734e1f0f1f171fbcb --- /dev/null +++ b/tasks/preservim__nerdtree-1128/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Add curly braces to the list of characters to be escaped. + +## Description + +### Description of Changes + + +The combination of the `globpath()` function and the **fish** shell requires some additional care when it comes to filename characters that need to be escaped. In particular, when a path containing curly braces is used in the `globpath()` function, it fails in the fish shell, but works fine in bash. If those braces are escaped, then it works in both shells. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f63132cade94`. 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/preservim__nerdtree-1128/tests/oracle.patch b/tasks/preservim__nerdtree-1128/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..75e2d36cb1a8743aa8878d0dd54e04491cf9787c --- /dev/null +++ b/tasks/preservim__nerdtree-1128/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 7f95ecf..66d250c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.15**: Add curly braces to the list of characters to be escaped. (PhilRunninger) [#1128](https://github.com/preservim/nerdtree/pull/1128) + - **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) + - **.13**: `cmd.exe /c start "" ` for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. (Eugenij-W) [#1126](https://github.com/preservim/nerdtree/pull/1126) +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 61cdfa8..d30dd51 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -332,7 +332,7 @@ function! s:Path._escChars() + return " `\|\"#%&,?()\*^<>$" + endif + +- return " \\`\|\"#%&,?()\*^<>[]$" ++ return " \\`\|\"#%&,?()\*^<>[]{}$" + endfunction + + " FUNCTION: Path.getDir() {{{1 diff --git a/tasks/preservim__nerdtree-1128/tests/test.sh b/tasks/preservim__nerdtree-1128/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..acbddc3734d14951b01fdbcdb7b396e08ffb0372 --- /dev/null +++ b/tasks/preservim__nerdtree-1128/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 f63132cade94e0937e51d55e4f9ddd33bec69e4e > "$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/preservim__nerdtree-1128/tests/verifier.py b/tasks/preservim__nerdtree-1128/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1128/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/preservim__nerdtree-1130/environment/Dockerfile b/tasks/preservim__nerdtree-1130/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a39bc623c087e64f1f01ed9de6eb76a233dc501e --- /dev/null +++ b/tasks/preservim__nerdtree-1130/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 10eaa3a2f42d395a9a6dca14957a5862e709651b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 10eaa3a2f42d395a9a6dca14957a5862e709651b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 10eaa3a2f42d395a9a6dca14957a5862e709651b \ + && 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/preservim__nerdtree-1130/instruction.md b/tasks/preservim__nerdtree-1130/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8e50459e60236449638c361c8c33100d5ab5401b --- /dev/null +++ b/tasks/preservim__nerdtree-1130/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** cmd.exe /c start "" for windows default viewer support + +## Description + +### Description of Changes + + +--- +### New Version Info +Not sure what to do here 😓 +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `10eaa3a2f42d`. 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/preservim__nerdtree-1130/solution/patch.diff b/tasks/preservim__nerdtree-1130/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c8d7bb1e67739a07d18add28b955ef72164dee0d --- /dev/null +++ b/tasks/preservim__nerdtree-1130/solution/patch.diff @@ -0,0 +1,43 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 95c290f..30f4758 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.13**: Invoke-Item for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. [#1126](https://github.com/preservim/nerdtree/pull/1126) + - **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) [#1122](https://github.com/preservim/nerdtree/pull/1122) + - **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 9750976..3073414 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -34,6 +34,10 @@ if executable('xdg-open') + call NERDTreeAddMenuItem({'text': '(o)pen the current node with system editor', 'shortcut': 'o', 'callback': 'NERDTreeExecuteFileLinux'}) + endif + ++if nerdtree#runningWindows() ++ call NERDTreeAddMenuItem({'text': '(o)pen the current node with system editor', 'shortcut': 'o', 'callback': 'NERDTreeExecuteFileWindows'}) ++endif ++ + if g:NERDTreePath.CopyingSupported() + call NERDTreeAddMenuItem({'text': '(c)opy the current node', 'shortcut': 'c', 'callback': 'NERDTreeCopyNode'}) + endif +@@ -451,4 +455,15 @@ function! NERDTreeExecuteFileLinux() + call system('xdg-open ' . shellescape(l:node.path.str())) + endfunction + ++" FUNCTION: NERDTreeExecuteFileWindows() {{{1 ++function! NERDTreeExecuteFileWindows() ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ call system('cmd.exe /c start "" ' . shellescape(l:node.path.str())) ++endfunction ++ + " vim: set sw=4 sts=4 et fdm=marker: diff --git a/tasks/preservim__nerdtree-1130/solution/solve.sh b/tasks/preservim__nerdtree-1130/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1130/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/preservim__nerdtree-1130/task.toml b/tasks/preservim__nerdtree-1130/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a36b6bfab56a9d9edc11108e34662bec15cafc15 --- /dev/null +++ b/tasks/preservim__nerdtree-1130/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1130" +description = "cmd.exe /c start \"\" for windows default viewer support" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "10eaa3a2f42d395a9a6dca14957a5862e709651b" +reference = "https://github.com/preservim/nerdtree/pull/1130" +source_access = "auto" +built_at = "2026-11-16T16:10:02.424823+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:335afd93cfeaf71ec16e48725af4b2c572c93f458f528c50c20cfe9b70fcf4ab" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-22T12:57:20Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "nerdtree_plugin/fs_menu.vim", +] +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:02.581783+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:43e97467b829921ba050c0d73afea97c41e827da23edd766db3c09d0f15eb646" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1130/tests/capture.py b/tasks/preservim__nerdtree-1130/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1130/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/preservim__nerdtree-1130/tests/instruction.md b/tasks/preservim__nerdtree-1130/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8e50459e60236449638c361c8c33100d5ab5401b --- /dev/null +++ b/tasks/preservim__nerdtree-1130/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** cmd.exe /c start "" for windows default viewer support + +## Description + +### Description of Changes + + +--- +### New Version Info +Not sure what to do here 😓 +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `10eaa3a2f42d`. 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/preservim__nerdtree-1130/tests/oracle.patch b/tasks/preservim__nerdtree-1130/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c8d7bb1e67739a07d18add28b955ef72164dee0d --- /dev/null +++ b/tasks/preservim__nerdtree-1130/tests/oracle.patch @@ -0,0 +1,43 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 95c290f..30f4758 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.13**: Invoke-Item for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. [#1126](https://github.com/preservim/nerdtree/pull/1126) + - **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) [#1122](https://github.com/preservim/nerdtree/pull/1122) + - **.10**: Do not consider the tree root to be "cascadable". (lifecrisis) [#1120](https://github.com/preservim/nerdtree/pull/1120) +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index 9750976..3073414 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -34,6 +34,10 @@ if executable('xdg-open') + call NERDTreeAddMenuItem({'text': '(o)pen the current node with system editor', 'shortcut': 'o', 'callback': 'NERDTreeExecuteFileLinux'}) + endif + ++if nerdtree#runningWindows() ++ call NERDTreeAddMenuItem({'text': '(o)pen the current node with system editor', 'shortcut': 'o', 'callback': 'NERDTreeExecuteFileWindows'}) ++endif ++ + if g:NERDTreePath.CopyingSupported() + call NERDTreeAddMenuItem({'text': '(c)opy the current node', 'shortcut': 'c', 'callback': 'NERDTreeCopyNode'}) + endif +@@ -451,4 +455,15 @@ function! NERDTreeExecuteFileLinux() + call system('xdg-open ' . shellescape(l:node.path.str())) + endfunction + ++" FUNCTION: NERDTreeExecuteFileWindows() {{{1 ++function! NERDTreeExecuteFileWindows() ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ call system('cmd.exe /c start "" ' . shellescape(l:node.path.str())) ++endfunction ++ + " vim: set sw=4 sts=4 et fdm=marker: diff --git a/tasks/preservim__nerdtree-1130/tests/test.sh b/tasks/preservim__nerdtree-1130/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..471eeae7e89b4976a98f77d8d7a835fb5b8bd5cf --- /dev/null +++ b/tasks/preservim__nerdtree-1130/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 10eaa3a2f42d395a9a6dca14957a5862e709651b > "$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/preservim__nerdtree-1130/tests/verifier.py b/tasks/preservim__nerdtree-1130/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1130/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/preservim__nerdtree-1134/environment/Dockerfile b/tasks/preservim__nerdtree-1134/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9a2246893e7236c28e4a07d327c5b7f30596f8e8 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 484dc84b47efe7163803451771e189347fe99eed 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 484dc84b47efe7163803451771e189347fe99eed \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 484dc84b47efe7163803451771e189347fe99eed \ + && 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/preservim__nerdtree-1134/instruction.md b/tasks/preservim__nerdtree-1134/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ecfa016ebfe1a5dac3e89e0db2a28679575ee329 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Use backward-compatible nerdtree#and() in one place that was missed. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `484dc84b47ef`. 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/preservim__nerdtree-1134/solution/patch.diff b/tasks/preservim__nerdtree-1134/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f717d3cbcf6ebee77296c0e13ae656a06ab82df0 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6fd2c5b..7f95ecf 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) + - **.13**: `cmd.exe /c start "" ` for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. (Eugenij-W) [#1126](https://github.com/preservim/nerdtree/pull/1126) + - **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) (Eugenij-W) [#1122](https://github.com/preservim/nerdtree/pull/1122) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 156b260..d0785a4 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -45,7 +45,7 @@ function! nerdtree#slash() abort + endfunction + + "FUNCTION: nerdtree#and(x,y) {{{2 +-" Implements and() function for Vim <= 7.2 ++" Implements and() function for Vim <= 7.4 + function! nerdtree#and(x,y) abort + if exists('*and') + return and(a:x, a:y) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 0d9f9ba..6cdd9df 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -219,7 +219,7 @@ endfunction + + " FUNCTION: Opener._openFile() {{{1 + function! s:Opener._openFile() +- if !self._stay && !and(g:NERDTreeQuitOnOpen,1) && exists('b:NERDTreeZoomed') && b:NERDTreeZoomed ++ if !self._stay && !nerdtree#and(g:NERDTreeQuitOnOpen,1) && exists('b:NERDTreeZoomed') && b:NERDTreeZoomed + call b:NERDTree.ui.toggleZoom() + endif + diff --git a/tasks/preservim__nerdtree-1134/solution/solve.sh b/tasks/preservim__nerdtree-1134/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1134/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/preservim__nerdtree-1134/task.toml b/tasks/preservim__nerdtree-1134/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..22f492fc1bc2ec85cfb804ce2aee7db787427b52 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1134" +description = "Use backward-compatible nerdtree#and() in one place that was missed." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "484dc84b47efe7163803451771e189347fe99eed" +reference = "https://github.com/preservim/nerdtree/pull/1134" +source_access = "auto" +built_at = "2026-11-16T16:10:02.421937+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a971c1499396f8e7f6962260fe2e96acf8026a97dcedbc26582c83d071518e90" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-05-25T15:33:20Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree.vim", + "lib/nerdtree/opener.vim", +] +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:02.582320+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:257adc038778afdb86eadda135dd6a16ec3561f94ce7e55b15cbd500338d974b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1134/tests/capture.py b/tasks/preservim__nerdtree-1134/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1134/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/preservim__nerdtree-1134/tests/instruction.md b/tasks/preservim__nerdtree-1134/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ecfa016ebfe1a5dac3e89e0db2a28679575ee329 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Use backward-compatible nerdtree#and() in one place that was missed. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `484dc84b47ef`. 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/preservim__nerdtree-1134/tests/oracle.patch b/tasks/preservim__nerdtree-1134/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f717d3cbcf6ebee77296c0e13ae656a06ab82df0 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 6fd2c5b..7f95ecf 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.7 ++- **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) + - **.13**: `cmd.exe /c start "" ` for windows default viewer support. (J. Altayó) [#1130](https://github.com/preservim/nerdtree/pull/1130) + - **.12**: Fixed a bug that caused the file-tree construction to slow down significantly. (Eugenij-W) [#1126](https://github.com/preservim/nerdtree/pull/1126) + - **.11**: Fix exception in NERDTreeFind (on windows OS and If the file is located in the root directory of the disk) (Eugenij-W) [#1122](https://github.com/preservim/nerdtree/pull/1122) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index 156b260..d0785a4 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -45,7 +45,7 @@ function! nerdtree#slash() abort + endfunction + + "FUNCTION: nerdtree#and(x,y) {{{2 +-" Implements and() function for Vim <= 7.2 ++" Implements and() function for Vim <= 7.4 + function! nerdtree#and(x,y) abort + if exists('*and') + return and(a:x, a:y) +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 0d9f9ba..6cdd9df 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -219,7 +219,7 @@ endfunction + + " FUNCTION: Opener._openFile() {{{1 + function! s:Opener._openFile() +- if !self._stay && !and(g:NERDTreeQuitOnOpen,1) && exists('b:NERDTreeZoomed') && b:NERDTreeZoomed ++ if !self._stay && !nerdtree#and(g:NERDTreeQuitOnOpen,1) && exists('b:NERDTreeZoomed') && b:NERDTreeZoomed + call b:NERDTree.ui.toggleZoom() + endif + diff --git a/tasks/preservim__nerdtree-1134/tests/test.sh b/tasks/preservim__nerdtree-1134/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..889687aae668577593cd903e6828a38135b9b319 --- /dev/null +++ b/tasks/preservim__nerdtree-1134/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 484dc84b47efe7163803451771e189347fe99eed > "$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/preservim__nerdtree-1134/tests/verifier.py b/tasks/preservim__nerdtree-1134/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1134/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/preservim__nerdtree-1138/environment/Dockerfile b/tasks/preservim__nerdtree-1138/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..838da9455c75715652714de374927a83b532e742 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 052b1f00a0ef14b0019f4d0cda9906ba93f9a0d6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 052b1f00a0ef14b0019f4d0cda9906ba93f9a0d6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 052b1f00a0ef14b0019f4d0cda9906ba93f9a0d6 \ + && 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/preservim__nerdtree-1138/instruction.md b/tasks/preservim__nerdtree-1138/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0e22573f2b4c98bf4b0325d1bcae9c2f1186352 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Allow concealed characters to show another character. + +## Description + +### Description of Changes + + +conceallevel=3 always hides the character, but conceallevel=2 allows an alternate character to be displayed instead. This change, and a similar one in [nerdtree-buffer-ops](https://github.com/PhilRunninger/nerdtree-buffer-ops) will allow every other leading space in NERDTree to be displayed as a vertical bar, as described in my comment on #1136 . + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `052b1f00a0ef`. 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/preservim__nerdtree-1138/solution/patch.diff b/tasks/preservim__nerdtree-1138/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..138e5be28441a9fe84bb0ebaf09ea6d524355679 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 66d250c..0f1f1f5 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.8 ++- **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) + #### 6.7 + - **.15**: Add curly braces to the list of characters to be escaped. (PhilRunninger) [#1128](https://github.com/preservim/nerdtree/pull/1128) + - **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index df0c804..fc7269e 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -22,7 +22,7 @@ syn match NERDTreeLinkDir #.*/ ->#me=e-3 containedin=NERDTreeDir + "highlighting to conceal the delimiter around the file/dir name + if has('conceal') + exec 'syn match NERDTreeNodeDelimiters #\%d' . char2nr(g:NERDTreeNodeDelimiter) . '# conceal containedin=ALL' +- setlocal conceallevel=3 concealcursor=nvic ++ setlocal conceallevel=2 concealcursor=nvic + else + exec 'syn match NERDTreeNodeDelimiters #\%d' . char2nr(g:NERDTreeNodeDelimiter) . '# containedin=ALL' + hi! link NERDTreeNodeDelimiters Ignore diff --git a/tasks/preservim__nerdtree-1138/solution/solve.sh b/tasks/preservim__nerdtree-1138/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1138/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/preservim__nerdtree-1138/task.toml b/tasks/preservim__nerdtree-1138/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4374c7f227c256a28b4ad180f054353c648ca096 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1138" +description = "Allow concealed characters to show another character." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "052b1f00a0ef14b0019f4d0cda9906ba93f9a0d6" +reference = "https://github.com/preservim/nerdtree/pull/1138" +source_access = "auto" +built_at = "2026-11-16T16:10:02.413203+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:468a6fec1493d07e08a0fc3d41ef60e3ffda6d1c65786a9a78621b47c30329d6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-06-01T06:08:14Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "syntax/nerdtree.vim", +] +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:02.582924+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:398c2dbef2f2db0edf601bb6eca81d04a1302ad80e73e47b244308a74940a651" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1138/tests/capture.py b/tasks/preservim__nerdtree-1138/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1138/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/preservim__nerdtree-1138/tests/instruction.md b/tasks/preservim__nerdtree-1138/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0e22573f2b4c98bf4b0325d1bcae9c2f1186352 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Allow concealed characters to show another character. + +## Description + +### Description of Changes + + +conceallevel=3 always hides the character, but conceallevel=2 allows an alternate character to be displayed instead. This change, and a similar one in [nerdtree-buffer-ops](https://github.com/PhilRunninger/nerdtree-buffer-ops) will allow every other leading space in NERDTree to be displayed as a vertical bar, as described in my comment on #1136 . + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `052b1f00a0ef`. 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/preservim__nerdtree-1138/tests/oracle.patch b/tasks/preservim__nerdtree-1138/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..138e5be28441a9fe84bb0ebaf09ea6d524355679 --- /dev/null +++ b/tasks/preservim__nerdtree-1138/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 66d250c..0f1f1f5 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.8 ++- **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) + #### 6.7 + - **.15**: Add curly braces to the list of characters to be escaped. (PhilRunninger) [#1128](https://github.com/preservim/nerdtree/pull/1128) + - **.14**: Use backward-compatible `nerdtree#and()` in one place that was missed. (PhilRunninger) [#1134](https://github.com/preservim/nerdtree/pull/1134) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index df0c804..fc7269e 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -22,7 +22,7 @@ syn match NERDTreeLinkDir #.*/ ->#me=e-3 containedin=NERDTreeDir + "highlighting to conceal the delimiter around the file/dir name + if has('conceal') + exec 'syn match NERDTreeNodeDelimiters #\%d' . char2nr(g:NERDTreeNodeDelimiter) . '# conceal containedin=ALL' +- setlocal conceallevel=3 concealcursor=nvic ++ setlocal conceallevel=2 concealcursor=nvic + else + exec 'syn match NERDTreeNodeDelimiters #\%d' . char2nr(g:NERDTreeNodeDelimiter) . '# containedin=ALL' + hi! link NERDTreeNodeDelimiters Ignore diff --git a/tasks/preservim__nerdtree-1138/tests/test.sh b/tasks/preservim__nerdtree-1138/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b5b6f488426dca554ec07e57541353af34d86ed --- /dev/null +++ b/tasks/preservim__nerdtree-1138/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 052b1f00a0ef14b0019f4d0cda9906ba93f9a0d6 > "$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/preservim__nerdtree-1138/tests/verifier.py b/tasks/preservim__nerdtree-1138/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1138/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/preservim__nerdtree-1144/environment/Dockerfile b/tasks/preservim__nerdtree-1144/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bd5571a55db4bc9061b43a89fc71c7cba65952ca --- /dev/null +++ b/tasks/preservim__nerdtree-1144/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d48ab70721d4f688ed34bd5939e2d6f4c89548c5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d48ab70721d4f688ed34bd5939e2d6f4c89548c5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d48ab70721d4f688ed34bd5939e2d6f4c89548c5 \ + && 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/preservim__nerdtree-1144/instruction.md b/tasks/preservim__nerdtree-1144/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a09359e084bb6202f5d35f8e483aac28d6086e4 --- /dev/null +++ b/tasks/preservim__nerdtree-1144/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Enable opening bookmarks in split windows. + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d48ab70721d4`. 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/preservim__nerdtree-1144/solution/patch.diff b/tasks/preservim__nerdtree-1144/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..67f5357da97e6787d485591fc3fdbbea7cc7a308 --- /dev/null +++ b/tasks/preservim__nerdtree-1144/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0f1f1f5..0380c67 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.9 ++- **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 + - **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) + #### 6.7 +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index aef1b04..612145f 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -26,11 +26,15 @@ function! nerdtree#ui_glue#createDefaultBindings() abort + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': 'all', 'callback': s.'activateAll' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Node', 'callback': s.'openHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Bookmark', 'callback': s.'openHSplitBookmark' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Node', 'callback': s.'openVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Bookmark', 'callback': s.'openVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Node', 'callback': s.'previewNodeCurrent' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Node', 'callback': s.'previewNodeHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeHSplitBookmark' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenRecursively, 'scope': 'DirNode', 'callback': s.'openNodeRecursively' }) + +@@ -511,6 +515,28 @@ function! s:openVSplit(target) abort + call a:target.activate({'where': 'v'}) + endfunction + ++"FUNCTION: s:openHSplitBookmark(bookmark) {{{1 ++"handle the user activating a bookmark ++function! s:openHSplitBookmark(bm) abort ++ call a:bm.activate(b:NERDTree, !a:bm.path.isDirectory ? {'where': 'h'} : {}) ++endfunction ++ ++"FUNCTION: s:openVSplitBookmark(bookmark) {{{1 ++"handle the user activating a bookmark ++function! s:openVSplitBookmark(bm) abort ++ call a:bm.activate(b:NERDTree, !a:bm.path.isDirectory ? {'where': 'v'} : {}) ++endfunction ++ ++" FUNCTION: s:previewHSplitBookmark(bookmark) {{{1 ++function! s:previewNodeHSplitBookmark(bookmark) abort ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'h', 'keepopen': 1} : {}) ++endfunction ++ ++" FUNCTION: s:previewVSplitBookmark(bookmark) {{{1 ++function! s:previewNodeVSplitBookmark(bookmark) abort ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'v', 'keepopen': 1} : {}) ++endfunction ++ + " FUNCTION: s:openExplorer(node) {{{1 + function! s:openExplorer(node) abort + call a:node.openExplorer() +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 6c11a94..7a6a931 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -350,7 +350,7 @@ The same as |NERDTree-t| except that the focus is kept in the current tab. + *NERDTree-i* + Default key: i + Map setting: *NERDTreeMapOpenSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + Opens the selected file in a new split window and puts the cursor in the new + window. +@@ -370,7 +370,7 @@ The default key combo for this mapping is "g" + NERDTreeMapOpenSplit (see + *NERDTree-s* + Default key: s + Map setting: *NERDTreeMapOpenVSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + Opens the selected file in a new vertically split window and puts the cursor + in the new window. +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 9ffadf6..ed8a248 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -67,6 +67,10 @@ function! s:UI._dumpHelp() + let help .= '" '. g:NERDTreeMapPreview .": find dir in tree\n" + let help .= '" '. g:NERDTreeMapOpenInTab.": open in new tab\n" + let help .= '" '. g:NERDTreeMapOpenInTabSilent .": open in new tab silently\n" ++ let help .= '" '. g:NERDTreeMapOpenSplit .": open split\n" ++ let help .= '" '. g:NERDTreeMapPreviewSplit .": preview split\n" ++ let help .= '" '. g:NERDTreeMapOpenVSplit .": open vsplit\n" ++ let help .= '" '. g:NERDTreeMapPreviewVSplit .": preview vsplit\n" + let help .= '" '. g:NERDTreeMapCustomOpen .": custom open\n" + let help .= '" '. g:NERDTreeMapDeleteBookmark .": delete bookmark\n" + diff --git a/tasks/preservim__nerdtree-1144/solution/solve.sh b/tasks/preservim__nerdtree-1144/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1144/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/preservim__nerdtree-1144/task.toml b/tasks/preservim__nerdtree-1144/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e48f7b79d34c56f550e1cf72a66de9796d969e15 --- /dev/null +++ b/tasks/preservim__nerdtree-1144/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1144" +description = "Enable opening bookmarks in split windows." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "d48ab70721d4f688ed34bd5939e2d6f4c89548c5" +reference = "https://github.com/preservim/nerdtree/pull/1144" +source_access = "auto" +built_at = "2026-11-16T16:10:02.411748+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4b1667cccb3a4fc5e81681772339c3d4f3ec79c3469b3a1430b21f570ccf7fba" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-06-23T14:40:30Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", + "doc/NERDTree.txt", + "lib/nerdtree/ui.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 38 +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:02.583491+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5885ba6850ecb87223448b0dc7ffbbeed15b528530ea011cd752e156a9b3c5cd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1144/tests/capture.py b/tasks/preservim__nerdtree-1144/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1144/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/preservim__nerdtree-1144/tests/instruction.md b/tasks/preservim__nerdtree-1144/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a09359e084bb6202f5d35f8e483aac28d6086e4 --- /dev/null +++ b/tasks/preservim__nerdtree-1144/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Enable opening bookmarks in split windows. + +## Description + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d48ab70721d4`. 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/preservim__nerdtree-1144/tests/oracle.patch b/tasks/preservim__nerdtree-1144/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..67f5357da97e6787d485591fc3fdbbea7cc7a308 --- /dev/null +++ b/tasks/preservim__nerdtree-1144/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0f1f1f5..0380c67 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.9 ++- **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 + - **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) + #### 6.7 +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index aef1b04..612145f 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -26,11 +26,15 @@ function! nerdtree#ui_glue#createDefaultBindings() abort + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': 'all', 'callback': s.'activateAll' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Node', 'callback': s.'openHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Bookmark', 'callback': s.'openHSplitBookmark' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Node', 'callback': s.'openVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Bookmark', 'callback': s.'openVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Node', 'callback': s.'previewNodeCurrent' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Node', 'callback': s.'previewNodeHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeHSplitBookmark' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenRecursively, 'scope': 'DirNode', 'callback': s.'openNodeRecursively' }) + +@@ -511,6 +515,28 @@ function! s:openVSplit(target) abort + call a:target.activate({'where': 'v'}) + endfunction + ++"FUNCTION: s:openHSplitBookmark(bookmark) {{{1 ++"handle the user activating a bookmark ++function! s:openHSplitBookmark(bm) abort ++ call a:bm.activate(b:NERDTree, !a:bm.path.isDirectory ? {'where': 'h'} : {}) ++endfunction ++ ++"FUNCTION: s:openVSplitBookmark(bookmark) {{{1 ++"handle the user activating a bookmark ++function! s:openVSplitBookmark(bm) abort ++ call a:bm.activate(b:NERDTree, !a:bm.path.isDirectory ? {'where': 'v'} : {}) ++endfunction ++ ++" FUNCTION: s:previewHSplitBookmark(bookmark) {{{1 ++function! s:previewNodeHSplitBookmark(bookmark) abort ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'h', 'keepopen': 1} : {}) ++endfunction ++ ++" FUNCTION: s:previewVSplitBookmark(bookmark) {{{1 ++function! s:previewNodeVSplitBookmark(bookmark) abort ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'v', 'keepopen': 1} : {}) ++endfunction ++ + " FUNCTION: s:openExplorer(node) {{{1 + function! s:openExplorer(node) abort + call a:node.openExplorer() +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 6c11a94..7a6a931 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -350,7 +350,7 @@ The same as |NERDTree-t| except that the focus is kept in the current tab. + *NERDTree-i* + Default key: i + Map setting: *NERDTreeMapOpenSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + Opens the selected file in a new split window and puts the cursor in the new + window. +@@ -370,7 +370,7 @@ The default key combo for this mapping is "g" + NERDTreeMapOpenSplit (see + *NERDTree-s* + Default key: s + Map setting: *NERDTreeMapOpenVSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + Opens the selected file in a new vertically split window and puts the cursor + in the new window. +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 9ffadf6..ed8a248 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -67,6 +67,10 @@ function! s:UI._dumpHelp() + let help .= '" '. g:NERDTreeMapPreview .": find dir in tree\n" + let help .= '" '. g:NERDTreeMapOpenInTab.": open in new tab\n" + let help .= '" '. g:NERDTreeMapOpenInTabSilent .": open in new tab silently\n" ++ let help .= '" '. g:NERDTreeMapOpenSplit .": open split\n" ++ let help .= '" '. g:NERDTreeMapPreviewSplit .": preview split\n" ++ let help .= '" '. g:NERDTreeMapOpenVSplit .": open vsplit\n" ++ let help .= '" '. g:NERDTreeMapPreviewVSplit .": preview vsplit\n" + let help .= '" '. g:NERDTreeMapCustomOpen .": custom open\n" + let help .= '" '. g:NERDTreeMapDeleteBookmark .": delete bookmark\n" + diff --git a/tasks/preservim__nerdtree-1144/tests/test.sh b/tasks/preservim__nerdtree-1144/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b08cc887bbe534a673971578febb10efd6de8ae --- /dev/null +++ b/tasks/preservim__nerdtree-1144/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 d48ab70721d4f688ed34bd5939e2d6f4c89548c5 > "$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/preservim__nerdtree-1144/tests/verifier.py b/tasks/preservim__nerdtree-1144/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1144/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/preservim__nerdtree-1151/environment/Dockerfile b/tasks/preservim__nerdtree-1151/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ed404d026bf0ff36ad7baeb689c8cad1839c07e4 --- /dev/null +++ b/tasks/preservim__nerdtree-1151/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6571452857fd1b14f15a3886f9fffc113c36bbac 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6571452857fd1b14f15a3886f9fffc113c36bbac \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6571452857fd1b14f15a3886f9fffc113c36bbac \ + && 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/preservim__nerdtree-1151/instruction.md b/tasks/preservim__nerdtree-1151/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d239162ab5c2b2a524cd67ed2bad303cedf13cbb --- /dev/null +++ b/tasks/preservim__nerdtree-1151/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Fix the scope of several key mappings + +## Description + +### Description of Changes + + +This pull request changes the scope of some of the key mappings. Prior to this, they were scoped to run on all node types: directory and file. But they didn't make sense to be run on directory nodes, as this creates another NERDTree in the new window. The key mappings whose scopes were changed are: `i`, `s`, `gi`, `gs`, and `go`. They now work only on file nodes and file bookmarks. + +When testing, it was discovered that the `go` command on directory bookmarks wasn't working correctly (probably because `NERDTreeFind` was changed some time back). Therefore, `s:previewBookmark()` was rewritten so that the bookmark directory would become the root of the NERDTree. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6571452857fd`. 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/preservim__nerdtree-1151/solution/patch.diff b/tasks/preservim__nerdtree-1151/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..af2a2f04dc16d8f5523bc7dcfdcd9fd86befe7fb --- /dev/null +++ b/tasks/preservim__nerdtree-1151/solution/patch.diff @@ -0,0 +1,84 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0380c67..068646e 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 + - **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 612145f..78b3fa1 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -25,15 +25,15 @@ function! nerdtree#ui_glue#createDefaultBindings() abort + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Bookmark', 'callback': s.'previewBookmark' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': 'all', 'callback': s.'activateAll' }) + +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Node', 'callback': s.'openHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'FileNode', 'callback': s.'openHSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Bookmark', 'callback': s.'openHSplitBookmark' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Node', 'callback': s.'openVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'FileNode', 'callback': s.'openVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Bookmark', 'callback': s.'openVSplitBookmark' }) + +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Node', 'callback': s.'previewNodeCurrent' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Node', 'callback': s.'previewNodeHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'FileNode', 'callback': s.'previewNodeCurrent' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'FileNode', 'callback': s.'previewNodeHSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeHSplitBookmark' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'FileNode', 'callback': s.'previewNodeVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenRecursively, 'scope': 'DirNode', 'callback': s.'openNodeRecursively' }) +@@ -564,11 +564,7 @@ endfunction + + " FUNCTION: s:previewBookmark(bookmark) {{{1 + function! s:previewBookmark(bookmark) abort +- if a:bookmark.path.isDirectory +- execute 'NERDTreeFind '.a:bookmark.path.str() +- else +- call a:bookmark.activate(b:NERDTree, {'stay': 1, 'where': 'p', 'keepopen': 1}) +- endif ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'h', 'keepopen': 1} : {}) + endfunction + + "FUNCTION: s:previewNodeCurrent(node) {{{1 +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 7a6a931..2989718 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -318,9 +318,8 @@ Applies to: files. + If a file node or a bookmark that links to a file is selected, it is opened in + the previous window, but the cursor does not move. + +-If a bookmark that links to a directory is selected, that directory is found +-in the current NERDTree. If the directory couldn't be found, a new NERDTree is +-created. ++If a bookmark that links to a directory is selected then that directory ++becomes the new root. + + The default key combo for this mapping is "g" + NERDTreeMapActivateNode (see + |NERDTree-o|). +@@ -359,7 +358,7 @@ window. + *NERDTree-gi* + Default key: gi + Map setting: *NERDTreeMapPreviewSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + The same as |NERDTree-i| except that the cursor is not moved. + +@@ -379,7 +378,7 @@ in the new window. + *NERDTree-gs* + Default key: gs + Map setting: *NERDTreeMapPreviewVSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + The same as |NERDTree-s| except that the cursor is not moved. + diff --git a/tasks/preservim__nerdtree-1151/solution/solve.sh b/tasks/preservim__nerdtree-1151/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1151/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/preservim__nerdtree-1151/task.toml b/tasks/preservim__nerdtree-1151/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..42c1f86810b9724702788a26c8f259d60e0d374d --- /dev/null +++ b/tasks/preservim__nerdtree-1151/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1151" +description = "Fix the scope of several key mappings" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "6571452857fd1b14f15a3886f9fffc113c36bbac" +reference = "https://github.com/preservim/nerdtree/pull/1151" +source_access = "auto" +built_at = "2026-11-16T16:10:02.410243+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cc24b192c7fccad94ab260225a15c61dedd1248fa34f1862a5be53b00c39a116" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-07-12T14:03:25Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", + "doc/NERDTree.txt", +] +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:02.584002+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d8d67d017c241e42ad268faddd2089efde9ffb5d86c8732141cc4324a434aada" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1151/tests/capture.py b/tasks/preservim__nerdtree-1151/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1151/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/preservim__nerdtree-1151/tests/instruction.md b/tasks/preservim__nerdtree-1151/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d239162ab5c2b2a524cd67ed2bad303cedf13cbb --- /dev/null +++ b/tasks/preservim__nerdtree-1151/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Fix the scope of several key mappings + +## Description + +### Description of Changes + + +This pull request changes the scope of some of the key mappings. Prior to this, they were scoped to run on all node types: directory and file. But they didn't make sense to be run on directory nodes, as this creates another NERDTree in the new window. The key mappings whose scopes were changed are: `i`, `s`, `gi`, `gs`, and `go`. They now work only on file nodes and file bookmarks. + +When testing, it was discovered that the `go` command on directory bookmarks wasn't working correctly (probably because `NERDTreeFind` was changed some time back). Therefore, `s:previewBookmark()` was rewritten so that the bookmark directory would become the root of the NERDTree. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6571452857fd`. 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/preservim__nerdtree-1151/tests/oracle.patch b/tasks/preservim__nerdtree-1151/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..af2a2f04dc16d8f5523bc7dcfdcd9fd86befe7fb --- /dev/null +++ b/tasks/preservim__nerdtree-1151/tests/oracle.patch @@ -0,0 +1,84 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 0380c67..068646e 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 + - **.0**: Allow concealed characters to show another character. (PhilRunninger) [#1138](https://github.com/preservim/nerdtree/pull/1138) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 612145f..78b3fa1 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -25,15 +25,15 @@ function! nerdtree#ui_glue#createDefaultBindings() abort + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Bookmark', 'callback': s.'previewBookmark' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapActivateNode, 'scope': 'all', 'callback': s.'activateAll' }) + +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Node', 'callback': s.'openHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'FileNode', 'callback': s.'openHSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenSplit, 'scope': 'Bookmark', 'callback': s.'openHSplitBookmark' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Node', 'callback': s.'openVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'FileNode', 'callback': s.'openVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenVSplit, 'scope': 'Bookmark', 'callback': s.'openVSplitBookmark' }) + +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'Node', 'callback': s.'previewNodeCurrent' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Node', 'callback': s.'previewNodeHSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreview, 'scope': 'FileNode', 'callback': s.'previewNodeCurrent' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'FileNode', 'callback': s.'previewNodeHSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeHSplitBookmark' }) +- call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Node', 'callback': s.'previewNodeVSplit' }) ++ call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'FileNode', 'callback': s.'previewNodeVSplit' }) + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapPreviewVSplit, 'scope': 'Bookmark', 'callback': s.'previewNodeVSplitBookmark' }) + + call NERDTreeAddKeyMap({ 'key': g:NERDTreeMapOpenRecursively, 'scope': 'DirNode', 'callback': s.'openNodeRecursively' }) +@@ -564,11 +564,7 @@ endfunction + + " FUNCTION: s:previewBookmark(bookmark) {{{1 + function! s:previewBookmark(bookmark) abort +- if a:bookmark.path.isDirectory +- execute 'NERDTreeFind '.a:bookmark.path.str() +- else +- call a:bookmark.activate(b:NERDTree, {'stay': 1, 'where': 'p', 'keepopen': 1}) +- endif ++ call a:bookmark.activate(b:NERDTree, !a:bookmark.path.isDirectory ? {'stay': 1, 'where': 'h', 'keepopen': 1} : {}) + endfunction + + "FUNCTION: s:previewNodeCurrent(node) {{{1 +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 7a6a931..2989718 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -318,9 +318,8 @@ Applies to: files. + If a file node or a bookmark that links to a file is selected, it is opened in + the previous window, but the cursor does not move. + +-If a bookmark that links to a directory is selected, that directory is found +-in the current NERDTree. If the directory couldn't be found, a new NERDTree is +-created. ++If a bookmark that links to a directory is selected then that directory ++becomes the new root. + + The default key combo for this mapping is "g" + NERDTreeMapActivateNode (see + |NERDTree-o|). +@@ -359,7 +358,7 @@ window. + *NERDTree-gi* + Default key: gi + Map setting: *NERDTreeMapPreviewSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + The same as |NERDTree-i| except that the cursor is not moved. + +@@ -379,7 +378,7 @@ in the new window. + *NERDTree-gs* + Default key: gs + Map setting: *NERDTreeMapPreviewVSplit* +-Applies to: files. ++Applies to: files, and bookmarks pointing to files. + + The same as |NERDTree-s| except that the cursor is not moved. + diff --git a/tasks/preservim__nerdtree-1151/tests/test.sh b/tasks/preservim__nerdtree-1151/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..63a27b59ed4418d2d86a13a564302e50176d580c --- /dev/null +++ b/tasks/preservim__nerdtree-1151/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 6571452857fd1b14f15a3886f9fffc113c36bbac > "$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/preservim__nerdtree-1151/tests/verifier.py b/tasks/preservim__nerdtree-1151/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1151/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/preservim__nerdtree-1153/environment/Dockerfile b/tasks/preservim__nerdtree-1153/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..394f766466ac8bcee109594d88ce0978319dcfb5 --- /dev/null +++ b/tasks/preservim__nerdtree-1153/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin aa37cb40dae26f21a2e343d17ac9f4be9d8bec37 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard aa37cb40dae26f21a2e343d17ac9f4be9d8bec37 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base aa37cb40dae26f21a2e343d17ac9f4be9d8bec37 \ + && 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/preservim__nerdtree-1153/instruction.md b/tasks/preservim__nerdtree-1153/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5ba29372f40bb3d8853cbdd19a98a38e29dc077 --- /dev/null +++ b/tasks/preservim__nerdtree-1153/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Fix new NERDTrees' width when previous one was in the only window. + +## Description + +When leaving a NERDTree buffer, its window's width is remembered so that +that width can be used when showing the buffer again in a new window. If +NERDTree is the only window when leaving the buffer, it remembers the +whole width of the editor. When a new NERDTree window is created, it is +sized such that there is only a very small window for files to be opened +into. + +To fix this, if NERDTree is the ONLY window, remember its width as the +value of g:NERDTreeWinSize, not the width of the editor. + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aa37cb40dae2`. 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/preservim__nerdtree-1153/solution/patch.diff b/tasks/preservim__nerdtree-1153/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cf77d5ada7a487ec0490ac3917a93efcc3fe3fec --- /dev/null +++ b/tasks/preservim__nerdtree-1153/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 068646e..f82701c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index ed8a248..2ea813c 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -368,7 +368,7 @@ function! s:UI.saveScreenState() + call g:NERDTree.CursorToTreeWin() + let self._screenState['oldPos'] = getpos('.') + let self._screenState['oldTopLine'] = line('w0') +- let self._screenState['oldWindowSize']= winwidth('') ++ let self._screenState['oldWindowSize'] = winnr('$')==1 ? g:NERDTreeWinSize : winwidth('') + call nerdtree#exec(win . 'wincmd w', 1) + catch + endtry diff --git a/tasks/preservim__nerdtree-1153/solution/solve.sh b/tasks/preservim__nerdtree-1153/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1153/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/preservim__nerdtree-1153/task.toml b/tasks/preservim__nerdtree-1153/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..94052a296a241a5385ea379288d778833d410acf --- /dev/null +++ b/tasks/preservim__nerdtree-1153/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1153" +description = "Fix new NERDTrees' width when previous one was in the only window." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "aa37cb40dae26f21a2e343d17ac9f4be9d8bec37" +reference = "https://github.com/preservim/nerdtree/pull/1153" +source_access = "auto" +built_at = "2026-11-16T16:10:02.408722+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:626b40d58936c024675d2329580963d372514e66b2908274f4b8b82d9beb90dd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-07-14T11:20:49Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/ui.vim", +] +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:02.584546+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9a145b4306aee3bd1f8300f6ed76983446f75d57860aa2d847ee5d6a6a72ce73" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1153/tests/capture.py b/tasks/preservim__nerdtree-1153/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1153/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/preservim__nerdtree-1153/tests/instruction.md b/tasks/preservim__nerdtree-1153/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5ba29372f40bb3d8853cbdd19a98a38e29dc077 --- /dev/null +++ b/tasks/preservim__nerdtree-1153/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Fix new NERDTrees' width when previous one was in the only window. + +## Description + +When leaving a NERDTree buffer, its window's width is remembered so that +that width can be used when showing the buffer again in a new window. If +NERDTree is the only window when leaving the buffer, it remembers the +whole width of the editor. When a new NERDTree window is created, it is +sized such that there is only a very small window for files to be opened +into. + +To fix this, if NERDTree is the ONLY window, remember its width as the +value of g:NERDTreeWinSize, not the width of the editor. + +### Description of Changes + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merge, tag the merge commit, e.g. `git tag -a 3.1.4 -m "v3.1.4" && git push origin --tags` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `aa37cb40dae2`. 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/preservim__nerdtree-1153/tests/oracle.patch b/tasks/preservim__nerdtree-1153/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cf77d5ada7a487ec0490ac3917a93efcc3fe3fec --- /dev/null +++ b/tasks/preservim__nerdtree-1153/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 068646e..f82701c 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.0**: Enable opening bookmarks in split windows. (PhilRunninger) [#1144](https://github.com/preservim/nerdtree/pull/1144) + #### 6.8 +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index ed8a248..2ea813c 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -368,7 +368,7 @@ function! s:UI.saveScreenState() + call g:NERDTree.CursorToTreeWin() + let self._screenState['oldPos'] = getpos('.') + let self._screenState['oldTopLine'] = line('w0') +- let self._screenState['oldWindowSize']= winwidth('') ++ let self._screenState['oldWindowSize'] = winnr('$')==1 ? g:NERDTreeWinSize : winwidth('') + call nerdtree#exec(win . 'wincmd w', 1) + catch + endtry diff --git a/tasks/preservim__nerdtree-1153/tests/test.sh b/tasks/preservim__nerdtree-1153/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..40d9ede029ce1a0360b9203693db5d35de8cec2a --- /dev/null +++ b/tasks/preservim__nerdtree-1153/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 aa37cb40dae26f21a2e343d17ac9f4be9d8bec37 > "$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/preservim__nerdtree-1153/tests/verifier.py b/tasks/preservim__nerdtree-1153/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1153/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/preservim__nerdtree-1156/environment/Dockerfile b/tasks/preservim__nerdtree-1156/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..433381c4c30eebd94bf5d30c9a29ca5bfe8319e9 --- /dev/null +++ b/tasks/preservim__nerdtree-1156/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 96e247ba7488af1e71d0facfc68aba37e750298c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 96e247ba7488af1e71d0facfc68aba37e750298c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 96e247ba7488af1e71d0facfc68aba37e750298c \ + && 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/preservim__nerdtree-1156/instruction.md b/tasks/preservim__nerdtree-1156/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..645ce37c4e004253ce1c5ac012643337bc2ac8ae --- /dev/null +++ b/tasks/preservim__nerdtree-1156/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Make sure symbolic links' flags are highlighted correctly. + +## Description + +### Description of Changes + + +Make sure the `NERDTreeFlags` syntax group is contained in the `NERDTreeLinkFile` group so that [vim-devicons](https://github.com/ryanoasis/vim-devicons) successfully can hide the brackets. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96e247ba7488`. 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/preservim__nerdtree-1156/solution/patch.diff b/tasks/preservim__nerdtree-1156/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..16287df251bca25a676e1c9cab14add5f0ec48e6 --- /dev/null +++ b/tasks/preservim__nerdtree-1156/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 9d05ee5..439ca05 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.1**: Respect user's `&shellslash` setting in CopyNode and RemoveNode functions (PhilRunninger) [#1150](https://github.com/preservim/nerdtree/pull/1150) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index fc7269e..af1581c 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -47,7 +47,7 @@ endif + "highlighting for readonly files + exec 'syn match NERDTreeRO #.*'.g:NERDTreeNodeDelimiter.'\zs.*\ze'.g:NERDTreeNodeDelimiter.'.*\['.g:NERDTreeGlyphReadOnly.'\]# contains=NERDTreeIgnore,NERDTreeBookmark,NERDTreeFile' + +-exec 'syn match NERDTreeFlags #\[[^\]]*\]\ze'.g:NERDTreeNodeDelimiter.'# containedin=NERDTreeFile,NERDTreeExecFile,NERDTreeDir' ++exec 'syn match NERDTreeFlags #\[[^\]]*\]\ze'.g:NERDTreeNodeDelimiter.'# containedin=NERDTreeFile,NERDTreeExecFile,NERDTreeLinkFile,NERDTreeRO,NERDTreeDir' + + syn match NERDTreeCWD #^[ 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/preservim__nerdtree-1156/tests/instruction.md b/tasks/preservim__nerdtree-1156/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..645ce37c4e004253ce1c5ac012643337bc2ac8ae --- /dev/null +++ b/tasks/preservim__nerdtree-1156/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Make sure symbolic links' flags are highlighted correctly. + +## Description + +### Description of Changes + + +Make sure the `NERDTreeFlags` syntax group is contained in the `NERDTreeLinkFile` group so that [vim-devicons](https://github.com/ryanoasis/vim-devicons) successfully can hide the brackets. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96e247ba7488`. 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/preservim__nerdtree-1156/tests/oracle.patch b/tasks/preservim__nerdtree-1156/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..16287df251bca25a676e1c9cab14add5f0ec48e6 --- /dev/null +++ b/tasks/preservim__nerdtree-1156/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 9d05ee5..439ca05 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) + - **.1**: Respect user's `&shellslash` setting in CopyNode and RemoveNode functions (PhilRunninger) [#1150](https://github.com/preservim/nerdtree/pull/1150) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index fc7269e..af1581c 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -47,7 +47,7 @@ endif + "highlighting for readonly files + exec 'syn match NERDTreeRO #.*'.g:NERDTreeNodeDelimiter.'\zs.*\ze'.g:NERDTreeNodeDelimiter.'.*\['.g:NERDTreeGlyphReadOnly.'\]# contains=NERDTreeIgnore,NERDTreeBookmark,NERDTreeFile' + +-exec 'syn match NERDTreeFlags #\[[^\]]*\]\ze'.g:NERDTreeNodeDelimiter.'# containedin=NERDTreeFile,NERDTreeExecFile,NERDTreeDir' ++exec 'syn match NERDTreeFlags #\[[^\]]*\]\ze'.g:NERDTreeNodeDelimiter.'# containedin=NERDTreeFile,NERDTreeExecFile,NERDTreeLinkFile,NERDTreeRO,NERDTreeDir' + + syn match NERDTreeCWD #^[ "$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/preservim__nerdtree-1156/tests/verifier.py b/tasks/preservim__nerdtree-1156/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1156/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/preservim__nerdtree-1157/environment/Dockerfile b/tasks/preservim__nerdtree-1157/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9de77d94a56f9b2fb55c1ba61fa8dc0db4952204 --- /dev/null +++ b/tasks/preservim__nerdtree-1157/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e571d3e95b610fc4435e01524bb594d642f5db79 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e571d3e95b610fc4435e01524bb594d642f5db79 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e571d3e95b610fc4435e01524bb594d642f5db79 \ + && 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/preservim__nerdtree-1157/instruction.md b/tasks/preservim__nerdtree-1157/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aab81991d94cc7ef274dec45c49563f1a7c6082e --- /dev/null +++ b/tasks/preservim__nerdtree-1157/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix highlight for file node + +## Description + +### Description of Changes +Fix for #960 #953 + +The issue arise because `NERDTreeFile` is linked to `Normal` highlight. This caused the file node background to be the same as whatever color `Normal` is using, thus the highlight is different than the cursorline. + +My solution is to clear bg highlight for `NERDTreeFile`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e571d3e95b61`. 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/preservim__nerdtree-1157/solution/patch.diff b/tasks/preservim__nerdtree-1157/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac54fdbb8f03833813629bd66ea7adeeab78b96c --- /dev/null +++ b/tasks/preservim__nerdtree-1157/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 439ca05..4487861 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index af1581c..bf523d1 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -93,3 +93,5 @@ hi def link NERDTreeBookmark Statement + hi def link NERDTreeFlags Number + + hi def link NERDTreeCurrentNode Search ++ ++hi NERDTreeFile ctermbg=NONE guibg=NONE diff --git a/tasks/preservim__nerdtree-1157/solution/solve.sh b/tasks/preservim__nerdtree-1157/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1157/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/preservim__nerdtree-1157/task.toml b/tasks/preservim__nerdtree-1157/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f1be8e6d36e8ece49f55686dd62a2cd52427e1bf --- /dev/null +++ b/tasks/preservim__nerdtree-1157/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1157" +description = "fix highlight for file node" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "e571d3e95b610fc4435e01524bb594d642f5db79" +reference = "https://github.com/preservim/nerdtree/pull/1157" +source_access = "auto" +built_at = "2026-11-16T16:10:02.405904+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2992b1cba93701418f725dd114409029efb9509226bd3dc0fb2c279c801ebdbf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-07-24T15:14:55Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "syntax/nerdtree.vim", +] +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:02.585580+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:85170d17017d3c7896b4fdf9db23ba56ee598dcd7b649b999c61897dd8ec2eb8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1157/tests/capture.py b/tasks/preservim__nerdtree-1157/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1157/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/preservim__nerdtree-1157/tests/instruction.md b/tasks/preservim__nerdtree-1157/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aab81991d94cc7ef274dec45c49563f1a7c6082e --- /dev/null +++ b/tasks/preservim__nerdtree-1157/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix highlight for file node + +## Description + +### Description of Changes +Fix for #960 #953 + +The issue arise because `NERDTreeFile` is linked to `Normal` highlight. This caused the file node background to be the same as whatever color `Normal` is using, thus the highlight is different than the cursorline. + +My solution is to clear bg highlight for `NERDTreeFile`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e571d3e95b61`. 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/preservim__nerdtree-1157/tests/oracle.patch b/tasks/preservim__nerdtree-1157/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ac54fdbb8f03833813629bd66ea7adeeab78b96c --- /dev/null +++ b/tasks/preservim__nerdtree-1157/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 439ca05..4487861 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) + - **.2**: Fix the scope of several key mappings (lifecrisis, PhilRunninger) [#1151](https://github.com/preservim/nerdtree/pull/1151) +diff --git a/syntax/nerdtree.vim b/syntax/nerdtree.vim +index af1581c..bf523d1 100644 +--- a/syntax/nerdtree.vim ++++ b/syntax/nerdtree.vim +@@ -93,3 +93,5 @@ hi def link NERDTreeBookmark Statement + hi def link NERDTreeFlags Number + + hi def link NERDTreeCurrentNode Search ++ ++hi NERDTreeFile ctermbg=NONE guibg=NONE diff --git a/tasks/preservim__nerdtree-1157/tests/test.sh b/tasks/preservim__nerdtree-1157/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f72b4baafd2258434f3fc38c9cb749cb47e16d6 --- /dev/null +++ b/tasks/preservim__nerdtree-1157/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 e571d3e95b610fc4435e01524bb594d642f5db79 > "$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/preservim__nerdtree-1157/tests/verifier.py b/tasks/preservim__nerdtree-1157/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1157/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/preservim__nerdtree-1164/environment/Dockerfile b/tasks/preservim__nerdtree-1164/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83f4913a17b74331f3f932f1cea2ee1139b36ff6 --- /dev/null +++ b/tasks/preservim__nerdtree-1164/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4a32dd0be35621dc8d4b73836f58434ff3e73124 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4a32dd0be35621dc8d4b73836f58434ff3e73124 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4a32dd0be35621dc8d4b73836f58434ff3e73124 \ + && 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/preservim__nerdtree-1164/instruction.md b/tasks/preservim__nerdtree-1164/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7f38cd9816167f8078d41660f66f93307e32dce --- /dev/null +++ b/tasks/preservim__nerdtree-1164/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Don't use silent when raising User events + +## Description + +### Description of Changes + + +The `silent` prefix is there to prevent the display of the `No matching autocommands` warning message. Leaving it in, though, prevents the display of debugging statements in functions that handle the event. As suggested by @tpope, my solution is to remove the `silent` and wrap the `doautocmd` statement in an `if exists('#...')` clause. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4a32dd0be356`. 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/preservim__nerdtree-1164/solution/patch.diff b/tasks/preservim__nerdtree-1164/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0480fdcd5919d889ed288ef392295bed89932e11 --- /dev/null +++ b/tasks/preservim__nerdtree-1164/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 4487861..61f0111 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 210ec37..4f0a7dc 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -28,7 +28,9 @@ endfunction + + " FUNCTION: s:Creator._broadcastInitEvent() {{{1 + function! s:Creator._broadcastInitEvent() +- silent doautocmd User NERDTreeInit ++ if exists('#NERDTreeInit') ++ doautocmd User NERDTreeInit ++ endif + endfunction + + " FUNCTION: s:Creator.BufNamePrefix() {{{1 +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 982db16..ed060f6 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -27,7 +27,9 @@ function! s:NERDTree.changeRoot(node) + call self.render() + call self.root.putCursorHere(0, 0) + +- silent doautocmd User NERDTreeNewRoot ++ if exists('#NERDTreeNewRoot') ++ doautocmd User NERDTreeNewRoot ++ endif + endfunction + + "FUNCTION: s:NERDTree.Close() {{{1 diff --git a/tasks/preservim__nerdtree-1164/solution/solve.sh b/tasks/preservim__nerdtree-1164/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1164/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/preservim__nerdtree-1164/task.toml b/tasks/preservim__nerdtree-1164/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b189aedc470a4668a15c67cc813c6548d9516145 --- /dev/null +++ b/tasks/preservim__nerdtree-1164/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1164" +description = "Don't use silent when raising User events" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "4a32dd0be35621dc8d4b73836f58434ff3e73124" +reference = "https://github.com/preservim/nerdtree/pull/1164" +source_access = "auto" +built_at = "2026-11-16T16:10:02.404473+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2ddf637b46f7ae24cd17e877cb266d2317b23d73356ae24597767fcdd725d0bc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-08-07T04:37:57Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/creator.vim", + "lib/nerdtree/nerdtree.vim", +] +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:02.586130+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:386165e473d7403367c2f382d940bb2cb03a083cf0d83a2a192d3d7031328a57" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1164/tests/capture.py b/tasks/preservim__nerdtree-1164/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1164/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/preservim__nerdtree-1164/tests/instruction.md b/tasks/preservim__nerdtree-1164/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7f38cd9816167f8078d41660f66f93307e32dce --- /dev/null +++ b/tasks/preservim__nerdtree-1164/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Don't use silent when raising User events + +## Description + +### Description of Changes + + +The `silent` prefix is there to prevent the display of the `No matching autocommands` warning message. Leaving it in, though, prevents the display of debugging statements in functions that handle the event. As suggested by @tpope, my solution is to remove the `silent` and wrap the `doautocmd` statement in an `if exists('#...')` clause. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4a32dd0be356`. 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/preservim__nerdtree-1164/tests/oracle.patch b/tasks/preservim__nerdtree-1164/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0480fdcd5919d889ed288ef392295bed89932e11 --- /dev/null +++ b/tasks/preservim__nerdtree-1164/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 4487861..61f0111 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) + - **.3**: Fix new NERDTrees' width when previous one was in the only window. (PhilRunninger) [#1153](https://github.com/preservim/nerdtree/pull/1153) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 210ec37..4f0a7dc 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -28,7 +28,9 @@ endfunction + + " FUNCTION: s:Creator._broadcastInitEvent() {{{1 + function! s:Creator._broadcastInitEvent() +- silent doautocmd User NERDTreeInit ++ if exists('#NERDTreeInit') ++ doautocmd User NERDTreeInit ++ endif + endfunction + + " FUNCTION: s:Creator.BufNamePrefix() {{{1 +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index 982db16..ed060f6 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -27,7 +27,9 @@ function! s:NERDTree.changeRoot(node) + call self.render() + call self.root.putCursorHere(0, 0) + +- silent doautocmd User NERDTreeNewRoot ++ if exists('#NERDTreeNewRoot') ++ doautocmd User NERDTreeNewRoot ++ endif + endfunction + + "FUNCTION: s:NERDTree.Close() {{{1 diff --git a/tasks/preservim__nerdtree-1164/tests/test.sh b/tasks/preservim__nerdtree-1164/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6753d259c7d45fbc7dd12949ad0c5c2a285a61e --- /dev/null +++ b/tasks/preservim__nerdtree-1164/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 4a32dd0be35621dc8d4b73836f58434ff3e73124 > "$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/preservim__nerdtree-1164/tests/verifier.py b/tasks/preservim__nerdtree-1164/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1164/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/preservim__nerdtree-1165/environment/Dockerfile b/tasks/preservim__nerdtree-1165/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3758ca3ae360848fb2c4ebb93a174d8408d08615 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 373a4b28e4444a5ec88ed3a81eb09073e8c92fc0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 373a4b28e4444a5ec88ed3a81eb09073e8c92fc0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 373a4b28e4444a5ec88ed3a81eb09073e8c92fc0 \ + && 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/preservim__nerdtree-1165/instruction.md b/tasks/preservim__nerdtree-1165/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cccf506873f374f2a3d476b13366bb36f9b54542 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix argument of exists() function calls checking for autocommands. + +## Description + +### Description of Changes + + +The `exists()` function needs to look for `#User#NERDTreeInit` instead of just `#NERDTreeInit`. + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `373a4b28e444`. 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/preservim__nerdtree-1165/solution/patch.diff b/tasks/preservim__nerdtree-1165/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dc3bb7d63d17075db5a739221aa423c7a33eef43 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 61f0111..4a6e454 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 4f0a7dc..4a98413 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -28,7 +28,7 @@ endfunction + + " FUNCTION: s:Creator._broadcastInitEvent() {{{1 + function! s:Creator._broadcastInitEvent() +- if exists('#NERDTreeInit') ++ if exists('#User#NERDTreeInit') + doautocmd User NERDTreeInit + endif + endfunction +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index ed060f6..db9e2b5 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -27,7 +27,7 @@ function! s:NERDTree.changeRoot(node) + call self.render() + call self.root.putCursorHere(0, 0) + +- if exists('#NERDTreeNewRoot') ++ if exists('#User#NERDTreeNewRoot') + doautocmd User NERDTreeNewRoot + endif + endfunction diff --git a/tasks/preservim__nerdtree-1165/solution/solve.sh b/tasks/preservim__nerdtree-1165/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1165/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/preservim__nerdtree-1165/task.toml b/tasks/preservim__nerdtree-1165/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d58e7fc88dac7fc1c118e21c9027065dad89fc2 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1165" +description = "Fix argument of exists() function calls checking for autocommands." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "373a4b28e4444a5ec88ed3a81eb09073e8c92fc0" +reference = "https://github.com/preservim/nerdtree/pull/1165" +source_access = "auto" +built_at = "2026-11-16T16:10:02.403042+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4ae535b80fea722cf0faa40f23af8d41e8f53054ac8858001cd15cbe0d94fc67" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-08-09T11:07:55Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/creator.vim", + "lib/nerdtree/nerdtree.vim", +] +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:02.586710+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e3bdf41b65970c05edd28e9d5919f8231f4275e8714863595802e84735486361" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1165/tests/capture.py b/tasks/preservim__nerdtree-1165/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1165/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/preservim__nerdtree-1165/tests/instruction.md b/tasks/preservim__nerdtree-1165/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cccf506873f374f2a3d476b13366bb36f9b54542 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix argument of exists() function calls checking for autocommands. + +## Description + +### Description of Changes + + +The `exists()` function needs to look for `#User#NERDTreeInit` instead of just `#NERDTreeInit`. + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `373a4b28e444`. 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/preservim__nerdtree-1165/tests/oracle.patch b/tasks/preservim__nerdtree-1165/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dc3bb7d63d17075db5a739221aa423c7a33eef43 --- /dev/null +++ b/tasks/preservim__nerdtree-1165/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 61f0111..4a6e454 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) + - **.4**: Make sure symbolic links' flags are highlighted correctly. (PhilRunninger) [#1156](https://github.com/preservim/nerdtree/pull/1156) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 4f0a7dc..4a98413 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -28,7 +28,7 @@ endfunction + + " FUNCTION: s:Creator._broadcastInitEvent() {{{1 + function! s:Creator._broadcastInitEvent() +- if exists('#NERDTreeInit') ++ if exists('#User#NERDTreeInit') + doautocmd User NERDTreeInit + endif + endfunction +diff --git a/lib/nerdtree/nerdtree.vim b/lib/nerdtree/nerdtree.vim +index ed060f6..db9e2b5 100644 +--- a/lib/nerdtree/nerdtree.vim ++++ b/lib/nerdtree/nerdtree.vim +@@ -27,7 +27,7 @@ function! s:NERDTree.changeRoot(node) + call self.render() + call self.root.putCursorHere(0, 0) + +- if exists('#NERDTreeNewRoot') ++ if exists('#User#NERDTreeNewRoot') + doautocmd User NERDTreeNewRoot + endif + endfunction diff --git a/tasks/preservim__nerdtree-1165/tests/test.sh b/tasks/preservim__nerdtree-1165/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..165cd211418555eb3759db6cb22738b5bc527cab --- /dev/null +++ b/tasks/preservim__nerdtree-1165/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 373a4b28e4444a5ec88ed3a81eb09073e8c92fc0 > "$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/preservim__nerdtree-1165/tests/verifier.py b/tasks/preservim__nerdtree-1165/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1165/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/preservim__nerdtree-1166/environment/Dockerfile b/tasks/preservim__nerdtree-1166/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0218ed046c1aa04e0a8a45bf5ddabe73a18a9308 --- /dev/null +++ b/tasks/preservim__nerdtree-1166/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6b5d70e5bf307bd84fec90ba77fa661036ff0361 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6b5d70e5bf307bd84fec90ba77fa661036ff0361 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6b5d70e5bf307bd84fec90ba77fa661036ff0361 \ + && 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/preservim__nerdtree-1166/instruction.md b/tasks/preservim__nerdtree-1166/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f9711bb2dff25e00fb5c96bc46e4ed57daafec5 --- /dev/null +++ b/tasks/preservim__nerdtree-1166/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Refactor sort comparison functions, removing redundancy + +## Description + +### Description of Changes +When researching #1162, I discovered a pair of functions that were doing very much the same thing: `Path.compareTo(path)` and `nerdtree#compareNodesBySortKey(n1,n2)`. I removed the `compareTo` function, and used the more robust `compareNodesBySortKey` function instead. + +Speaking of `compareNodesBySortKey`, there was another function named `compareNodes` that appeared to be unused. On the off chance that was written for other plugins, I decided to keep that function, refactored to fit the new structure. + +I also added a new function to accept two path objects instead of node objects. It's named `nerdtree#compareNodePaths`, and to keep things simple, it is called by `nerdtree#compareNodes`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6b5d70e5bf30`. 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/preservim__nerdtree-1166/solution/patch.diff b/tasks/preservim__nerdtree-1166/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8d8c78ac057cc6a10aca974c037ef2fb86fd1276 --- /dev/null +++ b/tasks/preservim__nerdtree-1166/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 4a6e454..55806cb 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index c935827..983bb62 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -110,15 +110,15 @@ function! nerdtree#completeBookmarks(A,L,P) abort + return filter(g:NERDTreeBookmark.BookmarkNames(), 'v:val =~# "^' . a:A . '"') + endfunction + +-"FUNCTION: nerdtree#compareNodes(dir) {{{2 ++"FUNCTION: nerdtree#compareNodes(n1, n2) {{{2 + function! nerdtree#compareNodes(n1, n2) abort +- return a:n1.path.compareTo(a:n2.path) ++ return nerdtree#compareNodePaths(a:n1.path, a:n2.path) + endfunction + +-"FUNCTION: nerdtree#compareNodesBySortKey(n1, n2) {{{2 +-function! nerdtree#compareNodesBySortKey(n1, n2) abort +- let sortKey1 = a:n1.path.getSortKey() +- let sortKey2 = a:n2.path.getSortKey() ++"FUNCTION: nerdtree#compareNodePaths(p1, p2) {{{2 ++function! nerdtree#compareNodePaths(p1, p2) abort ++ let sortKey1 = a:p1.getSortKey() ++ let sortKey2 = a:p2.getSortKey() + let i = 0 + while i < min([len(sortKey1), len(sortKey2)]) + " Compare chunks upto common length. +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 21e357b..786ccd9 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -99,50 +99,6 @@ function! s:Path.changeToDir() + endtry + endfunction + +-" FUNCTION: Path.compareTo() {{{1 +-" +-" Compares this Path to the given path and returns 0 if they are equal, -1 if +-" this Path is 'less than' the given path, or 1 if it is 'greater'. +-" +-" Args: +-" path: the path object to compare this to +-" +-" Return: +-" 1, -1 or 0 +-function! s:Path.compareTo(path) +- let thisPath = self.getLastPathComponent(1) +- let thatPath = a:path.getLastPathComponent(1) +- +- "if the paths are the same then clearly we return 0 +- if thisPath ==# thatPath +- return 0 +- endif +- +- let thisSS = self.getSortOrderIndex() +- let thatSS = a:path.getSortOrderIndex() +- +- "compare the sort sequences, if they are different then the return +- "value is easy +- if thisSS < thatSS +- return -1 +- elseif thisSS > thatSS +- return 1 +- else +- if !g:NERDTreeSortHiddenFirst +- let thisPath = substitute(thisPath, '^[._]', '', '') +- let thatPath = substitute(thatPath, '^[._]', '', '') +- endif +- "if the sort sequences are the same then compare the paths +- "alphabetically +- let pathCompare = g:NERDTreeCaseSensitiveSort ? thisPath <# thatPath : thisPath 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/preservim__nerdtree-1166/tests/instruction.md b/tasks/preservim__nerdtree-1166/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f9711bb2dff25e00fb5c96bc46e4ed57daafec5 --- /dev/null +++ b/tasks/preservim__nerdtree-1166/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Refactor sort comparison functions, removing redundancy + +## Description + +### Description of Changes +When researching #1162, I discovered a pair of functions that were doing very much the same thing: `Path.compareTo(path)` and `nerdtree#compareNodesBySortKey(n1,n2)`. I removed the `compareTo` function, and used the more robust `compareNodesBySortKey` function instead. + +Speaking of `compareNodesBySortKey`, there was another function named `compareNodes` that appeared to be unused. On the off chance that was written for other plugins, I decided to keep that function, refactored to fit the new structure. + +I also added a new function to accept two path objects instead of node objects. It's named `nerdtree#compareNodePaths`, and to keep things simple, it is called by `nerdtree#compareNodes`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6b5d70e5bf30`. 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/preservim__nerdtree-1166/tests/oracle.patch b/tasks/preservim__nerdtree-1166/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8d8c78ac057cc6a10aca974c037ef2fb86fd1276 --- /dev/null +++ b/tasks/preservim__nerdtree-1166/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 4a6e454..55806cb 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) + - **.5**: Fix highlight for file node. (pirey) [#1157](https://github.com/preservim/nerdtree/pull/1157) +diff --git a/autoload/nerdtree.vim b/autoload/nerdtree.vim +index c935827..983bb62 100644 +--- a/autoload/nerdtree.vim ++++ b/autoload/nerdtree.vim +@@ -110,15 +110,15 @@ function! nerdtree#completeBookmarks(A,L,P) abort + return filter(g:NERDTreeBookmark.BookmarkNames(), 'v:val =~# "^' . a:A . '"') + endfunction + +-"FUNCTION: nerdtree#compareNodes(dir) {{{2 ++"FUNCTION: nerdtree#compareNodes(n1, n2) {{{2 + function! nerdtree#compareNodes(n1, n2) abort +- return a:n1.path.compareTo(a:n2.path) ++ return nerdtree#compareNodePaths(a:n1.path, a:n2.path) + endfunction + +-"FUNCTION: nerdtree#compareNodesBySortKey(n1, n2) {{{2 +-function! nerdtree#compareNodesBySortKey(n1, n2) abort +- let sortKey1 = a:n1.path.getSortKey() +- let sortKey2 = a:n2.path.getSortKey() ++"FUNCTION: nerdtree#compareNodePaths(p1, p2) {{{2 ++function! nerdtree#compareNodePaths(p1, p2) abort ++ let sortKey1 = a:p1.getSortKey() ++ let sortKey2 = a:p2.getSortKey() + let i = 0 + while i < min([len(sortKey1), len(sortKey2)]) + " Compare chunks upto common length. +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 21e357b..786ccd9 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -99,50 +99,6 @@ function! s:Path.changeToDir() + endtry + endfunction + +-" FUNCTION: Path.compareTo() {{{1 +-" +-" Compares this Path to the given path and returns 0 if they are equal, -1 if +-" this Path is 'less than' the given path, or 1 if it is 'greater'. +-" +-" Args: +-" path: the path object to compare this to +-" +-" Return: +-" 1, -1 or 0 +-function! s:Path.compareTo(path) +- let thisPath = self.getLastPathComponent(1) +- let thatPath = a:path.getLastPathComponent(1) +- +- "if the paths are the same then clearly we return 0 +- if thisPath ==# thatPath +- return 0 +- endif +- +- let thisSS = self.getSortOrderIndex() +- let thatSS = a:path.getSortOrderIndex() +- +- "compare the sort sequences, if they are different then the return +- "value is easy +- if thisSS < thatSS +- return -1 +- elseif thisSS > thatSS +- return 1 +- else +- if !g:NERDTreeSortHiddenFirst +- let thisPath = substitute(thisPath, '^[._]', '', '') +- let thatPath = substitute(thatPath, '^[._]', '', '') +- endif +- "if the sort sequences are the same then compare the paths +- "alphabetically +- let pathCompare = g:NERDTreeCaseSensitiveSort ? thisPath <# thatPath : thisPath "$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/preservim__nerdtree-1166/tests/verifier.py b/tasks/preservim__nerdtree-1166/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1166/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/preservim__nerdtree-1167/environment/Dockerfile b/tasks/preservim__nerdtree-1167/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d78d2dff24ba32c07cc802e7b7e89a54ea8e5cef --- /dev/null +++ b/tasks/preservim__nerdtree-1167/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 23000acd7f9744667abc840dd10dd07a16e18fc6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 23000acd7f9744667abc840dd10dd07a16e18fc6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 23000acd7f9744667abc840dd10dd07a16e18fc6 \ + && 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/preservim__nerdtree-1167/instruction.md b/tasks/preservim__nerdtree-1167/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b072ec6cd96750f49bedbc11e4b0e417712921b --- /dev/null +++ b/tasks/preservim__nerdtree-1167/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Updated Readme + +## Description + +Fixed typo in readme + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `23000acd7f97`. 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/preservim__nerdtree-1167/solution/patch.diff b/tasks/preservim__nerdtree-1167/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..164ce906605bbaad24b3730d01d851839ec78588 --- /dev/null +++ b/tasks/preservim__nerdtree-1167/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 55806cb..cd16848 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) +diff --git a/README.markdown b/README.markdown +index 09173a6..018923c 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -28,7 +28,7 @@ git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/ner + vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q + ``` + +-Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you nee d to take. ++Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you need to take. + + #### [pathogen.vim](https://github.com/tpope/vim-pathogen) + diff --git a/tasks/preservim__nerdtree-1167/solution/solve.sh b/tasks/preservim__nerdtree-1167/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1167/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/preservim__nerdtree-1167/task.toml b/tasks/preservim__nerdtree-1167/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f52b85222756b2cdee8a50ae7f7532d3a3bc5f7e --- /dev/null +++ b/tasks/preservim__nerdtree-1167/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1167" +description = "Updated Readme" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "23000acd7f9744667abc840dd10dd07a16e18fc6" +reference = "https://github.com/preservim/nerdtree/pull/1167" +source_access = "auto" +built_at = "2026-11-16T16:10:02.399447+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:70dc2f8de5a2f61056d62ea53b244caeb2a07be0c40ae6a8f5eeb916c90bf4f4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-08-18T15:14:06Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", +] +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:02.587878+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e670c3cd06a29f5f8ab49b2ab4245bfe21a4f73c0c521d81dfe5aaa20720bb65" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1167/tests/capture.py b/tasks/preservim__nerdtree-1167/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1167/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/preservim__nerdtree-1167/tests/instruction.md b/tasks/preservim__nerdtree-1167/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b072ec6cd96750f49bedbc11e4b0e417712921b --- /dev/null +++ b/tasks/preservim__nerdtree-1167/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Updated Readme + +## Description + +Fixed typo in readme + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `23000acd7f97`. 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/preservim__nerdtree-1167/tests/oracle.patch b/tasks/preservim__nerdtree-1167/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..164ce906605bbaad24b3730d01d851839ec78588 --- /dev/null +++ b/tasks/preservim__nerdtree-1167/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 55806cb..cd16848 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) + - **.6**: Don't use silent when raising User events (PhilRunninger) [#1164](https://github.com/preservim/nerdtree/pull/1164) +diff --git a/README.markdown b/README.markdown +index 09173a6..018923c 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -28,7 +28,7 @@ git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/ner + vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q + ``` + +-Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you nee d to take. ++Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you need to take. + + #### [pathogen.vim](https://github.com/tpope/vim-pathogen) + diff --git a/tasks/preservim__nerdtree-1167/tests/test.sh b/tasks/preservim__nerdtree-1167/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d0a28f95de8675ca5e83a009a8ea5d8978990f2 --- /dev/null +++ b/tasks/preservim__nerdtree-1167/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 23000acd7f9744667abc840dd10dd07a16e18fc6 > "$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/preservim__nerdtree-1167/tests/verifier.py b/tasks/preservim__nerdtree-1167/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1167/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/preservim__nerdtree-1177/environment/Dockerfile b/tasks/preservim__nerdtree-1177/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b69ba68bfe0f595d380ec18a28f215bee419b6bc --- /dev/null +++ b/tasks/preservim__nerdtree-1177/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 577ddc73f0a1d2fd6166ed3268ab8536111037e0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 577ddc73f0a1d2fd6166ed3268ab8536111037e0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 577ddc73f0a1d2fd6166ed3268ab8536111037e0 \ + && 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/preservim__nerdtree-1177/instruction.md b/tasks/preservim__nerdtree-1177/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b7af3949b62b5d27320fe728b4a080ae28f039b --- /dev/null +++ b/tasks/preservim__nerdtree-1177/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** Open a mirrored NERDTree with correct width + +## Description + +### Description of Changes +. {`lib/nerdtree/creator.vim`} + +When mirroring a NERDTree buffer on another tab, it was being displayed with the default width, even if the original NERDTree window was zoomed (with the Shift+A key). This PR fixes that issue, by restoring the window's size and position after displaying the NERDTree buffer in the tab's new window. + +To recreate the issue: +``` +:let NERDTreeQuitOnOpen=1 +:NERDTree + Shift+A - to zoom the NERDTree window + t - to open a file in a new tab +:NERDTreeMirror - to open the same NERDTree buffer in the new tab +``` + +There was some cleanup done in the PR as well. + +1. An unused variable was removed; it was referenced, but never set anywhere. {`lib/nerdtree/opener.vim`, `lib/nerdtree/ui.vim`} +1. The variable initialization code was updated to use the `get()` function for more direct assignment of values. {`plugin/NERD_tree.vim`} + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `577ddc73f0a1`. 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/preservim__nerdtree-1177/solution/patch.diff b/tasks/preservim__nerdtree-1177/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6b9664a35b4669be2ae8b7795640d333fef29f8a --- /dev/null +++ b/tasks/preservim__nerdtree-1177/solution/patch.diff @@ -0,0 +1,284 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index cd16848..e558036 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 4a98413..b9d45dc 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -172,6 +172,7 @@ function! s:Creator.createMirror() + let t:NERDTreeBufName = bufferName + call self._createTreeWin() + exec 'buffer ' . bufferName ++ call b:NERDTree.ui.restoreScreenState() + if !&hidden + call b:NERDTree.render() + endif +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 6cdd9df..9c62b72 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -174,9 +174,8 @@ function! s:Opener._newSplit() + + "resize the tree window if no other window was open before + if onlyOneWin +- let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize + call nerdtree#exec('wincmd p', 1) +- call nerdtree#exec('silent '. splitMode .' resize '. size, 1) ++ call nerdtree#exec('silent '. splitMode .' resize '. g:NERDTreeWinSize, 1) + call nerdtree#exec('wincmd p', 0) + endif + +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 2ea813c..a481ba4 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -516,8 +516,7 @@ endfunction + " zoom (maximize/minimize) the NERDTree window + function! s:UI.toggleZoom() + if exists('b:NERDTreeZoomed') && b:NERDTreeZoomed +- let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize +- call nerdtree#exec('silent vertical resize '. size, 1) ++ call nerdtree#exec('silent vertical resize '. g:NERDTreeWinSize, 1) + let b:NERDTreeZoomed = 0 + else + call nerdtree#exec('vertical resize '. get(g:, 'NERDTreeWinSizeMax', ''), 1) +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index ca8070d..ef60cca 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -26,141 +26,114 @@ let loaded_nerd_tree = 1 + let s:old_cpo = &cpoptions + set cpoptions&vim + +-"Function: s:initVariable() function {{{2 +-"This function is used to initialise a given variable to a given value. The +-"variable is only initialised if it does not exist prior +-" +-"Args: +-"var: the name of the var to be initialised +-"value: the value to initialise var to +-" +-"Returns: +-"1 if the var is set, 0 otherwise +-function! s:initVariable(var, value) +- if !exists(a:var) +- exec 'let ' . a:var . ' = ' . "'" . substitute(a:value, "'", "''", 'g') . "'" +- return 1 +- endif +- return 0 +-endfunction +- +-"SECTION: Init variable calls and other random constants {{{2 +-call s:initVariable('g:NERDTreeAutoCenter', 1) +-call s:initVariable('g:NERDTreeAutoCenterThreshold', 3) +-call s:initVariable('g:NERDTreeCaseSensitiveSort', 0) +-call s:initVariable('g:NERDTreeNaturalSort', 0) +-call s:initVariable('g:NERDTreeSortHiddenFirst', 1) +-call s:initVariable('g:NERDTreeUseTCD', 0) +-call s:initVariable('g:NERDTreeChDirMode', 0) +-call s:initVariable('g:NERDTreeCreatePrefix', 'silent') +-call s:initVariable('g:NERDTreeMinimalUI', 0) +-call s:initVariable('g:NERDTreeMinimalMenu', 0) +-if !exists('g:NERDTreeIgnore') +- let g:NERDTreeIgnore = ['\~$'] +-endif +-call s:initVariable('g:NERDTreeBookmarksFile', expand('$HOME') . '/.NERDTreeBookmarks') +-call s:initVariable('g:NERDTreeBookmarksSort', 1) +-call s:initVariable('g:NERDTreeHighlightCursorline', 1) +-call s:initVariable('g:NERDTreeHijackNetrw', 1) +-call s:initVariable('g:NERDTreeMarkBookmarks', 1) +-call s:initVariable('g:NERDTreeMouseMode', 1) +-call s:initVariable('g:NERDTreeNotificationThreshold', 100) +-call s:initVariable('g:NERDTreeQuitOnOpen', 0) +-call s:initVariable('g:NERDTreeRespectWildIgnore', 0) +-call s:initVariable('g:NERDTreeShowBookmarks', 0) +-call s:initVariable('g:NERDTreeShowFiles', 1) +-call s:initVariable('g:NERDTreeShowHidden', 0) +-call s:initVariable('g:NERDTreeShowLineNumbers', 0) +-call s:initVariable('g:NERDTreeSortDirs', 1) ++"SECTION: Initialize variable calls and other random constants {{{2 ++let g:NERDTreeAutoCenter = get(g:, 'NERDTreeAutoCenter', 1) ++let g:NERDTreeAutoCenterThreshold = get(g:, 'NERDTreeAutoCenterThreshold', 3) ++let g:NERDTreeCaseSensitiveSort = get(g:, 'NERDTreeCaseSensitiveSort', 0) ++let g:NERDTreeNaturalSort = get(g:, 'NERDTreeNaturalSort', 0) ++let g:NERDTreeSortHiddenFirst = get(g:, 'NERDTreeSortHiddenFirst', 1) ++let g:NERDTreeUseTCD = get(g:, 'NERDTreeUseTCD', 0) ++let g:NERDTreeChDirMode = get(g:, 'NERDTreeChDirMode', 0) ++let g:NERDTreeCreatePrefix = get(g:, 'NERDTreeCreatePrefix', 'silent') ++let g:NERDTreeMinimalUI = get(g:, 'NERDTreeMinimalUI', 0) ++let g:NERDTreeMinimalMenu = get(g:, 'NERDTreeMinimalMenu', 0) ++let g:NERDTreeIgnore = get(g:, 'NERDTreeIgnore', ['\~$']) ++let g:NERDTreeBookmarksFile = get(g:, 'NERDTreeBookmarksFile', expand('$HOME') . '/.NERDTreeBookmarks') ++let g:NERDTreeBookmarksSort = get(g:, 'NERDTreeBookmarksSort', 1) ++let g:NERDTreeHighlightCursorline = get(g:, 'NERDTreeHighlightCursorline', 1) ++let g:NERDTreeHijackNetrw = get(g:, 'NERDTreeHijackNetrw', 1) ++let g:NERDTreeMarkBookmarks = get(g:, 'NERDTreeMarkBookmarks', 1) ++let g:NERDTreeMouseMode = get(g:, 'NERDTreeMouseMode', 1) ++let g:NERDTreeNotificationThreshold = get(g:, 'NERDTreeNotificationThreshold', 100) ++let g:NERDTreeQuitOnOpen = get(g:, 'NERDTreeQuitOnOpen', 0) ++let g:NERDTreeRespectWildIgnore = get(g:, 'NERDTreeRespectWildIgnore', 0) ++let g:NERDTreeShowBookmarks = get(g:, 'NERDTreeShowBookmarks', 0) ++let g:NERDTreeShowFiles = get(g:, 'NERDTreeShowFiles', 1) ++let g:NERDTreeShowHidden = get(g:, 'NERDTreeShowHidden', 0) ++let g:NERDTreeShowLineNumbers = get(g:, 'NERDTreeShowLineNumbers', 0) ++let g:NERDTreeSortDirs = get(g:, 'NERDTreeSortDirs', 1) + + if !nerdtree#runningWindows() && !nerdtree#runningCygwin() +- call s:initVariable('g:NERDTreeDirArrowExpandable', '▸') +- call s:initVariable('g:NERDTreeDirArrowCollapsible', '▾') ++ let g:NERDTreeDirArrowExpandable = get(g:, 'NERDTreeDirArrowExpandable', '▸') ++ let g:NERDTreeDirArrowCollapsible = get(g:, 'NERDTreeDirArrowCollapsible', '▾') + else +- call s:initVariable('g:NERDTreeDirArrowExpandable', '+') +- call s:initVariable('g:NERDTreeDirArrowCollapsible', '~') ++ let g:NERDTreeDirArrowExpandable = get(g:, 'NERDTreeDirArrowExpandable', '+') ++ let g:NERDTreeDirArrowCollapsible = get(g:, 'NERDTreeDirArrowCollapsible', '~') + endif + +-call s:initVariable('g:NERDTreeCascadeOpenSingleChildDir', 1) +-call s:initVariable('g:NERDTreeCascadeSingleChildDir', 1) ++let g:NERDTreeCascadeOpenSingleChildDir = get(g:, 'NERDTreeCascadeOpenSingleChildDir', 1) ++let g:NERDTreeCascadeSingleChildDir = get(g:, 'NERDTreeCascadeSingleChildDir', 1) + +-if !exists('g:NERDTreeSortOrder') +- let g:NERDTreeSortOrder = ['\/$', '*', '\.swp$', '\.bak$', '\~$'] +-endif ++let g:NERDTreeSortOrder = get(g:, 'NERDTreeSortOrder', ['\/$', '*', '\.swp$', '\.bak$', '\~$']) + let g:NERDTreeOldSortOrder = [] + +-call s:initVariable('g:NERDTreeGlyphReadOnly', 'RO') ++let g:NERDTreeGlyphReadOnly = get(g:, 'NERDTreeGlyphReadOnly', 'RO') + + if has('conceal') +- call s:initVariable('g:NERDTreeNodeDelimiter', "\x07") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\x07") + elseif (g:NERDTreeDirArrowExpandable ==# "\u00a0" || g:NERDTreeDirArrowCollapsible ==# "\u00a0") +- call s:initVariable('g:NERDTreeNodeDelimiter', "\u00b7") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\u00b7") + else +- call s:initVariable('g:NERDTreeNodeDelimiter', "\u00a0") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\u00a0") + endif + +-if !exists('g:NERDTreeStatusline') +- +- "the exists() crap here is a hack to stop vim spazzing out when +- "loading a session that was created with an open nerd tree. It spazzes +- "because it doesnt store b:NERDTree(its a b: var, and its a hash) +- let g:NERDTreeStatusline = "%{exists('b:NERDTree')?b:NERDTree.root.path.str():''}" ++"the exists() crap here is a hack to stop vim spazzing out when ++"loading a session that was created with an open nerd tree. It spazzes ++"because it doesnt store b:NERDTree(its a b: var, and its a hash) ++let g:NERDTreeStatusline = get(g:, 'NERDTreeStatusline', "%{exists('b:NERDTree')?b:NERDTree.root.path.str():''}") + +-endif +-call s:initVariable('g:NERDTreeWinPos', 'left') +-call s:initVariable('g:NERDTreeWinSize', 31) ++let g:NERDTreeWinPos = get(g:, 'NERDTreeWinPos', 'left') ++let g:NERDTreeWinSize = get(g:, 'NERDTreeWinSize', 31) + + "init the shell commands that will be used to copy nodes, and remove dir trees +-" + "Note: the space after the command is important + if nerdtree#runningWindows() +- call s:initVariable('g:NERDTreeRemoveDirCmd', 'rmdir /s /q ') +- call s:initVariable('g:NERDTreeCopyDirCmd', 'xcopy /s /e /i /y /q ') +- call s:initVariable('g:NERDTreeCopyFileCmd', 'copy /y ') ++ let g:NERDTreeRemoveDirCmd = get(g:, 'NERDTreeRemoveDirCmd', 'rmdir /s /q ') ++ let g:NERDTreeCopyDirCmd = get(g:, 'NERDTreeCopyDirCmd', 'xcopy /s /e /i /y /q ') ++ let g:NERDTreeCopyFileCmd = get(g:, 'NERDTreeCopyFileCmd', 'copy /y ') + else +- call s:initVariable('g:NERDTreeRemoveDirCmd', 'rm -rf ') +- call s:initVariable('g:NERDTreeCopyCmd', 'cp -r ') ++ let g:NERDTreeRemoveDirCmd = get(g:, 'NERDTreeRemoveDirCmd', 'rm -rf ') ++ let g:NERDTreeCopyCmd = get(g:, 'NERDTreeCopyCmd', 'cp -r ') + endif + +- + "SECTION: Init variable calls for key mappings {{{2 +-call s:initVariable('g:NERDTreeMapCustomOpen', '') +-call s:initVariable('g:NERDTreeMapActivateNode', 'o') +-call s:initVariable('g:NERDTreeMapChangeRoot', 'C') +-call s:initVariable('g:NERDTreeMapChdir', 'cd') +-call s:initVariable('g:NERDTreeMapCloseChildren', 'X') +-call s:initVariable('g:NERDTreeMapCloseDir', 'x') +-call s:initVariable('g:NERDTreeMapDeleteBookmark', 'D') +-call s:initVariable('g:NERDTreeMapMenu', 'm') +-call s:initVariable('g:NERDTreeMapHelp', '?') +-call s:initVariable('g:NERDTreeMapJumpFirstChild', 'K') +-call s:initVariable('g:NERDTreeMapJumpLastChild', 'J') +-call s:initVariable('g:NERDTreeMapJumpNextSibling', '') +-call s:initVariable('g:NERDTreeMapJumpParent', 'p') +-call s:initVariable('g:NERDTreeMapJumpPrevSibling', '') +-call s:initVariable('g:NERDTreeMapJumpRoot', 'P') +-call s:initVariable('g:NERDTreeMapOpenExpl', 'e') +-call s:initVariable('g:NERDTreeMapOpenInTab', 't') +-call s:initVariable('g:NERDTreeMapOpenInTabSilent', 'T') +-call s:initVariable('g:NERDTreeMapOpenRecursively', 'O') +-call s:initVariable('g:NERDTreeMapOpenSplit', 'i') +-call s:initVariable('g:NERDTreeMapOpenVSplit', 's') +-call s:initVariable('g:NERDTreeMapPreview', 'g' . NERDTreeMapActivateNode) +-call s:initVariable('g:NERDTreeMapPreviewSplit', 'g' . NERDTreeMapOpenSplit) +-call s:initVariable('g:NERDTreeMapPreviewVSplit', 'g' . NERDTreeMapOpenVSplit) +-call s:initVariable('g:NERDTreeMapQuit', 'q') +-call s:initVariable('g:NERDTreeMapRefresh', 'r') +-call s:initVariable('g:NERDTreeMapRefreshRoot', 'R') +-call s:initVariable('g:NERDTreeMapToggleBookmarks', 'B') +-call s:initVariable('g:NERDTreeMapToggleFiles', 'F') +-call s:initVariable('g:NERDTreeMapToggleFilters', 'f') +-call s:initVariable('g:NERDTreeMapToggleHidden', 'I') +-call s:initVariable('g:NERDTreeMapToggleZoom', 'A') +-call s:initVariable('g:NERDTreeMapUpdir', 'u') +-call s:initVariable('g:NERDTreeMapUpdirKeepOpen', 'U') +-call s:initVariable('g:NERDTreeMapCWD', 'CD') +-call s:initVariable('g:NERDTreeMenuDown', 'j') +-call s:initVariable('g:NERDTreeMenuUp', 'k') ++let g:NERDTreeMapCustomOpen = get(g:, 'NERDTreeMapCustomOpen', '') ++let g:NERDTreeMapActivateNode = get(g:, 'NERDTreeMapActivateNode', 'o') ++let g:NERDTreeMapChangeRoot = get(g:, 'NERDTreeMapChangeRoot', 'C') ++let g:NERDTreeMapChdir = get(g:, 'NERDTreeMapChdir', 'cd') ++let g:NERDTreeMapCloseChildren = get(g:, 'NERDTreeMapCloseChildren', 'X') ++let g:NERDTreeMapCloseDir = get(g:, 'NERDTreeMapCloseDir', 'x') ++let g:NERDTreeMapDeleteBookmark = get(g:, 'NERDTreeMapDeleteBookmark', 'D') ++let g:NERDTreeMapMenu = get(g:, 'NERDTreeMapMenu', 'm') ++let g:NERDTreeMapHelp = get(g:, 'NERDTreeMapHelp', '?') ++let g:NERDTreeMapJumpFirstChild = get(g:, 'NERDTreeMapJumpFirstChild', 'K') ++let g:NERDTreeMapJumpLastChild = get(g:, 'NERDTreeMapJumpLastChild', 'J') ++let g:NERDTreeMapJumpNextSibling = get(g:, 'NERDTreeMapJumpNextSibling', '') ++let g:NERDTreeMapJumpParent = get(g:, 'NERDTreeMapJumpParent', 'p') ++let g:NERDTreeMapJumpPrevSibling = get(g:, 'NERDTreeMapJumpPrevSibling', '') ++let g:NERDTreeMapJumpRoot = get(g:, 'NERDTreeMapJumpRoot', 'P') ++let g:NERDTreeMapOpenExpl = get(g:, 'NERDTreeMapOpenExpl', 'e') ++let g:NERDTreeMapOpenInTab = get(g:, 'NERDTreeMapOpenInTab', 't') ++let g:NERDTreeMapOpenInTabSilent = get(g:, 'NERDTreeMapOpenInTabSilent', 'T') ++let g:NERDTreeMapOpenRecursively = get(g:, 'NERDTreeMapOpenRecursively', 'O') ++let g:NERDTreeMapOpenSplit = get(g:, 'NERDTreeMapOpenSplit', 'i') ++let g:NERDTreeMapOpenVSplit = get(g:, 'NERDTreeMapOpenVSplit', 's') ++let g:NERDTreeMapPreview = get(g:, 'NERDTreeMapPreview', 'g'.NERDTreeMapActivateNode) ++let g:NERDTreeMapPreviewSplit = get(g:, 'NERDTreeMapPreviewSplit', 'g'.NERDTreeMapOpenSplit) ++let g:NERDTreeMapPreviewVSplit = get(g:, 'NERDTreeMapPreviewVSplit', 'g'.NERDTreeMapOpenVSplit) ++let g:NERDTreeMapQuit = get(g:, 'NERDTreeMapQuit', 'q') ++let g:NERDTreeMapRefresh = get(g:, 'NERDTreeMapRefresh', 'r') ++let g:NERDTreeMapRefreshRoot = get(g:, 'NERDTreeMapRefreshRoot', 'R') ++let g:NERDTreeMapToggleBookmarks = get(g:, 'NERDTreeMapToggleBookmarks', 'B') ++let g:NERDTreeMapToggleFiles = get(g:, 'NERDTreeMapToggleFiles', 'F') ++let g:NERDTreeMapToggleFilters = get(g:, 'NERDTreeMapToggleFilters', 'f') ++let g:NERDTreeMapToggleHidden = get(g:, 'NERDTreeMapToggleHidden', 'I') ++let g:NERDTreeMapToggleZoom = get(g:, 'NERDTreeMapToggleZoom', 'A') ++let g:NERDTreeMapUpdir = get(g:, 'NERDTreeMapUpdir', 'u') ++let g:NERDTreeMapUpdirKeepOpen = get(g:, 'NERDTreeMapUpdirKeepOpen', 'U') ++let g:NERDTreeMapCWD = get(g:, 'NERDTreeMapCWD', 'CD') ++let g:NERDTreeMenuDown = get(g:, 'NERDTreeMenuDown', 'j') ++let g:NERDTreeMenuUp = get(g:, 'NERDTreeMenuUp', 'k') + + "SECTION: Load class files{{{2 + call nerdtree#loadClassFiles() diff --git a/tasks/preservim__nerdtree-1177/solution/solve.sh b/tasks/preservim__nerdtree-1177/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1177/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/preservim__nerdtree-1177/task.toml b/tasks/preservim__nerdtree-1177/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c245432b8ed2d3a5e3d63ce13ae7bf503592dad --- /dev/null +++ b/tasks/preservim__nerdtree-1177/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1177" +description = "Open a mirrored NERDTree with correct width" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "577ddc73f0a1d2fd6166ed3268ab8536111037e0" +reference = "https://github.com/preservim/nerdtree/pull/1177" +source_access = "auto" +built_at = "2026-11-16T16:10:02.389058+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:10878ef6253dc816b7e43f4e2c20d446d70bde1eb2c573db1200f1c0a5ec6279" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-10-14T22:08:19Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/creator.vim", + "lib/nerdtree/opener.vim", + "lib/nerdtree/ui.vim", + "plugin/NERD_tree.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 205 +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:02.588417+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:cb550271e950ebc521525a3a1eed414dfac23692876fbc82e0b74064a5f137a7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1177/tests/capture.py b/tasks/preservim__nerdtree-1177/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1177/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/preservim__nerdtree-1177/tests/instruction.md b/tasks/preservim__nerdtree-1177/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b7af3949b62b5d27320fe728b4a080ae28f039b --- /dev/null +++ b/tasks/preservim__nerdtree-1177/tests/instruction.md @@ -0,0 +1,47 @@ +# Issue + +**Title:** Open a mirrored NERDTree with correct width + +## Description + +### Description of Changes +. {`lib/nerdtree/creator.vim`} + +When mirroring a NERDTree buffer on another tab, it was being displayed with the default width, even if the original NERDTree window was zoomed (with the Shift+A key). This PR fixes that issue, by restoring the window's size and position after displaying the NERDTree buffer in the tab's new window. + +To recreate the issue: +``` +:let NERDTreeQuitOnOpen=1 +:NERDTree + Shift+A - to zoom the NERDTree window + t - to open a file in a new tab +:NERDTreeMirror - to open the same NERDTree buffer in the new tab +``` + +There was some cleanup done in the PR as well. + +1. An unused variable was removed; it was referenced, but never set anywhere. {`lib/nerdtree/opener.vim`, `lib/nerdtree/ui.vim`} +1. The variable initialization code was updated to use the `get()` function for more direct assignment of values. {`plugin/NERD_tree.vim`} + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `577ddc73f0a1`. 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/preservim__nerdtree-1177/tests/oracle.patch b/tasks/preservim__nerdtree-1177/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6b9664a35b4669be2ae8b7795640d333fef29f8a --- /dev/null +++ b/tasks/preservim__nerdtree-1177/tests/oracle.patch @@ -0,0 +1,284 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index cd16848..e558036 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) + - **.7**: Fix argument of `exists()` function calls checking for autocommands. (PhilRunninger) [#1165](https://github.com/preservim/nerdtree/pull/1165) +diff --git a/lib/nerdtree/creator.vim b/lib/nerdtree/creator.vim +index 4a98413..b9d45dc 100644 +--- a/lib/nerdtree/creator.vim ++++ b/lib/nerdtree/creator.vim +@@ -172,6 +172,7 @@ function! s:Creator.createMirror() + let t:NERDTreeBufName = bufferName + call self._createTreeWin() + exec 'buffer ' . bufferName ++ call b:NERDTree.ui.restoreScreenState() + if !&hidden + call b:NERDTree.render() + endif +diff --git a/lib/nerdtree/opener.vim b/lib/nerdtree/opener.vim +index 6cdd9df..9c62b72 100644 +--- a/lib/nerdtree/opener.vim ++++ b/lib/nerdtree/opener.vim +@@ -174,9 +174,8 @@ function! s:Opener._newSplit() + + "resize the tree window if no other window was open before + if onlyOneWin +- let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize + call nerdtree#exec('wincmd p', 1) +- call nerdtree#exec('silent '. splitMode .' resize '. size, 1) ++ call nerdtree#exec('silent '. splitMode .' resize '. g:NERDTreeWinSize, 1) + call nerdtree#exec('wincmd p', 0) + endif + +diff --git a/lib/nerdtree/ui.vim b/lib/nerdtree/ui.vim +index 2ea813c..a481ba4 100644 +--- a/lib/nerdtree/ui.vim ++++ b/lib/nerdtree/ui.vim +@@ -516,8 +516,7 @@ endfunction + " zoom (maximize/minimize) the NERDTree window + function! s:UI.toggleZoom() + if exists('b:NERDTreeZoomed') && b:NERDTreeZoomed +- let size = exists('b:NERDTreeOldWindowSize') ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize +- call nerdtree#exec('silent vertical resize '. size, 1) ++ call nerdtree#exec('silent vertical resize '. g:NERDTreeWinSize, 1) + let b:NERDTreeZoomed = 0 + else + call nerdtree#exec('vertical resize '. get(g:, 'NERDTreeWinSizeMax', ''), 1) +diff --git a/plugin/NERD_tree.vim b/plugin/NERD_tree.vim +index ca8070d..ef60cca 100644 +--- a/plugin/NERD_tree.vim ++++ b/plugin/NERD_tree.vim +@@ -26,141 +26,114 @@ let loaded_nerd_tree = 1 + let s:old_cpo = &cpoptions + set cpoptions&vim + +-"Function: s:initVariable() function {{{2 +-"This function is used to initialise a given variable to a given value. The +-"variable is only initialised if it does not exist prior +-" +-"Args: +-"var: the name of the var to be initialised +-"value: the value to initialise var to +-" +-"Returns: +-"1 if the var is set, 0 otherwise +-function! s:initVariable(var, value) +- if !exists(a:var) +- exec 'let ' . a:var . ' = ' . "'" . substitute(a:value, "'", "''", 'g') . "'" +- return 1 +- endif +- return 0 +-endfunction +- +-"SECTION: Init variable calls and other random constants {{{2 +-call s:initVariable('g:NERDTreeAutoCenter', 1) +-call s:initVariable('g:NERDTreeAutoCenterThreshold', 3) +-call s:initVariable('g:NERDTreeCaseSensitiveSort', 0) +-call s:initVariable('g:NERDTreeNaturalSort', 0) +-call s:initVariable('g:NERDTreeSortHiddenFirst', 1) +-call s:initVariable('g:NERDTreeUseTCD', 0) +-call s:initVariable('g:NERDTreeChDirMode', 0) +-call s:initVariable('g:NERDTreeCreatePrefix', 'silent') +-call s:initVariable('g:NERDTreeMinimalUI', 0) +-call s:initVariable('g:NERDTreeMinimalMenu', 0) +-if !exists('g:NERDTreeIgnore') +- let g:NERDTreeIgnore = ['\~$'] +-endif +-call s:initVariable('g:NERDTreeBookmarksFile', expand('$HOME') . '/.NERDTreeBookmarks') +-call s:initVariable('g:NERDTreeBookmarksSort', 1) +-call s:initVariable('g:NERDTreeHighlightCursorline', 1) +-call s:initVariable('g:NERDTreeHijackNetrw', 1) +-call s:initVariable('g:NERDTreeMarkBookmarks', 1) +-call s:initVariable('g:NERDTreeMouseMode', 1) +-call s:initVariable('g:NERDTreeNotificationThreshold', 100) +-call s:initVariable('g:NERDTreeQuitOnOpen', 0) +-call s:initVariable('g:NERDTreeRespectWildIgnore', 0) +-call s:initVariable('g:NERDTreeShowBookmarks', 0) +-call s:initVariable('g:NERDTreeShowFiles', 1) +-call s:initVariable('g:NERDTreeShowHidden', 0) +-call s:initVariable('g:NERDTreeShowLineNumbers', 0) +-call s:initVariable('g:NERDTreeSortDirs', 1) ++"SECTION: Initialize variable calls and other random constants {{{2 ++let g:NERDTreeAutoCenter = get(g:, 'NERDTreeAutoCenter', 1) ++let g:NERDTreeAutoCenterThreshold = get(g:, 'NERDTreeAutoCenterThreshold', 3) ++let g:NERDTreeCaseSensitiveSort = get(g:, 'NERDTreeCaseSensitiveSort', 0) ++let g:NERDTreeNaturalSort = get(g:, 'NERDTreeNaturalSort', 0) ++let g:NERDTreeSortHiddenFirst = get(g:, 'NERDTreeSortHiddenFirst', 1) ++let g:NERDTreeUseTCD = get(g:, 'NERDTreeUseTCD', 0) ++let g:NERDTreeChDirMode = get(g:, 'NERDTreeChDirMode', 0) ++let g:NERDTreeCreatePrefix = get(g:, 'NERDTreeCreatePrefix', 'silent') ++let g:NERDTreeMinimalUI = get(g:, 'NERDTreeMinimalUI', 0) ++let g:NERDTreeMinimalMenu = get(g:, 'NERDTreeMinimalMenu', 0) ++let g:NERDTreeIgnore = get(g:, 'NERDTreeIgnore', ['\~$']) ++let g:NERDTreeBookmarksFile = get(g:, 'NERDTreeBookmarksFile', expand('$HOME') . '/.NERDTreeBookmarks') ++let g:NERDTreeBookmarksSort = get(g:, 'NERDTreeBookmarksSort', 1) ++let g:NERDTreeHighlightCursorline = get(g:, 'NERDTreeHighlightCursorline', 1) ++let g:NERDTreeHijackNetrw = get(g:, 'NERDTreeHijackNetrw', 1) ++let g:NERDTreeMarkBookmarks = get(g:, 'NERDTreeMarkBookmarks', 1) ++let g:NERDTreeMouseMode = get(g:, 'NERDTreeMouseMode', 1) ++let g:NERDTreeNotificationThreshold = get(g:, 'NERDTreeNotificationThreshold', 100) ++let g:NERDTreeQuitOnOpen = get(g:, 'NERDTreeQuitOnOpen', 0) ++let g:NERDTreeRespectWildIgnore = get(g:, 'NERDTreeRespectWildIgnore', 0) ++let g:NERDTreeShowBookmarks = get(g:, 'NERDTreeShowBookmarks', 0) ++let g:NERDTreeShowFiles = get(g:, 'NERDTreeShowFiles', 1) ++let g:NERDTreeShowHidden = get(g:, 'NERDTreeShowHidden', 0) ++let g:NERDTreeShowLineNumbers = get(g:, 'NERDTreeShowLineNumbers', 0) ++let g:NERDTreeSortDirs = get(g:, 'NERDTreeSortDirs', 1) + + if !nerdtree#runningWindows() && !nerdtree#runningCygwin() +- call s:initVariable('g:NERDTreeDirArrowExpandable', '▸') +- call s:initVariable('g:NERDTreeDirArrowCollapsible', '▾') ++ let g:NERDTreeDirArrowExpandable = get(g:, 'NERDTreeDirArrowExpandable', '▸') ++ let g:NERDTreeDirArrowCollapsible = get(g:, 'NERDTreeDirArrowCollapsible', '▾') + else +- call s:initVariable('g:NERDTreeDirArrowExpandable', '+') +- call s:initVariable('g:NERDTreeDirArrowCollapsible', '~') ++ let g:NERDTreeDirArrowExpandable = get(g:, 'NERDTreeDirArrowExpandable', '+') ++ let g:NERDTreeDirArrowCollapsible = get(g:, 'NERDTreeDirArrowCollapsible', '~') + endif + +-call s:initVariable('g:NERDTreeCascadeOpenSingleChildDir', 1) +-call s:initVariable('g:NERDTreeCascadeSingleChildDir', 1) ++let g:NERDTreeCascadeOpenSingleChildDir = get(g:, 'NERDTreeCascadeOpenSingleChildDir', 1) ++let g:NERDTreeCascadeSingleChildDir = get(g:, 'NERDTreeCascadeSingleChildDir', 1) + +-if !exists('g:NERDTreeSortOrder') +- let g:NERDTreeSortOrder = ['\/$', '*', '\.swp$', '\.bak$', '\~$'] +-endif ++let g:NERDTreeSortOrder = get(g:, 'NERDTreeSortOrder', ['\/$', '*', '\.swp$', '\.bak$', '\~$']) + let g:NERDTreeOldSortOrder = [] + +-call s:initVariable('g:NERDTreeGlyphReadOnly', 'RO') ++let g:NERDTreeGlyphReadOnly = get(g:, 'NERDTreeGlyphReadOnly', 'RO') + + if has('conceal') +- call s:initVariable('g:NERDTreeNodeDelimiter', "\x07") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\x07") + elseif (g:NERDTreeDirArrowExpandable ==# "\u00a0" || g:NERDTreeDirArrowCollapsible ==# "\u00a0") +- call s:initVariable('g:NERDTreeNodeDelimiter', "\u00b7") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\u00b7") + else +- call s:initVariable('g:NERDTreeNodeDelimiter', "\u00a0") ++ let g:NERDTreeNodeDelimiter = get(g:, 'NERDTreeNodeDelimiter', "\u00a0") + endif + +-if !exists('g:NERDTreeStatusline') +- +- "the exists() crap here is a hack to stop vim spazzing out when +- "loading a session that was created with an open nerd tree. It spazzes +- "because it doesnt store b:NERDTree(its a b: var, and its a hash) +- let g:NERDTreeStatusline = "%{exists('b:NERDTree')?b:NERDTree.root.path.str():''}" ++"the exists() crap here is a hack to stop vim spazzing out when ++"loading a session that was created with an open nerd tree. It spazzes ++"because it doesnt store b:NERDTree(its a b: var, and its a hash) ++let g:NERDTreeStatusline = get(g:, 'NERDTreeStatusline', "%{exists('b:NERDTree')?b:NERDTree.root.path.str():''}") + +-endif +-call s:initVariable('g:NERDTreeWinPos', 'left') +-call s:initVariable('g:NERDTreeWinSize', 31) ++let g:NERDTreeWinPos = get(g:, 'NERDTreeWinPos', 'left') ++let g:NERDTreeWinSize = get(g:, 'NERDTreeWinSize', 31) + + "init the shell commands that will be used to copy nodes, and remove dir trees +-" + "Note: the space after the command is important + if nerdtree#runningWindows() +- call s:initVariable('g:NERDTreeRemoveDirCmd', 'rmdir /s /q ') +- call s:initVariable('g:NERDTreeCopyDirCmd', 'xcopy /s /e /i /y /q ') +- call s:initVariable('g:NERDTreeCopyFileCmd', 'copy /y ') ++ let g:NERDTreeRemoveDirCmd = get(g:, 'NERDTreeRemoveDirCmd', 'rmdir /s /q ') ++ let g:NERDTreeCopyDirCmd = get(g:, 'NERDTreeCopyDirCmd', 'xcopy /s /e /i /y /q ') ++ let g:NERDTreeCopyFileCmd = get(g:, 'NERDTreeCopyFileCmd', 'copy /y ') + else +- call s:initVariable('g:NERDTreeRemoveDirCmd', 'rm -rf ') +- call s:initVariable('g:NERDTreeCopyCmd', 'cp -r ') ++ let g:NERDTreeRemoveDirCmd = get(g:, 'NERDTreeRemoveDirCmd', 'rm -rf ') ++ let g:NERDTreeCopyCmd = get(g:, 'NERDTreeCopyCmd', 'cp -r ') + endif + +- + "SECTION: Init variable calls for key mappings {{{2 +-call s:initVariable('g:NERDTreeMapCustomOpen', '') +-call s:initVariable('g:NERDTreeMapActivateNode', 'o') +-call s:initVariable('g:NERDTreeMapChangeRoot', 'C') +-call s:initVariable('g:NERDTreeMapChdir', 'cd') +-call s:initVariable('g:NERDTreeMapCloseChildren', 'X') +-call s:initVariable('g:NERDTreeMapCloseDir', 'x') +-call s:initVariable('g:NERDTreeMapDeleteBookmark', 'D') +-call s:initVariable('g:NERDTreeMapMenu', 'm') +-call s:initVariable('g:NERDTreeMapHelp', '?') +-call s:initVariable('g:NERDTreeMapJumpFirstChild', 'K') +-call s:initVariable('g:NERDTreeMapJumpLastChild', 'J') +-call s:initVariable('g:NERDTreeMapJumpNextSibling', '') +-call s:initVariable('g:NERDTreeMapJumpParent', 'p') +-call s:initVariable('g:NERDTreeMapJumpPrevSibling', '') +-call s:initVariable('g:NERDTreeMapJumpRoot', 'P') +-call s:initVariable('g:NERDTreeMapOpenExpl', 'e') +-call s:initVariable('g:NERDTreeMapOpenInTab', 't') +-call s:initVariable('g:NERDTreeMapOpenInTabSilent', 'T') +-call s:initVariable('g:NERDTreeMapOpenRecursively', 'O') +-call s:initVariable('g:NERDTreeMapOpenSplit', 'i') +-call s:initVariable('g:NERDTreeMapOpenVSplit', 's') +-call s:initVariable('g:NERDTreeMapPreview', 'g' . NERDTreeMapActivateNode) +-call s:initVariable('g:NERDTreeMapPreviewSplit', 'g' . NERDTreeMapOpenSplit) +-call s:initVariable('g:NERDTreeMapPreviewVSplit', 'g' . NERDTreeMapOpenVSplit) +-call s:initVariable('g:NERDTreeMapQuit', 'q') +-call s:initVariable('g:NERDTreeMapRefresh', 'r') +-call s:initVariable('g:NERDTreeMapRefreshRoot', 'R') +-call s:initVariable('g:NERDTreeMapToggleBookmarks', 'B') +-call s:initVariable('g:NERDTreeMapToggleFiles', 'F') +-call s:initVariable('g:NERDTreeMapToggleFilters', 'f') +-call s:initVariable('g:NERDTreeMapToggleHidden', 'I') +-call s:initVariable('g:NERDTreeMapToggleZoom', 'A') +-call s:initVariable('g:NERDTreeMapUpdir', 'u') +-call s:initVariable('g:NERDTreeMapUpdirKeepOpen', 'U') +-call s:initVariable('g:NERDTreeMapCWD', 'CD') +-call s:initVariable('g:NERDTreeMenuDown', 'j') +-call s:initVariable('g:NERDTreeMenuUp', 'k') ++let g:NERDTreeMapCustomOpen = get(g:, 'NERDTreeMapCustomOpen', '') ++let g:NERDTreeMapActivateNode = get(g:, 'NERDTreeMapActivateNode', 'o') ++let g:NERDTreeMapChangeRoot = get(g:, 'NERDTreeMapChangeRoot', 'C') ++let g:NERDTreeMapChdir = get(g:, 'NERDTreeMapChdir', 'cd') ++let g:NERDTreeMapCloseChildren = get(g:, 'NERDTreeMapCloseChildren', 'X') ++let g:NERDTreeMapCloseDir = get(g:, 'NERDTreeMapCloseDir', 'x') ++let g:NERDTreeMapDeleteBookmark = get(g:, 'NERDTreeMapDeleteBookmark', 'D') ++let g:NERDTreeMapMenu = get(g:, 'NERDTreeMapMenu', 'm') ++let g:NERDTreeMapHelp = get(g:, 'NERDTreeMapHelp', '?') ++let g:NERDTreeMapJumpFirstChild = get(g:, 'NERDTreeMapJumpFirstChild', 'K') ++let g:NERDTreeMapJumpLastChild = get(g:, 'NERDTreeMapJumpLastChild', 'J') ++let g:NERDTreeMapJumpNextSibling = get(g:, 'NERDTreeMapJumpNextSibling', '') ++let g:NERDTreeMapJumpParent = get(g:, 'NERDTreeMapJumpParent', 'p') ++let g:NERDTreeMapJumpPrevSibling = get(g:, 'NERDTreeMapJumpPrevSibling', '') ++let g:NERDTreeMapJumpRoot = get(g:, 'NERDTreeMapJumpRoot', 'P') ++let g:NERDTreeMapOpenExpl = get(g:, 'NERDTreeMapOpenExpl', 'e') ++let g:NERDTreeMapOpenInTab = get(g:, 'NERDTreeMapOpenInTab', 't') ++let g:NERDTreeMapOpenInTabSilent = get(g:, 'NERDTreeMapOpenInTabSilent', 'T') ++let g:NERDTreeMapOpenRecursively = get(g:, 'NERDTreeMapOpenRecursively', 'O') ++let g:NERDTreeMapOpenSplit = get(g:, 'NERDTreeMapOpenSplit', 'i') ++let g:NERDTreeMapOpenVSplit = get(g:, 'NERDTreeMapOpenVSplit', 's') ++let g:NERDTreeMapPreview = get(g:, 'NERDTreeMapPreview', 'g'.NERDTreeMapActivateNode) ++let g:NERDTreeMapPreviewSplit = get(g:, 'NERDTreeMapPreviewSplit', 'g'.NERDTreeMapOpenSplit) ++let g:NERDTreeMapPreviewVSplit = get(g:, 'NERDTreeMapPreviewVSplit', 'g'.NERDTreeMapOpenVSplit) ++let g:NERDTreeMapQuit = get(g:, 'NERDTreeMapQuit', 'q') ++let g:NERDTreeMapRefresh = get(g:, 'NERDTreeMapRefresh', 'r') ++let g:NERDTreeMapRefreshRoot = get(g:, 'NERDTreeMapRefreshRoot', 'R') ++let g:NERDTreeMapToggleBookmarks = get(g:, 'NERDTreeMapToggleBookmarks', 'B') ++let g:NERDTreeMapToggleFiles = get(g:, 'NERDTreeMapToggleFiles', 'F') ++let g:NERDTreeMapToggleFilters = get(g:, 'NERDTreeMapToggleFilters', 'f') ++let g:NERDTreeMapToggleHidden = get(g:, 'NERDTreeMapToggleHidden', 'I') ++let g:NERDTreeMapToggleZoom = get(g:, 'NERDTreeMapToggleZoom', 'A') ++let g:NERDTreeMapUpdir = get(g:, 'NERDTreeMapUpdir', 'u') ++let g:NERDTreeMapUpdirKeepOpen = get(g:, 'NERDTreeMapUpdirKeepOpen', 'U') ++let g:NERDTreeMapCWD = get(g:, 'NERDTreeMapCWD', 'CD') ++let g:NERDTreeMenuDown = get(g:, 'NERDTreeMenuDown', 'j') ++let g:NERDTreeMenuUp = get(g:, 'NERDTreeMenuUp', 'k') + + "SECTION: Load class files{{{2 + call nerdtree#loadClassFiles() diff --git a/tasks/preservim__nerdtree-1177/tests/test.sh b/tasks/preservim__nerdtree-1177/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..04ee80c3ee4f9a98d3949508780607f4874854bf --- /dev/null +++ b/tasks/preservim__nerdtree-1177/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 577ddc73f0a1d2fd6166ed3268ab8536111037e0 > "$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/preservim__nerdtree-1177/tests/verifier.py b/tasks/preservim__nerdtree-1177/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1177/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/preservim__nerdtree-1192/environment/Dockerfile b/tasks/preservim__nerdtree-1192/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a45cc1ff71c7ccef40adc286a739977190ec5399 --- /dev/null +++ b/tasks/preservim__nerdtree-1192/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 14af89743ac1c31ff9bb43682025eda50333a7d5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 14af89743ac1c31ff9bb43682025eda50333a7d5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 14af89743ac1c31ff9bb43682025eda50333a7d5 \ + && 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/preservim__nerdtree-1192/instruction.md b/tasks/preservim__nerdtree-1192/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f385ba3fc077e41dedee93008469be9cf5ff1e60 --- /dev/null +++ b/tasks/preservim__nerdtree-1192/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** readme update add script for automatically open NERDTree and focus on file + +## Description + +### Description of Changes +update readme add script for automatically open NERDTree and focus on file + + +--- +### New Version Info + +#### Author's Instructions +- [ ] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [ ] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [ ] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [ ] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `14af89743ac1`. 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/preservim__nerdtree-1192/solution/patch.diff b/tasks/preservim__nerdtree-1192/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5a90e2ea6b7e0e08fad04d23f43519cb8e6346de --- /dev/null +++ b/tasks/preservim__nerdtree-1192/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/README.markdown b/README.markdown +index 018923c..da87fbc 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -92,6 +92,11 @@ If you are interested in this behaviour then consider [vim-nerdtree-tabs](https: + + Stick this in your vimrc: `autocmd vimenter * NERDTree` + ++--- ++#### How can I open a NERDTree automatically when vim starts up and autofocus on file? ++ ++Stick this in your vimrc: `autocmd vimenter * NERDTree | wincmd p` ++ + --- + #### How can I open a NERDTree automatically when vim starts up if no files were specified? + +@@ -103,6 +108,15 @@ autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif + + Note: Now start vim with plain `vim`, not `vim .` + ++--- ++#### How to autofocus on file and focus on NERDTREE when no files were specified? ++ ++Stick this in your vimrc: ++```vim ++autocmd StdinReadPre * let s:std_in=1 ++autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | else | NERDTree | wincmd p | endif ++``` ++ + --- + #### What if I'm also opening a saved session, for example `vim -S session_file.vim`? I don't want NERDTree to open in that scenario. + ```vim diff --git a/tasks/preservim__nerdtree-1192/solution/solve.sh b/tasks/preservim__nerdtree-1192/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1192/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/preservim__nerdtree-1192/task.toml b/tasks/preservim__nerdtree-1192/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b078220d71a35e6485df109e6fddba62aa46d95b --- /dev/null +++ b/tasks/preservim__nerdtree-1192/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1192" +description = "readme update add script for automatically open NERDTree and focus on file" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "14af89743ac1c31ff9bb43682025eda50333a7d5" +reference = "https://github.com/preservim/nerdtree/pull/1192" +source_access = "auto" +built_at = "2026-11-16T16:10:02.396016+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:84b0cb5a3022141240b2ea9b863590e4993ed4a6d5aa0c298f661a996aa2b138" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-12-18T05:36:10Z" +diff_format = "unified" +context_files = [ + "README.markdown", +] +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:02.588997+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9b6d4c807d7705d769cd6e7e5d51177c8bb455414290cef06837c480eb4dac78" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1192/tests/capture.py b/tasks/preservim__nerdtree-1192/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1192/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/preservim__nerdtree-1192/tests/instruction.md b/tasks/preservim__nerdtree-1192/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f385ba3fc077e41dedee93008469be9cf5ff1e60 --- /dev/null +++ b/tasks/preservim__nerdtree-1192/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** readme update add script for automatically open NERDTree and focus on file + +## Description + +### Description of Changes +update readme add script for automatically open NERDTree and focus on file + + +--- +### New Version Info + +#### Author's Instructions +- [ ] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [ ] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [ ] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [ ] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `14af89743ac1`. 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/preservim__nerdtree-1192/tests/oracle.patch b/tasks/preservim__nerdtree-1192/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5a90e2ea6b7e0e08fad04d23f43519cb8e6346de --- /dev/null +++ b/tasks/preservim__nerdtree-1192/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/README.markdown b/README.markdown +index 018923c..da87fbc 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -92,6 +92,11 @@ If you are interested in this behaviour then consider [vim-nerdtree-tabs](https: + + Stick this in your vimrc: `autocmd vimenter * NERDTree` + ++--- ++#### How can I open a NERDTree automatically when vim starts up and autofocus on file? ++ ++Stick this in your vimrc: `autocmd vimenter * NERDTree | wincmd p` ++ + --- + #### How can I open a NERDTree automatically when vim starts up if no files were specified? + +@@ -103,6 +108,15 @@ autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif + + Note: Now start vim with plain `vim`, not `vim .` + ++--- ++#### How to autofocus on file and focus on NERDTREE when no files were specified? ++ ++Stick this in your vimrc: ++```vim ++autocmd StdinReadPre * let s:std_in=1 ++autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | else | NERDTree | wincmd p | endif ++``` ++ + --- + #### What if I'm also opening a saved session, for example `vim -S session_file.vim`? I don't want NERDTree to open in that scenario. + ```vim diff --git a/tasks/preservim__nerdtree-1192/tests/test.sh b/tasks/preservim__nerdtree-1192/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3036a6fdb73051be194c924ae687e09a4238c1f9 --- /dev/null +++ b/tasks/preservim__nerdtree-1192/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 14af89743ac1c31ff9bb43682025eda50333a7d5 > "$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/preservim__nerdtree-1192/tests/verifier.py b/tasks/preservim__nerdtree-1192/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1192/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/preservim__nerdtree-1193/environment/Dockerfile b/tasks/preservim__nerdtree-1193/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f0235c18f410f4e08d2628d4e574b1e4d9497655 --- /dev/null +++ b/tasks/preservim__nerdtree-1193/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 474d735b7d68a315e1f426920f9aa7391369b606 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 474d735b7d68a315e1f426920f9aa7391369b606 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 474d735b7d68a315e1f426920f9aa7391369b606 \ + && 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/preservim__nerdtree-1193/instruction.md b/tasks/preservim__nerdtree-1193/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f43012f8264b19fcb320bd13138bbe9a1744ecde --- /dev/null +++ b/tasks/preservim__nerdtree-1193/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Revamp the README file + +## Description + +### Description of Changes +This file was in desperate need of being rewritten, so I did. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `474d735b7d68`. 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/preservim__nerdtree-1193/solution/patch.diff b/tasks/preservim__nerdtree-1193/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..92a017b27ceef1627e897b20402be4c9155c397f --- /dev/null +++ b/tasks/preservim__nerdtree-1193/solution/patch.diff @@ -0,0 +1,298 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e558036..d9c1b45 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) + - **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) +diff --git a/README.markdown b/README.markdown +index da87fbc..a3a62c1 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -1,171 +1,173 @@ +-The NERDTree [![Vint](https://github.com/preservim/nerdtree/workflows/Vint/badge.svg)](https://github.com/preservim/nerdtree/actions?workflow=Vint) +-============= ++# The NERDTree [![Vint](https://github.com/preservim/nerdtree/workflows/Vint/badge.svg)](https://github.com/preservim/nerdtree/actions?workflow=Vint) + +-Introduction +------------- ++## Introduction + +-The NERDTree is a file system explorer for the Vim editor. Using this plugin, +-users can visually browse complex directory hierarchies, quickly open files for +-reading or editing, and perform basic file system operations. +- +-This plugin can also be extended with custom mappings using a special API. The +-details of this API and of other NERDTree features are described in the +-included documentation. ++The NERDTree is a file system explorer for the Vim editor. Using this plugin, users can visually browse complex directory hierarchies, quickly open files for reading or editing, and perform basic file system operations. + + ![NERDTree Screenshot](https://github.com/preservim/nerdtree/raw/master/screenshot.png) + +-Installation +------------- +- +-Below are just some of the methods for installing NERDTree. Do not follow all of these instructions; just pick your favorite one. Other plugin managers exist, and NERDTree should install just fine with any of them. ++## Installation + +-#### Vim 8+ packages ++Use your favorite plugin manager to install this plugin. [tpope/vim-pathogen](https://github.com/tpope/vim-pathogen), [VundleVimVundle.vim](https://github.com/VundleVim/Vundle.vim), [junegunnvim-plug](https://github.com/junegunn/vim-plug), and [Shougo/dein.vim](https://github.com/Shougo/dein.vim) are some of the more popular ones. A lengthy discussion of these and other managers can be found on [vi.stackexchange.com](https://vi.stackexchange.com/questions/388/what-is-the-difference-between-the-vim-plugin-managers). Basic instructions are provided below, but please **be sure to read, understand, and follow all the safety rules that come with your ~~power tools~~ plugin manager.** + +-If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: ++If you have no favorite, or want to manage your plugins without 3rd-party dependencies, consider using Vim 8+ packages, as described in Greg Hurrell's excellent Youtube video: [Vim screencast #75: Plugin managers](https://www.youtube.com/watch?v=X2_R3uxDN6g). + +-```bash +-git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree +-vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q +-``` ++
++Pathogen ++Pathogen is more of a runtime path manager than a plugin manager. You must clone the plugins' repositories yourself to a specific location, and Pathogen makes sure they are available in Vim. + +-Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you need to take. + +-#### [pathogen.vim](https://github.com/tpope/vim-pathogen) ++1. In the terminal, ++ ```bash ++ git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree ++ ``` ++1. In your `vimrc`, ++ ```vim ++ call pathogen#infect() ++ syntax on ++ filetype plugin indent on ++ ``` ++1. Restart Vim, and run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. ++
+ +-In the terminal, +-```bash +-git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree +-``` +-In your vimrc, +-```vim +-call pathogen#infect() +-syntax on +-filetype plugin indent on +-``` ++
++ Vundle + +-Then reload vim, run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. ++1. Install Vundle, according to its instructions. ++1. Add the following text to your `vimrc`. ++ ```vim ++ call vundle#begin() ++ Plugin 'preservim/nerdtree' ++ call vundle#end() ++ ``` ++1. Restart Vim, and run the `:PluginInstall` statement to install your plugins. ++
+ +-#### [Vundle.vim](https://github.com/VundleVim/Vundle.vim) +-```vim +-call vundle#begin() +-Plugin 'preservim/nerdtree' +-call vundle#end() +-``` ++
++ Vim-Plug + +-#### [vim-plug](https://github.com/junegunn/vim-plug) ++1. Install Vim-Plug, according to its instructions. ++1. Add the following text to your `vimrc`. + ```vim + call plug#begin() +-Plug 'preservim/nerdtree' ++ Plug 'preservim/nerdtree' + call plug#end() + ``` ++1. Restart Vim, and run the `:PlugInstall` statement to install your plugins. ++
+ +-#### [dein.vim](https://github.com/Shougo/dein.vim) +-```vim +-call dein#begin() +-call dein#add('preservim/nerdtree') +-call dein#end() +-``` ++
++ Dein + +-#### [apt-vim](https://github.com/egalpin/apt-vim) +-```bash +-apt-vim install -y https://github.com/preservim/nerdtree.git +-``` ++1. Install Dein, according to its instructions. ++1. Add the following text to your `vimrc`. ++ ```vim ++ call dein#begin() ++ call dein#add('preservim/nerdtree') ++ call dein#end() ++ ``` ++1. Restart Vim, and run the `:call dein#install()` statement to install your plugins. ++
+ +-F.A.Q. (here, and in the [Wiki](https://github.com/preservim/nerdtree/wiki)) +------- ++
++Vim 8+ packages + +-#### Is there any support for `git` flags? ++If you are using Vim version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: + +-Yes, install [nerdtree-git-plugin](https://github.com/Xuyuanp/nerdtree-git-plugin). ++```bash ++git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q ++``` ++
+ +---- +-#### Can I have the nerdtree on every tab automatically? ++## Getting Started ++After installing NERDTree, the best way to learn it is to turn on the Quick Help. Open NERDTree with the `:NERDTree` command, and press `?` to turn on the Quick Help, which will show you all the mappings and commands available in the NERDTree. Of course, your most complete source of information is the documentation: `:help NERDTree`. + +-Nope. If this is something you want then chances are you aren't using tabs and +-buffers as they were intended to be used. Read this +-http://stackoverflow.com/questions/102384/using-vims-tabs-like-buffers ++## NERDTree Plugins ++NERDTree can be extended with custom mappings and functions using its built-in API. The details of this API and are described in the included documentation. Several plugins have been written, and are available on Github for installation like any other plugin. The plugins in this list are maintained (or not) by their respective owners, and certain combinations may be incompatible. + +-If you are interested in this behaviour then consider [vim-nerdtree-tabs](https://github.com/jistr/vim-nerdtree-tabs) ++* [Xuyuanp/nerdtree-git-plugin](https://github.com/Xuyuanp/nerdtree-git-plugin): Shows Git status flags for files and folders in NERDTree. ++* [ryanoasis/vim-devicons](https://github.com/ryanoasis/vim-devicons): Adds filetype-specific icons to NERDTree files and folders, ++* [tiagofumo/vim-nerdtree-syntax-highlight](https://github.com/tiagofumo/vim-nerdtree-syntax-highlight): Adds syntax highlighting to NERDTree based on filetype. ++* [scrooloose/nerdtree-project-plugin](https://github.com/scrooloose/nerdtree-project-plugin): Saves and restores the state of the NERDTree between sessions. ++* [PhilRunninger/nerdtree-buffer-ops](https://github.com/PhilRunninger/nerdtree-buffer-ops): 1) Highlights open files in a different color. 2) Closes a buffer directly from NERDTree. ++* [PhilRunninger/nerdtree-visual-selection](https://github.com/PhilRunninger/nerdtree-visual-selection): Enables NERDTree to open, delete, move, or copy multiple Visually-selected files at once. + +---- +-#### How can I open a NERDTree automatically when vim starts up? ++If any others should be listed, mention them in an issue or pull request. + +-Stick this in your vimrc: `autocmd vimenter * NERDTree` + +---- +-#### How can I open a NERDTree automatically when vim starts up and autofocus on file? ++## Frequently Asked Questions + +-Stick this in your vimrc: `autocmd vimenter * NERDTree | wincmd p` ++In the answers to these questions, you will see code blocks that you can put in your `vimrc` file. + +---- +-#### How can I open a NERDTree automatically when vim starts up if no files were specified? ++### How can I map a specific key or shortcut to open NERDTree? + +-Stick this in your vimrc: ++NERDTree doesn't create any shortcuts outside of the NERDTree window, so as not to overwrite any of your other shortcuts. Use the `nnoremap` command in your `vimrc`. You, of course, have many keys and NERDTree commands to choose from. Here are but a few examples. + ```vim +-autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif ++nnoremap n :NERDTreeFocus ++nnoremap :NERDTree ++nnoremap :NERDTreeToggle ++nnoremap :NERDTreeFind + ``` + +-Note: Now start vim with plain `vim`, not `vim .` ++### How do I open NERDTree automatically when Vim starts? ++Each code block below is slightly different, as described in the `" Comment lines`. + ++```vim ++" Start NERDTree and leave the cursor in it. ++autocmd VimEnter * NERDTree ++``` ++--- ++```vim ++" Start NERDTree and put the cursor back in the other window. ++autocmd VimEnter * NERDTree | wincmd p ++``` + --- +-#### How to autofocus on file and focus on NERDTREE when no files were specified? +- +-Stick this in your vimrc: + ```vim ++" Start NERDTree when Vim is started without file arguments. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | else | NERDTree | wincmd p | endif ++autocmd VimEnter * if argc() == 0 && !exists('s:std_in') | NERDTree | endif + ``` +- + --- +-#### What if I'm also opening a saved session, for example `vim -S session_file.vim`? I don't want NERDTree to open in that scenario. + ```vim ++" Start NERDTree. If a file is specified, move the cursor to its window. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") && v:this_session == "" | NERDTree | endif ++autocmd VimEnter * NERDTree | if argc() > 0 || exists("s:std_in") | wincmd p | endif + ``` +- + --- +-#### How can I open NERDTree automatically when vim starts up on opening a directory? + ```vim ++" Start NERDTree, unless a file or session is specified, eg. vim -S session_file.vim. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | exe 'cd '.argv()[0] | endif ++autocmd VimEnter * if argc() == 0 && !exists('s:std_in') && v:this_session == '' | NERDTree | endif + ``` +- +-This window is tab-specific, meaning it's used by all windows in the tab. This trick also prevents NERDTree from hiding when first selecting a file. +- +-Note: Executing `vim ~/some-directory` will open NERDTree and a new edit window. `exe 'cd '.argv()[0]` sets the `pwd` of the new edit window to `~/some-directory` +- + --- +-#### How can I map a specific key or shortcut to open NERDTree? +- +-Stick this in your vimrc to open NERDTree with `Ctrl+n` (you can set whatever key you want): + ```vim +-map :NERDTreeToggle ++" Start NERDTree when Vim starts with a directory argument. ++autocmd StdinReadPre * let s:std_in=1 ++autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') | ++ \ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif + ``` + +---- +-#### How can I close vim if the only window left open is a NERDTree? ++### How can I close Vim automatically when NERDTree is the last window? + +-Stick this in your vimrc: + ```vim +-autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif ++" Exit Vim if NERDTree is the only window left. ++autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | ++ \ quit | endif + ``` + +---- +-#### Can I have different highlighting for different file extensions? ++### Can I have the same NERDTree on every tab automatically? + +-See here: https://github.com/preservim/nerdtree/issues/433#issuecomment-92590696 ++```vim ++" Open the existing NERDTree on each new tab. ++autocmd BufWinEnter * silent NERDTreeMirror ++``` + +---- +-#### How can I change default arrows? ++### How can I change the default arrows? + +-Use these variables in your vimrc. Note that below are default arrow symbols + ```vim + let g:NERDTreeDirArrowExpandable = '▸' + let g:NERDTreeDirArrowCollapsible = '▾' + ``` +-You can remove the arrows altogether by setting these variables to empty strings, as shown below. This will remove not only the arrows, but a single space following them, shifting the whole tree two character positions to the left. +-```vim +-let g:NERDTreeDirArrowExpandable = '' +-let g:NERDTreeDirArrowCollapsible = '' +-``` ++The preceding values are the non-Windows default arrow symbols. Setting these variables to empty strings will remove the arrows completely and shift the entire tree two character positions to the left. See `:h NERDTreeDirArrowExpandable` for more details. ++ diff --git a/tasks/preservim__nerdtree-1193/solution/solve.sh b/tasks/preservim__nerdtree-1193/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1193/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/preservim__nerdtree-1193/task.toml b/tasks/preservim__nerdtree-1193/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2345707d6b59b78807ddd6033cd38e0c0d69abd2 --- /dev/null +++ b/tasks/preservim__nerdtree-1193/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1193" +description = "Revamp the README file" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "474d735b7d68a315e1f426920f9aa7391369b606" +reference = "https://github.com/preservim/nerdtree/pull/1193" +source_access = "auto" +built_at = "2026-11-16T16:10:02.382732+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d3ec9a06cc1ec05a1cc487f24f3953f359c65b50b01edddad6e81a0d7df121ba" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2020-12-18T20:03:39Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", +] +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:02.589525+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8a0020e76089721d12b3fc2c6c2e6273d8c4feb0e89f165f82bde57b1751f832" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1193/tests/capture.py b/tasks/preservim__nerdtree-1193/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1193/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/preservim__nerdtree-1193/tests/instruction.md b/tasks/preservim__nerdtree-1193/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f43012f8264b19fcb320bd13138bbe9a1744ecde --- /dev/null +++ b/tasks/preservim__nerdtree-1193/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Revamp the README file + +## Description + +### Description of Changes +This file was in desperate need of being rewritten, so I did. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `474d735b7d68`. 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/preservim__nerdtree-1193/tests/oracle.patch b/tasks/preservim__nerdtree-1193/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..92a017b27ceef1627e897b20402be4c9155c397f --- /dev/null +++ b/tasks/preservim__nerdtree-1193/tests/oracle.patch @@ -0,0 +1,298 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e558036..d9c1b45 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) + - **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) + - **.8**: Refactor sort comparison functions, removing redundancy (PhilRunninger) [#1166](https://github.com/preservim/nerdtree/pull/1166) +diff --git a/README.markdown b/README.markdown +index da87fbc..a3a62c1 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -1,171 +1,173 @@ +-The NERDTree [![Vint](https://github.com/preservim/nerdtree/workflows/Vint/badge.svg)](https://github.com/preservim/nerdtree/actions?workflow=Vint) +-============= ++# The NERDTree [![Vint](https://github.com/preservim/nerdtree/workflows/Vint/badge.svg)](https://github.com/preservim/nerdtree/actions?workflow=Vint) + +-Introduction +------------- ++## Introduction + +-The NERDTree is a file system explorer for the Vim editor. Using this plugin, +-users can visually browse complex directory hierarchies, quickly open files for +-reading or editing, and perform basic file system operations. +- +-This plugin can also be extended with custom mappings using a special API. The +-details of this API and of other NERDTree features are described in the +-included documentation. ++The NERDTree is a file system explorer for the Vim editor. Using this plugin, users can visually browse complex directory hierarchies, quickly open files for reading or editing, and perform basic file system operations. + + ![NERDTree Screenshot](https://github.com/preservim/nerdtree/raw/master/screenshot.png) + +-Installation +------------- +- +-Below are just some of the methods for installing NERDTree. Do not follow all of these instructions; just pick your favorite one. Other plugin managers exist, and NERDTree should install just fine with any of them. ++## Installation + +-#### Vim 8+ packages ++Use your favorite plugin manager to install this plugin. [tpope/vim-pathogen](https://github.com/tpope/vim-pathogen), [VundleVimVundle.vim](https://github.com/VundleVim/Vundle.vim), [junegunnvim-plug](https://github.com/junegunn/vim-plug), and [Shougo/dein.vim](https://github.com/Shougo/dein.vim) are some of the more popular ones. A lengthy discussion of these and other managers can be found on [vi.stackexchange.com](https://vi.stackexchange.com/questions/388/what-is-the-difference-between-the-vim-plugin-managers). Basic instructions are provided below, but please **be sure to read, understand, and follow all the safety rules that come with your ~~power tools~~ plugin manager.** + +-If you are using VIM version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: ++If you have no favorite, or want to manage your plugins without 3rd-party dependencies, consider using Vim 8+ packages, as described in Greg Hurrell's excellent Youtube video: [Vim screencast #75: Plugin managers](https://www.youtube.com/watch?v=X2_R3uxDN6g). + +-```bash +-git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree +-vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q +-``` ++
++Pathogen ++Pathogen is more of a runtime path manager than a plugin manager. You must clone the plugins' repositories yourself to a specific location, and Pathogen makes sure they are available in Vim. + +-Otherwise, these are some of the several 3rd-party plugin managers you can choose from. Be sure you read the instructions for your chosen plugin, as there typically are additional steps you need to take. + +-#### [pathogen.vim](https://github.com/tpope/vim-pathogen) ++1. In the terminal, ++ ```bash ++ git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree ++ ``` ++1. In your `vimrc`, ++ ```vim ++ call pathogen#infect() ++ syntax on ++ filetype plugin indent on ++ ``` ++1. Restart Vim, and run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. ++
+ +-In the terminal, +-```bash +-git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree +-``` +-In your vimrc, +-```vim +-call pathogen#infect() +-syntax on +-filetype plugin indent on +-``` ++
++ Vundle + +-Then reload vim, run `:helptags ~/.vim/bundle/nerdtree/doc/` or `:Helptags`. ++1. Install Vundle, according to its instructions. ++1. Add the following text to your `vimrc`. ++ ```vim ++ call vundle#begin() ++ Plugin 'preservim/nerdtree' ++ call vundle#end() ++ ``` ++1. Restart Vim, and run the `:PluginInstall` statement to install your plugins. ++
+ +-#### [Vundle.vim](https://github.com/VundleVim/Vundle.vim) +-```vim +-call vundle#begin() +-Plugin 'preservim/nerdtree' +-call vundle#end() +-``` ++
++ Vim-Plug + +-#### [vim-plug](https://github.com/junegunn/vim-plug) ++1. Install Vim-Plug, according to its instructions. ++1. Add the following text to your `vimrc`. + ```vim + call plug#begin() +-Plug 'preservim/nerdtree' ++ Plug 'preservim/nerdtree' + call plug#end() + ``` ++1. Restart Vim, and run the `:PlugInstall` statement to install your plugins. ++
+ +-#### [dein.vim](https://github.com/Shougo/dein.vim) +-```vim +-call dein#begin() +-call dein#add('preservim/nerdtree') +-call dein#end() +-``` ++
++ Dein + +-#### [apt-vim](https://github.com/egalpin/apt-vim) +-```bash +-apt-vim install -y https://github.com/preservim/nerdtree.git +-``` ++1. Install Dein, according to its instructions. ++1. Add the following text to your `vimrc`. ++ ```vim ++ call dein#begin() ++ call dein#add('preservim/nerdtree') ++ call dein#end() ++ ``` ++1. Restart Vim, and run the `:call dein#install()` statement to install your plugins. ++
+ +-F.A.Q. (here, and in the [Wiki](https://github.com/preservim/nerdtree/wiki)) +------- ++
++Vim 8+ packages + +-#### Is there any support for `git` flags? ++If you are using Vim version 8 or higher you can use its built-in package management; see `:help packages` for more information. Just run these commands in your terminal: + +-Yes, install [nerdtree-git-plugin](https://github.com/Xuyuanp/nerdtree-git-plugin). ++```bash ++git clone https://github.com/preservim/nerdtree.git ~/.vim/pack/vendor/start/nerdtree ++vim -u NONE -c "helptags ~/.vim/pack/vendor/start/nerdtree/doc" -c q ++``` ++
+ +---- +-#### Can I have the nerdtree on every tab automatically? ++## Getting Started ++After installing NERDTree, the best way to learn it is to turn on the Quick Help. Open NERDTree with the `:NERDTree` command, and press `?` to turn on the Quick Help, which will show you all the mappings and commands available in the NERDTree. Of course, your most complete source of information is the documentation: `:help NERDTree`. + +-Nope. If this is something you want then chances are you aren't using tabs and +-buffers as they were intended to be used. Read this +-http://stackoverflow.com/questions/102384/using-vims-tabs-like-buffers ++## NERDTree Plugins ++NERDTree can be extended with custom mappings and functions using its built-in API. The details of this API and are described in the included documentation. Several plugins have been written, and are available on Github for installation like any other plugin. The plugins in this list are maintained (or not) by their respective owners, and certain combinations may be incompatible. + +-If you are interested in this behaviour then consider [vim-nerdtree-tabs](https://github.com/jistr/vim-nerdtree-tabs) ++* [Xuyuanp/nerdtree-git-plugin](https://github.com/Xuyuanp/nerdtree-git-plugin): Shows Git status flags for files and folders in NERDTree. ++* [ryanoasis/vim-devicons](https://github.com/ryanoasis/vim-devicons): Adds filetype-specific icons to NERDTree files and folders, ++* [tiagofumo/vim-nerdtree-syntax-highlight](https://github.com/tiagofumo/vim-nerdtree-syntax-highlight): Adds syntax highlighting to NERDTree based on filetype. ++* [scrooloose/nerdtree-project-plugin](https://github.com/scrooloose/nerdtree-project-plugin): Saves and restores the state of the NERDTree between sessions. ++* [PhilRunninger/nerdtree-buffer-ops](https://github.com/PhilRunninger/nerdtree-buffer-ops): 1) Highlights open files in a different color. 2) Closes a buffer directly from NERDTree. ++* [PhilRunninger/nerdtree-visual-selection](https://github.com/PhilRunninger/nerdtree-visual-selection): Enables NERDTree to open, delete, move, or copy multiple Visually-selected files at once. + +---- +-#### How can I open a NERDTree automatically when vim starts up? ++If any others should be listed, mention them in an issue or pull request. + +-Stick this in your vimrc: `autocmd vimenter * NERDTree` + +---- +-#### How can I open a NERDTree automatically when vim starts up and autofocus on file? ++## Frequently Asked Questions + +-Stick this in your vimrc: `autocmd vimenter * NERDTree | wincmd p` ++In the answers to these questions, you will see code blocks that you can put in your `vimrc` file. + +---- +-#### How can I open a NERDTree automatically when vim starts up if no files were specified? ++### How can I map a specific key or shortcut to open NERDTree? + +-Stick this in your vimrc: ++NERDTree doesn't create any shortcuts outside of the NERDTree window, so as not to overwrite any of your other shortcuts. Use the `nnoremap` command in your `vimrc`. You, of course, have many keys and NERDTree commands to choose from. Here are but a few examples. + ```vim +-autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | endif ++nnoremap n :NERDTreeFocus ++nnoremap :NERDTree ++nnoremap :NERDTreeToggle ++nnoremap :NERDTreeFind + ``` + +-Note: Now start vim with plain `vim`, not `vim .` ++### How do I open NERDTree automatically when Vim starts? ++Each code block below is slightly different, as described in the `" Comment lines`. + ++```vim ++" Start NERDTree and leave the cursor in it. ++autocmd VimEnter * NERDTree ++``` ++--- ++```vim ++" Start NERDTree and put the cursor back in the other window. ++autocmd VimEnter * NERDTree | wincmd p ++``` + --- +-#### How to autofocus on file and focus on NERDTREE when no files were specified? +- +-Stick this in your vimrc: + ```vim ++" Start NERDTree when Vim is started without file arguments. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") | NERDTree | else | NERDTree | wincmd p | endif ++autocmd VimEnter * if argc() == 0 && !exists('s:std_in') | NERDTree | endif + ``` +- + --- +-#### What if I'm also opening a saved session, for example `vim -S session_file.vim`? I don't want NERDTree to open in that scenario. + ```vim ++" Start NERDTree. If a file is specified, move the cursor to its window. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 0 && !exists("s:std_in") && v:this_session == "" | NERDTree | endif ++autocmd VimEnter * NERDTree | if argc() > 0 || exists("s:std_in") | wincmd p | endif + ``` +- + --- +-#### How can I open NERDTree automatically when vim starts up on opening a directory? + ```vim ++" Start NERDTree, unless a file or session is specified, eg. vim -S session_file.vim. + autocmd StdinReadPre * let s:std_in=1 +-autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists("s:std_in") | exe 'NERDTree' argv()[0] | wincmd p | ene | exe 'cd '.argv()[0] | endif ++autocmd VimEnter * if argc() == 0 && !exists('s:std_in') && v:this_session == '' | NERDTree | endif + ``` +- +-This window is tab-specific, meaning it's used by all windows in the tab. This trick also prevents NERDTree from hiding when first selecting a file. +- +-Note: Executing `vim ~/some-directory` will open NERDTree and a new edit window. `exe 'cd '.argv()[0]` sets the `pwd` of the new edit window to `~/some-directory` +- + --- +-#### How can I map a specific key or shortcut to open NERDTree? +- +-Stick this in your vimrc to open NERDTree with `Ctrl+n` (you can set whatever key you want): + ```vim +-map :NERDTreeToggle ++" Start NERDTree when Vim starts with a directory argument. ++autocmd StdinReadPre * let s:std_in=1 ++autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists('s:std_in') | ++ \ execute 'NERDTree' argv()[0] | wincmd p | enew | execute 'cd '.argv()[0] | endif + ``` + +---- +-#### How can I close vim if the only window left open is a NERDTree? ++### How can I close Vim automatically when NERDTree is the last window? + +-Stick this in your vimrc: + ```vim +-autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif ++" Exit Vim if NERDTree is the only window left. ++autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | ++ \ quit | endif + ``` + +---- +-#### Can I have different highlighting for different file extensions? ++### Can I have the same NERDTree on every tab automatically? + +-See here: https://github.com/preservim/nerdtree/issues/433#issuecomment-92590696 ++```vim ++" Open the existing NERDTree on each new tab. ++autocmd BufWinEnter * silent NERDTreeMirror ++``` + +---- +-#### How can I change default arrows? ++### How can I change the default arrows? + +-Use these variables in your vimrc. Note that below are default arrow symbols + ```vim + let g:NERDTreeDirArrowExpandable = '▸' + let g:NERDTreeDirArrowCollapsible = '▾' + ``` +-You can remove the arrows altogether by setting these variables to empty strings, as shown below. This will remove not only the arrows, but a single space following them, shifting the whole tree two character positions to the left. +-```vim +-let g:NERDTreeDirArrowExpandable = '' +-let g:NERDTreeDirArrowCollapsible = '' +-``` ++The preceding values are the non-Windows default arrow symbols. Setting these variables to empty strings will remove the arrows completely and shift the entire tree two character positions to the left. See `:h NERDTreeDirArrowExpandable` for more details. ++ diff --git a/tasks/preservim__nerdtree-1193/tests/test.sh b/tasks/preservim__nerdtree-1193/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a2936c215819fa4ea0b4da13af66c70e4b34ab0 --- /dev/null +++ b/tasks/preservim__nerdtree-1193/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 474d735b7d68a315e1f426920f9aa7391369b606 > "$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/preservim__nerdtree-1193/tests/verifier.py b/tasks/preservim__nerdtree-1193/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1193/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/preservim__nerdtree-1200/environment/Dockerfile b/tasks/preservim__nerdtree-1200/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2072fb92923ff7b4b816f979d2ad5627d1e5c510 --- /dev/null +++ b/tasks/preservim__nerdtree-1200/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin aaa946fb6bd79b9af86fbaf4b6b63fd81d839bd9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard aaa946fb6bd79b9af86fbaf4b6b63fd81d839bd9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base aaa946fb6bd79b9af86fbaf4b6b63fd81d839bd9 \ + && 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/preservim__nerdtree-1200/instruction.md b/tasks/preservim__nerdtree-1200/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2510554d081d9129fc02c03d0c06da908ffde9c2 --- /dev/null +++ b/tasks/preservim__nerdtree-1200/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Respect NERDTreeCustomOpenArgs when opening bookmark + +## 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 `aaa946fb6bd7`. 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/preservim__nerdtree-1200/solution/patch.diff b/tasks/preservim__nerdtree-1200/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4f8828233f4f9849bc92702c00c91ab9690995ae --- /dev/null +++ b/tasks/preservim__nerdtree-1200/solution/patch.diff @@ -0,0 +1,70 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d9c1b45..a1ec843 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) + - **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) + - **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 78b3fa1..b0cedee 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -110,8 +110,38 @@ endfunction + "FUNCTION: s:initCustomOpenArgs() {{{1 + " Make sure NERDTreeCustomOpenArgs has needed keys + function! s:initCustomOpenArgs() abort +- let g:NERDTreeCustomOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) +- return extend(g:NERDTreeCustomOpenArgs, {'file':{'reuse': 'all', 'where': 'p'}, 'dir':{}}, 'keep') ++ let l:defaultOpenArgs = {'file': {'reuse': 'all', 'where': 'p'}, 'dir': {}} ++ let l:customOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) ++ ++ if v:false is# s:validateType(l:customOpenArgs, v:t_dict) ++ return l:defaultOpenArgs ++ endif ++ ++ for l:typeKey in keys(l:defaultOpenArgs) ++ if v:false is# s:validateType(get(l:customOpenArgs, l:typeKey, {}), v:t_dict) ++ let l:customOpenArgs[l:typeKey] = l:defaultOpenArgs[l:typeKey] ++ continue ++ endif ++ ++ for l:optionName in keys(l:defaultOpenArgs[l:typeKey]) ++ if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), v:t_string) ++ continue ++ endif ++ let l:customOpenArgs[l:typeKey][l:optionName] = l:defaultOpenArgs[l:typeKey][l:optionName] ++ endfor ++ endfor ++ ++ let g:NERDTreeCustomOpenArgs = l:customOpenArgs ++ ++ return extend(l:customOpenArgs, l:defaultOpenArgs, 'keep') ++endfunction ++ ++function! s:validateType(variable, type) abort ++ if type(a:variable) is# a:type ++ return v:true ++ endif ++ ++ return v:false + endfunction + + "FUNCTION: s:activateAll() {{{1 +@@ -500,9 +530,10 @@ function! nerdtree#ui_glue#openBookmark(name) abort + endtry + if l:bookmark.path.isDirectory + call l:bookmark.open(b:NERDTree) +- else +- call l:bookmark.open(b:NERDTree, {'where': 'p'}) ++ return + endif ++ ++ call l:bookmark.open(b:NERDTree, s:initCustomOpenArgs().file) + endfunction + + " FUNCTION: s:openHSplit(target) {{{1 diff --git a/tasks/preservim__nerdtree-1200/solution/solve.sh b/tasks/preservim__nerdtree-1200/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1200/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/preservim__nerdtree-1200/task.toml b/tasks/preservim__nerdtree-1200/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2483d626814de44ad4263280e0bf3ca9e9ed0465 --- /dev/null +++ b/tasks/preservim__nerdtree-1200/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1200" +description = "Respect NERDTreeCustomOpenArgs when opening bookmark" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "aaa946fb6bd79b9af86fbaf4b6b63fd81d839bd9" +reference = "https://github.com/preservim/nerdtree/pull/1200" +source_access = "auto" +built_at = "2026-11-16T16:10:02.394423+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:da6cdd40703cfabe15a17988551d5b0256d82e60227b5940834c624835faa7b3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-18T01:00:18Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "autoload/nerdtree/ui_glue.vim", +] +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:02.590036+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9d4970f63e421b4ae28540cb1546e9ca99541feff898dc9e5007eebe6863fa4a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1200/tests/capture.py b/tasks/preservim__nerdtree-1200/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1200/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/preservim__nerdtree-1200/tests/instruction.md b/tasks/preservim__nerdtree-1200/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2510554d081d9129fc02c03d0c06da908ffde9c2 --- /dev/null +++ b/tasks/preservim__nerdtree-1200/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Respect NERDTreeCustomOpenArgs when opening bookmark + +## 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 `aaa946fb6bd7`. 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/preservim__nerdtree-1200/tests/oracle.patch b/tasks/preservim__nerdtree-1200/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4f8828233f4f9849bc92702c00c91ab9690995ae --- /dev/null +++ b/tasks/preservim__nerdtree-1200/tests/oracle.patch @@ -0,0 +1,70 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d9c1b45..a1ec843 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.9 ++- **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) + - **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) + - **.10**: Open a mirrored NERDTree with correct width (PhilRunninger) [#1177](https://github.com/preservim/nerdtree/pull/1177) + - **.9**: Updated Readme, removed typo (H3RSKO) [#1167](https://github.com/preservim/nerdtree/pull/1167) +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index 78b3fa1..b0cedee 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -110,8 +110,38 @@ endfunction + "FUNCTION: s:initCustomOpenArgs() {{{1 + " Make sure NERDTreeCustomOpenArgs has needed keys + function! s:initCustomOpenArgs() abort +- let g:NERDTreeCustomOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) +- return extend(g:NERDTreeCustomOpenArgs, {'file':{'reuse': 'all', 'where': 'p'}, 'dir':{}}, 'keep') ++ let l:defaultOpenArgs = {'file': {'reuse': 'all', 'where': 'p'}, 'dir': {}} ++ let l:customOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) ++ ++ if v:false is# s:validateType(l:customOpenArgs, v:t_dict) ++ return l:defaultOpenArgs ++ endif ++ ++ for l:typeKey in keys(l:defaultOpenArgs) ++ if v:false is# s:validateType(get(l:customOpenArgs, l:typeKey, {}), v:t_dict) ++ let l:customOpenArgs[l:typeKey] = l:defaultOpenArgs[l:typeKey] ++ continue ++ endif ++ ++ for l:optionName in keys(l:defaultOpenArgs[l:typeKey]) ++ if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), v:t_string) ++ continue ++ endif ++ let l:customOpenArgs[l:typeKey][l:optionName] = l:defaultOpenArgs[l:typeKey][l:optionName] ++ endfor ++ endfor ++ ++ let g:NERDTreeCustomOpenArgs = l:customOpenArgs ++ ++ return extend(l:customOpenArgs, l:defaultOpenArgs, 'keep') ++endfunction ++ ++function! s:validateType(variable, type) abort ++ if type(a:variable) is# a:type ++ return v:true ++ endif ++ ++ return v:false + endfunction + + "FUNCTION: s:activateAll() {{{1 +@@ -500,9 +530,10 @@ function! nerdtree#ui_glue#openBookmark(name) abort + endtry + if l:bookmark.path.isDirectory + call l:bookmark.open(b:NERDTree) +- else +- call l:bookmark.open(b:NERDTree, {'where': 'p'}) ++ return + endif ++ ++ call l:bookmark.open(b:NERDTree, s:initCustomOpenArgs().file) + endfunction + + " FUNCTION: s:openHSplit(target) {{{1 diff --git a/tasks/preservim__nerdtree-1200/tests/test.sh b/tasks/preservim__nerdtree-1200/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..adb27c895c76b97f4b49c3d09287cac5cdf3c6d3 --- /dev/null +++ b/tasks/preservim__nerdtree-1200/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 aaa946fb6bd79b9af86fbaf4b6b63fd81d839bd9 > "$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/preservim__nerdtree-1200/tests/verifier.py b/tasks/preservim__nerdtree-1200/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1200/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/preservim__nerdtree-1206/environment/Dockerfile b/tasks/preservim__nerdtree-1206/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e75e8d9118df43c4e720fdab7393352589eb4a1 --- /dev/null +++ b/tasks/preservim__nerdtree-1206/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a7eb011e47a9b55bb20b4da981092816f940c932 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a7eb011e47a9b55bb20b4da981092816f940c932 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a7eb011e47a9b55bb20b4da981092816f940c932 \ + && 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/preservim__nerdtree-1206/instruction.md b/tasks/preservim__nerdtree-1206/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4161e1fda168ddbac5ff440001740ab80162fac2 --- /dev/null +++ b/tasks/preservim__nerdtree-1206/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix missing key case, add BC type checking + +## 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 `a7eb011e47a9`. 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/preservim__nerdtree-1206/solution/patch.diff b/tasks/preservim__nerdtree-1206/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..66ccc7669130a86bd033ca76c3004fcf5ad78d9a --- /dev/null +++ b/tasks/preservim__nerdtree-1206/solution/patch.diff @@ -0,0 +1,43 @@ +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index aabd2ee..31b58c4 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -108,24 +108,24 @@ function! s:customOpenBookmark(node) abort + endfunction + + "FUNCTION: s:initCustomOpenArgs() {{{1 +-" Make sure NERDTreeCustomOpenArgs has needed keys + function! s:initCustomOpenArgs() abort + let l:defaultOpenArgs = {'file': {'reuse': 'all', 'where': 'p'}, 'dir': {}} + let l:customOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) +- return extend(l:customOpenArgs, l:defaultOpenArgs, 'keep') + +- if v:false is# s:validateType(l:customOpenArgs, v:t_dict) ++ if !s:validateType(l:customOpenArgs, type({})) || empty(l:customOpenArgs) ++ let g:NERDTreeCustomOpenArgs = l:customOpenArgs + return l:defaultOpenArgs + endif + + for l:typeKey in keys(l:defaultOpenArgs) +- if v:false is# s:validateType(get(l:customOpenArgs, l:typeKey, {}), v:t_dict) ++ if !s:validateType(get(l:customOpenArgs, l:typeKey, {}), type({})) ++ \ || !has_key(l:customOpenArgs, l:typeKey) + let l:customOpenArgs[l:typeKey] = l:defaultOpenArgs[l:typeKey] + continue + endif + + for l:optionName in keys(l:defaultOpenArgs[l:typeKey]) +- if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), v:t_string) ++ if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), type('')) + continue + endif + let l:customOpenArgs[l:typeKey][l:optionName] = l:defaultOpenArgs[l:typeKey][l:optionName] +@@ -138,7 +138,7 @@ function! s:initCustomOpenArgs() abort + endfunction + + function! s:validateType(variable, type) abort +- if type(a:variable) is# a:type ++ if type(a:variable) == a:type + return v:true + endif + diff --git a/tasks/preservim__nerdtree-1206/solution/solve.sh b/tasks/preservim__nerdtree-1206/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1206/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/preservim__nerdtree-1206/task.toml b/tasks/preservim__nerdtree-1206/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4552401f2d0c425db38fb03c001f8532b0ead85f --- /dev/null +++ b/tasks/preservim__nerdtree-1206/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1206" +description = "Fix missing key case, add BC type checking" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "a7eb011e47a9b55bb20b4da981092816f940c932" +reference = "https://github.com/preservim/nerdtree/pull/1206" +source_access = "auto" +built_at = "2026-11-16T16:10:02.392920+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:50e2d45102de83e0be2a676df43241cffae5c8181994b41d6ad0dc75a7c9da76" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-19T02:23:52Z" +diff_format = "unified" +context_files = [ + "autoload/nerdtree/ui_glue.vim", +] +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:02.590539+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:315f1b50688cc3c51e9578426527df6f11bd97b9153cfee2f48ee8bd19e76ce9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1206/tests/capture.py b/tasks/preservim__nerdtree-1206/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1206/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/preservim__nerdtree-1206/tests/instruction.md b/tasks/preservim__nerdtree-1206/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4161e1fda168ddbac5ff440001740ab80162fac2 --- /dev/null +++ b/tasks/preservim__nerdtree-1206/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix missing key case, add BC type checking + +## 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 `a7eb011e47a9`. 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/preservim__nerdtree-1206/tests/oracle.patch b/tasks/preservim__nerdtree-1206/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..66ccc7669130a86bd033ca76c3004fcf5ad78d9a --- /dev/null +++ b/tasks/preservim__nerdtree-1206/tests/oracle.patch @@ -0,0 +1,43 @@ +diff --git a/autoload/nerdtree/ui_glue.vim b/autoload/nerdtree/ui_glue.vim +index aabd2ee..31b58c4 100644 +--- a/autoload/nerdtree/ui_glue.vim ++++ b/autoload/nerdtree/ui_glue.vim +@@ -108,24 +108,24 @@ function! s:customOpenBookmark(node) abort + endfunction + + "FUNCTION: s:initCustomOpenArgs() {{{1 +-" Make sure NERDTreeCustomOpenArgs has needed keys + function! s:initCustomOpenArgs() abort + let l:defaultOpenArgs = {'file': {'reuse': 'all', 'where': 'p'}, 'dir': {}} + let l:customOpenArgs = get(g:, 'NERDTreeCustomOpenArgs', {}) +- return extend(l:customOpenArgs, l:defaultOpenArgs, 'keep') + +- if v:false is# s:validateType(l:customOpenArgs, v:t_dict) ++ if !s:validateType(l:customOpenArgs, type({})) || empty(l:customOpenArgs) ++ let g:NERDTreeCustomOpenArgs = l:customOpenArgs + return l:defaultOpenArgs + endif + + for l:typeKey in keys(l:defaultOpenArgs) +- if v:false is# s:validateType(get(l:customOpenArgs, l:typeKey, {}), v:t_dict) ++ if !s:validateType(get(l:customOpenArgs, l:typeKey, {}), type({})) ++ \ || !has_key(l:customOpenArgs, l:typeKey) + let l:customOpenArgs[l:typeKey] = l:defaultOpenArgs[l:typeKey] + continue + endif + + for l:optionName in keys(l:defaultOpenArgs[l:typeKey]) +- if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), v:t_string) ++ if s:validateType(get(l:customOpenArgs[l:typeKey], l:optionName, v:null), type('')) + continue + endif + let l:customOpenArgs[l:typeKey][l:optionName] = l:defaultOpenArgs[l:typeKey][l:optionName] +@@ -138,7 +138,7 @@ function! s:initCustomOpenArgs() abort + endfunction + + function! s:validateType(variable, type) abort +- if type(a:variable) is# a:type ++ if type(a:variable) == a:type + return v:true + endif + diff --git a/tasks/preservim__nerdtree-1206/tests/test.sh b/tasks/preservim__nerdtree-1206/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1fd9be2c59ade72525f4e793c47c2eec3a52ec0 --- /dev/null +++ b/tasks/preservim__nerdtree-1206/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 a7eb011e47a9b55bb20b4da981092816f940c932 > "$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/preservim__nerdtree-1206/tests/verifier.py b/tasks/preservim__nerdtree-1206/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1206/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/preservim__nerdtree-1207/environment/Dockerfile b/tasks/preservim__nerdtree-1207/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a246a51222de260475422fd4cb8adb2150f2b58 --- /dev/null +++ b/tasks/preservim__nerdtree-1207/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7099f638edd3eda5cd5687b4e13d342bb7f9949d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7099f638edd3eda5cd5687b4e13d342bb7f9949d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7099f638edd3eda5cd5687b4e13d342bb7f9949d \ + && 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/preservim__nerdtree-1207/instruction.md b/tasks/preservim__nerdtree-1207/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..144a132026b2127438fe3f5b2fcdb28c7ae15a8f --- /dev/null +++ b/tasks/preservim__nerdtree-1207/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Enable full path specifications for NERDTreeIgnore + +## Description + +### Description of Changes + + +Added a new tag `[[path]]`, for NERDTreeIgnore, that performs a pattern match on the full path of the node instead of just the last component of it. This is useful if you have a particular folder that you want to be hidden, while still showing every other instance of that folder. For example, +```vim +let NERDTreeIgnore = ['tmp/cache$[[path]]']` +``` +will cause NERDTree to ignore `/tmp/cache` and `/home/foo/projects/bar/tmp/cache`, but `/spooler/cache` and `/usr/bin/cache` will be displayed. + +The path regex needs to be compatible with the OS you're using, so for Windows, you would need to escape the backslashes, like so: `'tmp\\cache[[path]]'` or `'C:\\Users\\foo\\tmp\\cache$[[path]]'`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7099f638edd3`. 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/preservim__nerdtree-1207/solution/patch.diff b/tasks/preservim__nerdtree-1207/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..70d56f0570c5f74c4f32cb7c5541bcbe138b0275 --- /dev/null +++ b/tasks/preservim__nerdtree-1207/solution/patch.diff @@ -0,0 +1,224 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index a1ec843..e5783e6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.10 ++- **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 + - **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) + - **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 2989718..95742a3 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -116,7 +116,7 @@ The following features and functionality are provided by the NERDTree: + :NERDTreeVCS (opens root of repository containing CWD) + < + :NERDTreeFromBookmark *:NERDTreeFromBookmark* +- Opens a fresh NERDTree with the root initialized to the dir for ++ Opens a fresh NERDTree with the root initialized to the directory for + . The only reason to use this command over :NERDTree is for + the completion (which is for bookmarks rather than directories). + +@@ -126,7 +126,7 @@ The following features and functionality are provided by the NERDTree: + is set to that path. If no NERDTree exists for this tab then this command + acts the same as the |:NERDTree| command. + +-:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* ++:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* + Like |:NERDTreeToggle|, but searches up the directory tree to find the top of + the version control system repository, and roots the NERDTree there. It + works with Git, Subversion, Mercurial, Bazaar, and Darcs repositories. A +@@ -249,7 +249,7 @@ Key Description help-tag~ + + o........Open files, directories and bookmarks......................|NERDTree-o| + go.......Open selected file, but leave cursor in the NERDTree......|NERDTree-go| +- Open selected bookmark dir in current NERDTree ++ Open selected bookmark directory in current NERDTree + t........Open selected node/bookmark in a new tab...................|NERDTree-t| + T........Same as 't' but keep the focus on the current tab..........|NERDTree-T| + i........Open selected file in a split window.......................|NERDTree-i| +@@ -260,10 +260,10 @@ gs.......Same as s, but leave the cursor on the NERDTree...........|NERDTree-gs| + O........Recursively open the selected directory....................|NERDTree-O| + x........Close the current nodes parent.............................|NERDTree-x| + X........Recursively close all children of the current node.........|NERDTree-X| +-e........Edit the current dir.......................................|NERDTree-e| ++e........Edit the current directory.................................|NERDTree-e| + + double-click....same as |NERDTree-o|. +-middle-click....same as |NERDTree-i| for files, and |NERDTree-e| for dirs. ++middle-click....same as |NERDTree-i| for files, and |NERDTree-e| for directories. + + D........Delete the current bookmark ...............................|NERDTree-D| + +@@ -274,13 +274,13 @@ J........Jump down inside directories at the current tree depth.....|NERDTree-J| + ....Jump down to next sibling of the current directory.......|NERDTree-C-J| + ....Jump up to previous sibling of the current directory.....|NERDTree-C-K| + +-C........Change the tree root to the selected dir...................|NERDTree-C| ++C........Change the tree root to the selected directory.............|NERDTree-C| + u........Move the tree root up one directory........................|NERDTree-u| + U........Same as 'u' except the old root node is left open..........|NERDTree-U| + r........Recursively refresh the current directory..................|NERDTree-r| + R........Recursively refresh the current root.......................|NERDTree-R| + m........Display the NERDTree menu..................................|NERDTree-m| +-cd.......Change the CWD to the dir of the selected node............|NERDTree-cd| ++cd.......Change the CWD to the directory of the selected node......|NERDTree-cd| + CD.......Change tree root to the CWD...............................|NERDTree-CD| + + I........Toggle whether hidden files displayed......................|NERDTree-I| +@@ -469,7 +469,7 @@ Jump to the first child of the current nodes parent. + + If the cursor is already on the first node then do the following: + * loop back thru the siblings of the current nodes parent until we find an +- open dir with children ++ open directory with children + * go to the first child of that node + + ------------------------------------------------------------------------------ +@@ -482,7 +482,7 @@ Jump to the last child of the current nodes parent. + + If the cursor is already on the last node then do the following: + * loop forward thru the siblings of the current nodes parent until we find +- an open dir with children ++ an open directory with children + * go to the last child of that node + + ------------------------------------------------------------------------------ +@@ -516,7 +516,7 @@ Default key: u + Map setting: *NERDTreeMapUpdir* + Applies to: no restrictions. + +-Move the tree root up a dir (like doing a "cd .."). ++Move the tree root up a directory (like doing a "cd .."). + + ------------------------------------------------------------------------------ + *NERDTree-U* +@@ -532,8 +532,8 @@ Default key: r + Map setting: *NERDTreeMapRefresh* + Applies to: files and directories. + +-If a dir is selected, recursively refresh that dir, i.e. scan the filesystem +-for changes and represent them in the tree. ++If a directory is selected, recursively refresh that directory, i.e. scan the ++filesystem for changes and represent them in the tree. + + If a file node is selected then the above is done on it's parent. + +@@ -634,8 +634,8 @@ file explorers have. + + The script comes with two default menu plugins: exec_menuitem.vim and + fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for +-creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a +-menu item to execute executable files. ++creating/deleting/moving/copying files and directories. exec_menuitem.vim ++provides a menu item to execute executable files. + + Related tags: |NERDTree-m| |NERDTreeApi| + +@@ -921,7 +921,7 @@ Default: ['\~$']. + + This setting is used to specify which files the NERDTree should ignore. It + must be a list of regular expressions. When the NERDTree is rendered, any +-files/dirs that match any of the regex's in NERDTreeIgnore won't be ++files/directories that match any of the regex's in NERDTreeIgnore won't be + displayed. + + For example if you put the following line in your vimrc: > +@@ -929,13 +929,18 @@ For example if you put the following line in your vimrc: > + < + then all files ending in .vim or ~ will be ignored. + +-There are 2 magic flags that can be appended to the end of each regular +-expression to specify that the regex should match only files or only dirs. +-These flags are "[[dir]]" and "[[file]]". Example: > +- let NERDTreeIgnore=['\.d$[[dir]]', '\.o$[[file]]'] ++There are 3 magic flags that can be appended to the end of each regular ++expression to specify that the regex should match only filenames, only lowest ++level directories, or a full path. These flags are "[[dir]]", "[[file]]", and ++"[[path]]". Example: > ++ let NERDTreeIgnore=['\.d$[[dir]]', '\.o$[[file]]', 'tmp/cache$[[path]]'] + < +-This will cause all dirs ending in ".d" to be ignored and all files ending in +-".o" to be ignored. ++This will cause all directories ending in ".d" to be ignored, all files ending ++in ".o" to be ignored, and the "cache" subdirectory of any "tmp" directory to ++be ignored. All other "cache" directories will be displayed. ++ ++When using the "[[path]]" tag on Windows, make sure you use escaped ++backslashes for the separators in the regex, eg. 'Temp\\cache$[[path]]' + + Note: to tell the NERDTree not to ignore any files you must use the following + line: > +@@ -1099,8 +1104,8 @@ Examples: > + < + 1. Directories will appear last, everything else will appear above. + 2. Everything will simply appear in alphabetical order. +-3. Dirs will appear first, then ruby and php. Swap files, bak files and vim +- backup files will appear last with everything else preceding them. ++3. Directories will appear first, then ruby and php. Swap files, bak files ++ and vim backup files will appear last with everything else preceding them. + 4. Everything is sorted by size, largest to smallest, with directories + considered to have size 0 bytes. + 5. Directories will appear first alphabetically, followed by files, sorted by +@@ -1174,8 +1179,9 @@ Use one of the following lines for this setting: > + Values: 0 or 1 + Default: 1. + +-When displaying dir nodes, this setting tells NERDTree to collapse dirs that +-have only one child. Use one of the following lines for this setting: > ++When displaying directory nodes, this setting tells NERDTree to collapse ++directories that have only one child. Use one of the following lines for this ++setting: > + let NERDTreeCascadeSingleChildDir=0 + let NERDTreeCascadeSingleChildDir=1 + < +@@ -1184,11 +1190,12 @@ have only one child. Use one of the following lines for this setting: > + Values: 0 or 1 + Default: 1. + +-When opening dir nodes, this setting tells NERDTree to recursively open dirs +-that have only one child which is also a dir. NERDTree will stop when it finds +-a dir that contains anything but another single dir. This setting also causes +-the |NERDTree-x| mapping to close dirs in the same manner. This setting may be +-useful for Java projects. Use one of the following lines for this setting: > ++When opening directory nodes, this setting tells NERDTree to recursively open ++directories that have only one child which is also a directory. NERDTree will ++stop when it finds a directory that contains anything but another single ++directory. This setting also causes the |NERDTree-x| mapping to close ++directories in the same manner. This setting may be useful for Java projects. ++Use one of the following lines for this setting: > + let NERDTreeCascadeOpenSingleChildDir=0 + let NERDTreeCascadeOpenSingleChildDir=1 + < +@@ -1362,8 +1369,8 @@ NERDTreeAddKeyMap({options}) *NERDTreeAddKeyMap()* + < + This code should sit in a file like ~/.vim/nerdtree_plugin/mymapping.vim. + It adds a (redundant) mapping on 'foo' which changes vim's CWD to that of +- the current dir node. Note this mapping will only fire when the cursor is +- on a directory node. ++ the current directory node. Note this mapping will only fire when the ++ cursor is on a directory node. + + ------------------------------------------------------------------------------ + 4.2. Menu API *NERDTreeMenuAPI* +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 786ccd9..26749c6 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -483,7 +483,10 @@ endfunction + " returns true if this path matches the given ignore pattern + function! s:Path._ignorePatternMatches(pattern) + let pat = a:pattern +- if strpart(pat,len(pat)-7) ==# '[[dir]]' ++ if strpart(pat,len(pat)-8) ==# '[[path]]' ++ let pat = strpart(pat,0, len(pat)-8) ++ return self.str() =~# pat ++ elseif strpart(pat,len(pat)-7) ==# '[[dir]]' + if !self.isDirectory + return 0 + endif diff --git a/tasks/preservim__nerdtree-1207/solution/solve.sh b/tasks/preservim__nerdtree-1207/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1207/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/preservim__nerdtree-1207/task.toml b/tasks/preservim__nerdtree-1207/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..12b0c1987a2d86ab50ff8a820ce3cf79b6b44561 --- /dev/null +++ b/tasks/preservim__nerdtree-1207/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1207" +description = "Enable full path specifications for NERDTreeIgnore" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "7099f638edd3eda5cd5687b4e13d342bb7f9949d" +reference = "https://github.com/preservim/nerdtree/pull/1207" +source_access = "auto" +built_at = "2026-11-16T16:10:02.391051+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b726eaffbf9ae5ff6b4308fe5f5d9ed957b29341a64089e9e7fcfbecdd8fbab5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-20T01:07:26Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "doc/NERDTree.txt", + "lib/nerdtree/path.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 78 +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:02.591048+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eea6f78eae158d9de393434d3597b6ffd2b3f0b5e4f63a1daf44a65102766a50" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1207/tests/capture.py b/tasks/preservim__nerdtree-1207/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1207/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/preservim__nerdtree-1207/tests/instruction.md b/tasks/preservim__nerdtree-1207/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..144a132026b2127438fe3f5b2fcdb28c7ae15a8f --- /dev/null +++ b/tasks/preservim__nerdtree-1207/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Enable full path specifications for NERDTreeIgnore + +## Description + +### Description of Changes + + +Added a new tag `[[path]]`, for NERDTreeIgnore, that performs a pattern match on the full path of the node instead of just the last component of it. This is useful if you have a particular folder that you want to be hidden, while still showing every other instance of that folder. For example, +```vim +let NERDTreeIgnore = ['tmp/cache$[[path]]']` +``` +will cause NERDTree to ignore `/tmp/cache` and `/home/foo/projects/bar/tmp/cache`, but `/spooler/cache` and `/usr/bin/cache` will be displayed. + +The path regex needs to be compatible with the OS you're using, so for Windows, you would need to escape the backslashes, like so: `'tmp\\cache[[path]]'` or `'C:\\Users\\foo\\tmp\\cache$[[path]]'`. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7099f638edd3`. 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/preservim__nerdtree-1207/tests/oracle.patch b/tasks/preservim__nerdtree-1207/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..70d56f0570c5f74c4f32cb7c5541bcbe138b0275 --- /dev/null +++ b/tasks/preservim__nerdtree-1207/tests/oracle.patch @@ -0,0 +1,224 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index a1ec843..e5783e6 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -4,6 +4,8 @@ + version in an unordered list. The format is: + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> ++#### 6.10 ++- **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 + - **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) + - **.11**: Revamp the README. (buncis, PhilRunninger) [#1192](https://github.com/preservim/nerdtree/pull/1192), [#1193](https://github.com/preservim/nerdtree/pull/1193) +diff --git a/doc/NERDTree.txt b/doc/NERDTree.txt +index 2989718..95742a3 100644 +--- a/doc/NERDTree.txt ++++ b/doc/NERDTree.txt +@@ -116,7 +116,7 @@ The following features and functionality are provided by the NERDTree: + :NERDTreeVCS (opens root of repository containing CWD) + < + :NERDTreeFromBookmark *:NERDTreeFromBookmark* +- Opens a fresh NERDTree with the root initialized to the dir for ++ Opens a fresh NERDTree with the root initialized to the directory for + . The only reason to use this command over :NERDTree is for + the completion (which is for bookmarks rather than directories). + +@@ -126,7 +126,7 @@ The following features and functionality are provided by the NERDTree: + is set to that path. If no NERDTree exists for this tab then this command + acts the same as the |:NERDTree| command. + +-:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* ++:NERDTreeToggleVCS [ | ] *:NERDTreeToggleVCS* + Like |:NERDTreeToggle|, but searches up the directory tree to find the top of + the version control system repository, and roots the NERDTree there. It + works with Git, Subversion, Mercurial, Bazaar, and Darcs repositories. A +@@ -249,7 +249,7 @@ Key Description help-tag~ + + o........Open files, directories and bookmarks......................|NERDTree-o| + go.......Open selected file, but leave cursor in the NERDTree......|NERDTree-go| +- Open selected bookmark dir in current NERDTree ++ Open selected bookmark directory in current NERDTree + t........Open selected node/bookmark in a new tab...................|NERDTree-t| + T........Same as 't' but keep the focus on the current tab..........|NERDTree-T| + i........Open selected file in a split window.......................|NERDTree-i| +@@ -260,10 +260,10 @@ gs.......Same as s, but leave the cursor on the NERDTree...........|NERDTree-gs| + O........Recursively open the selected directory....................|NERDTree-O| + x........Close the current nodes parent.............................|NERDTree-x| + X........Recursively close all children of the current node.........|NERDTree-X| +-e........Edit the current dir.......................................|NERDTree-e| ++e........Edit the current directory.................................|NERDTree-e| + + double-click....same as |NERDTree-o|. +-middle-click....same as |NERDTree-i| for files, and |NERDTree-e| for dirs. ++middle-click....same as |NERDTree-i| for files, and |NERDTree-e| for directories. + + D........Delete the current bookmark ...............................|NERDTree-D| + +@@ -274,13 +274,13 @@ J........Jump down inside directories at the current tree depth.....|NERDTree-J| + ....Jump down to next sibling of the current directory.......|NERDTree-C-J| + ....Jump up to previous sibling of the current directory.....|NERDTree-C-K| + +-C........Change the tree root to the selected dir...................|NERDTree-C| ++C........Change the tree root to the selected directory.............|NERDTree-C| + u........Move the tree root up one directory........................|NERDTree-u| + U........Same as 'u' except the old root node is left open..........|NERDTree-U| + r........Recursively refresh the current directory..................|NERDTree-r| + R........Recursively refresh the current root.......................|NERDTree-R| + m........Display the NERDTree menu..................................|NERDTree-m| +-cd.......Change the CWD to the dir of the selected node............|NERDTree-cd| ++cd.......Change the CWD to the directory of the selected node......|NERDTree-cd| + CD.......Change tree root to the CWD...............................|NERDTree-CD| + + I........Toggle whether hidden files displayed......................|NERDTree-I| +@@ -469,7 +469,7 @@ Jump to the first child of the current nodes parent. + + If the cursor is already on the first node then do the following: + * loop back thru the siblings of the current nodes parent until we find an +- open dir with children ++ open directory with children + * go to the first child of that node + + ------------------------------------------------------------------------------ +@@ -482,7 +482,7 @@ Jump to the last child of the current nodes parent. + + If the cursor is already on the last node then do the following: + * loop forward thru the siblings of the current nodes parent until we find +- an open dir with children ++ an open directory with children + * go to the last child of that node + + ------------------------------------------------------------------------------ +@@ -516,7 +516,7 @@ Default key: u + Map setting: *NERDTreeMapUpdir* + Applies to: no restrictions. + +-Move the tree root up a dir (like doing a "cd .."). ++Move the tree root up a directory (like doing a "cd .."). + + ------------------------------------------------------------------------------ + *NERDTree-U* +@@ -532,8 +532,8 @@ Default key: r + Map setting: *NERDTreeMapRefresh* + Applies to: files and directories. + +-If a dir is selected, recursively refresh that dir, i.e. scan the filesystem +-for changes and represent them in the tree. ++If a directory is selected, recursively refresh that directory, i.e. scan the ++filesystem for changes and represent them in the tree. + + If a file node is selected then the above is done on it's parent. + +@@ -634,8 +634,8 @@ file explorers have. + + The script comes with two default menu plugins: exec_menuitem.vim and + fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for +-creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a +-menu item to execute executable files. ++creating/deleting/moving/copying files and directories. exec_menuitem.vim ++provides a menu item to execute executable files. + + Related tags: |NERDTree-m| |NERDTreeApi| + +@@ -921,7 +921,7 @@ Default: ['\~$']. + + This setting is used to specify which files the NERDTree should ignore. It + must be a list of regular expressions. When the NERDTree is rendered, any +-files/dirs that match any of the regex's in NERDTreeIgnore won't be ++files/directories that match any of the regex's in NERDTreeIgnore won't be + displayed. + + For example if you put the following line in your vimrc: > +@@ -929,13 +929,18 @@ For example if you put the following line in your vimrc: > + < + then all files ending in .vim or ~ will be ignored. + +-There are 2 magic flags that can be appended to the end of each regular +-expression to specify that the regex should match only files or only dirs. +-These flags are "[[dir]]" and "[[file]]". Example: > +- let NERDTreeIgnore=['\.d$[[dir]]', '\.o$[[file]]'] ++There are 3 magic flags that can be appended to the end of each regular ++expression to specify that the regex should match only filenames, only lowest ++level directories, or a full path. These flags are "[[dir]]", "[[file]]", and ++"[[path]]". Example: > ++ let NERDTreeIgnore=['\.d$[[dir]]', '\.o$[[file]]', 'tmp/cache$[[path]]'] + < +-This will cause all dirs ending in ".d" to be ignored and all files ending in +-".o" to be ignored. ++This will cause all directories ending in ".d" to be ignored, all files ending ++in ".o" to be ignored, and the "cache" subdirectory of any "tmp" directory to ++be ignored. All other "cache" directories will be displayed. ++ ++When using the "[[path]]" tag on Windows, make sure you use escaped ++backslashes for the separators in the regex, eg. 'Temp\\cache$[[path]]' + + Note: to tell the NERDTree not to ignore any files you must use the following + line: > +@@ -1099,8 +1104,8 @@ Examples: > + < + 1. Directories will appear last, everything else will appear above. + 2. Everything will simply appear in alphabetical order. +-3. Dirs will appear first, then ruby and php. Swap files, bak files and vim +- backup files will appear last with everything else preceding them. ++3. Directories will appear first, then ruby and php. Swap files, bak files ++ and vim backup files will appear last with everything else preceding them. + 4. Everything is sorted by size, largest to smallest, with directories + considered to have size 0 bytes. + 5. Directories will appear first alphabetically, followed by files, sorted by +@@ -1174,8 +1179,9 @@ Use one of the following lines for this setting: > + Values: 0 or 1 + Default: 1. + +-When displaying dir nodes, this setting tells NERDTree to collapse dirs that +-have only one child. Use one of the following lines for this setting: > ++When displaying directory nodes, this setting tells NERDTree to collapse ++directories that have only one child. Use one of the following lines for this ++setting: > + let NERDTreeCascadeSingleChildDir=0 + let NERDTreeCascadeSingleChildDir=1 + < +@@ -1184,11 +1190,12 @@ have only one child. Use one of the following lines for this setting: > + Values: 0 or 1 + Default: 1. + +-When opening dir nodes, this setting tells NERDTree to recursively open dirs +-that have only one child which is also a dir. NERDTree will stop when it finds +-a dir that contains anything but another single dir. This setting also causes +-the |NERDTree-x| mapping to close dirs in the same manner. This setting may be +-useful for Java projects. Use one of the following lines for this setting: > ++When opening directory nodes, this setting tells NERDTree to recursively open ++directories that have only one child which is also a directory. NERDTree will ++stop when it finds a directory that contains anything but another single ++directory. This setting also causes the |NERDTree-x| mapping to close ++directories in the same manner. This setting may be useful for Java projects. ++Use one of the following lines for this setting: > + let NERDTreeCascadeOpenSingleChildDir=0 + let NERDTreeCascadeOpenSingleChildDir=1 + < +@@ -1362,8 +1369,8 @@ NERDTreeAddKeyMap({options}) *NERDTreeAddKeyMap()* + < + This code should sit in a file like ~/.vim/nerdtree_plugin/mymapping.vim. + It adds a (redundant) mapping on 'foo' which changes vim's CWD to that of +- the current dir node. Note this mapping will only fire when the cursor is +- on a directory node. ++ the current directory node. Note this mapping will only fire when the ++ cursor is on a directory node. + + ------------------------------------------------------------------------------ + 4.2. Menu API *NERDTreeMenuAPI* +diff --git a/lib/nerdtree/path.vim b/lib/nerdtree/path.vim +index 786ccd9..26749c6 100644 +--- a/lib/nerdtree/path.vim ++++ b/lib/nerdtree/path.vim +@@ -483,7 +483,10 @@ endfunction + " returns true if this path matches the given ignore pattern + function! s:Path._ignorePatternMatches(pattern) + let pat = a:pattern +- if strpart(pat,len(pat)-7) ==# '[[dir]]' ++ if strpart(pat,len(pat)-8) ==# '[[path]]' ++ let pat = strpart(pat,0, len(pat)-8) ++ return self.str() =~# pat ++ elseif strpart(pat,len(pat)-7) ==# '[[dir]]' + if !self.isDirectory + return 0 + endif diff --git a/tasks/preservim__nerdtree-1207/tests/test.sh b/tasks/preservim__nerdtree-1207/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b04a5d55b6ae650ce3133b2d2461b373b70277af --- /dev/null +++ b/tasks/preservim__nerdtree-1207/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 7099f638edd3eda5cd5687b4e13d342bb7f9949d > "$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/preservim__nerdtree-1207/tests/verifier.py b/tasks/preservim__nerdtree-1207/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1207/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/preservim__nerdtree-1213/environment/Dockerfile b/tasks/preservim__nerdtree-1213/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee2fca63be1734e93f197d340f21922892d6cc8e --- /dev/null +++ b/tasks/preservim__nerdtree-1213/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b134f6518b902c7e0482ae770b804fd47c2d2426 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b134f6518b902c7e0482ae770b804fd47c2d2426 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b134f6518b902c7e0482ae770b804fd47c2d2426 \ + && 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/preservim__nerdtree-1213/instruction.md b/tasks/preservim__nerdtree-1213/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e83cf44322f1d98013a23393ad72c944e3e6a87 --- /dev/null +++ b/tasks/preservim__nerdtree-1213/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Escape quotation marks so they can be used in key mappings. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b134f6518b90`. 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/preservim__nerdtree-1213/solution/patch.diff b/tasks/preservim__nerdtree-1213/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f270b42546ebfe63837a28932e7292d5fd062efb --- /dev/null +++ b/tasks/preservim__nerdtree-1213/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e5783e6..8d8eef9 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 + - **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) +diff --git a/lib/nerdtree/key_map.vim b/lib/nerdtree/key_map.vim +index f3268c2..e6afb82 100644 +--- a/lib/nerdtree/key_map.vim ++++ b/lib/nerdtree/key_map.vim +@@ -51,7 +51,7 @@ function! s:KeyMap.bind() + else + let keymapInvokeString = self.key + endif +- let keymapInvokeString = escape(keymapInvokeString, '\') ++ let keymapInvokeString = escape(keymapInvokeString, '\"') + + let premap = self.key ==# '' ? ' ' : ' ' + diff --git a/tasks/preservim__nerdtree-1213/solution/solve.sh b/tasks/preservim__nerdtree-1213/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1213/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/preservim__nerdtree-1213/task.toml b/tasks/preservim__nerdtree-1213/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..11ca71cf17fca72abb71a759a5674578b13b2bbe --- /dev/null +++ b/tasks/preservim__nerdtree-1213/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1213" +description = "Escape quotation marks so they can be used in key mappings." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "b134f6518b902c7e0482ae770b804fd47c2d2426" +reference = "https://github.com/preservim/nerdtree/pull/1213" +source_access = "auto" +built_at = "2026-11-16T16:10:02.386023+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9fcf64842fb76228b7e3fe7a1fcbb5ecc9725037b68f0c3698383ee194694302" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-31T04:43:30Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "lib/nerdtree/key_map.vim", +] +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:02.591573+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:93fe734280d92c9b73591430686c5100d3d2c2d28dc068b041efa78223f11696" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1213/tests/capture.py b/tasks/preservim__nerdtree-1213/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1213/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/preservim__nerdtree-1213/tests/instruction.md b/tasks/preservim__nerdtree-1213/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e83cf44322f1d98013a23393ad72c944e3e6a87 --- /dev/null +++ b/tasks/preservim__nerdtree-1213/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Escape quotation marks so they can be used in key mappings. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b134f6518b90`. 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/preservim__nerdtree-1213/tests/oracle.patch b/tasks/preservim__nerdtree-1213/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f270b42546ebfe63837a28932e7292d5fd062efb --- /dev/null +++ b/tasks/preservim__nerdtree-1213/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index e5783e6..8d8eef9 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 + - **.12**: Respect NERDTreeCustomOpenArgs when opening bookmark (przepompownia) [#1200](https://github.com/preservim/nerdtree/pull/1200) +diff --git a/lib/nerdtree/key_map.vim b/lib/nerdtree/key_map.vim +index f3268c2..e6afb82 100644 +--- a/lib/nerdtree/key_map.vim ++++ b/lib/nerdtree/key_map.vim +@@ -51,7 +51,7 @@ function! s:KeyMap.bind() + else + let keymapInvokeString = self.key + endif +- let keymapInvokeString = escape(keymapInvokeString, '\') ++ let keymapInvokeString = escape(keymapInvokeString, '\"') + + let premap = self.key ==# '' ? ' ' : ' ' + diff --git a/tasks/preservim__nerdtree-1213/tests/test.sh b/tasks/preservim__nerdtree-1213/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ebad879e7eb98d1accf72b47fcb79f457ad92af1 --- /dev/null +++ b/tasks/preservim__nerdtree-1213/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 b134f6518b902c7e0482ae770b804fd47c2d2426 > "$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/preservim__nerdtree-1213/tests/verifier.py b/tasks/preservim__nerdtree-1213/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1213/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/preservim__nerdtree-1214/environment/Dockerfile b/tasks/preservim__nerdtree-1214/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2ce4a5185a8a644a7824618335dea15dd0432664 --- /dev/null +++ b/tasks/preservim__nerdtree-1214/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 628098fff1d75ad104934009b4ce60c4e23204ec 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 628098fff1d75ad104934009b4ce60c4e23204ec \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 628098fff1d75ad104934009b4ce60c4e23204ec \ + && 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/preservim__nerdtree-1214/instruction.md b/tasks/preservim__nerdtree-1214/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..672ea22163aa90ed23f133f5baee5b9f07a7b5aa --- /dev/null +++ b/tasks/preservim__nerdtree-1214/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** New menu command: Run a system command in this directory. + +## Description + +### Description of Changes + + +Invoking this menu option - `m`, `s` - will prompt the user for a command to run in the selected directory (or the file's directory). If the command produces any output, it is echoed back to the screen. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `628098fff1d7`. 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/preservim__nerdtree-1214/solution/patch.diff b/tasks/preservim__nerdtree-1214/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9e1f399208ce3a41b407369cf5b97b6badfdadd1 --- /dev/null +++ b/tasks/preservim__nerdtree-1214/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8d8eef9..1192d48 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.2**: New menu command: Run a system command in this directory. (PhilRunninger) [#1214](https://github.com/preservim/nerdtree/pull/1214) + - **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index b3ef42e..09cb69b 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -49,6 +49,10 @@ else + call NERDTreeAddMenuItem({'text': '(l)ist the current node', 'shortcut': 'l', 'callback': 'NERDTreeListNodeWin32'}) + endif + ++if exists('*system') ++ call NERDTreeAddMenuItem({'text': 'Run (s)ystem command in this directory', 'shortcut':'s', 'callback': 'NERDTreeSystemCommand'}) ++endif ++ + "FUNCTION: s:inputPrompt(action){{{1 + "returns the string that should be prompted to the user for the given action + " +@@ -460,4 +464,21 @@ function! NERDTreeExecuteFileWindows() + call system('cmd.exe /c start "" ' . shellescape(l:node.path.str())) + endfunction + ++" FUNCTION: NERDTreeSystemCommand() {{{1 ++function! NERDTreeSystemCommand() ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ let l:cwd = getcwd() ++ let l:directory = l:node.path.isDirectory ? l:node.path.str() : l:node.parent.path.str() ++ execute 'cd '.l:directory ++ ++ let l:nl = nr2char(10) ++ echo l:nl . system(input(l:directory . (nerdtree#runningWindows() ? '> ' : ' $ '))) ++ execute 'cd '.l:cwd ++endfunction ++ + " vim: set sw=4 sts=4 et fdm=marker: diff --git a/tasks/preservim__nerdtree-1214/solution/solve.sh b/tasks/preservim__nerdtree-1214/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1214/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/preservim__nerdtree-1214/task.toml b/tasks/preservim__nerdtree-1214/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..126db61c2a7dbb37aad3120b200b1f91d1baa18a --- /dev/null +++ b/tasks/preservim__nerdtree-1214/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1214" +description = "New menu command: Run a system command in this directory." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "628098fff1d75ad104934009b4ce60c4e23204ec" +reference = "https://github.com/preservim/nerdtree/pull/1214" +source_access = "auto" +built_at = "2026-11-16T16:10:02.387433+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dfd1a0cbe7cfbe5a58b60d94dd201b10489e5c4a0c2837df39532b474629a9c5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-31T04:45:57Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "nerdtree_plugin/fs_menu.vim", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 22 +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:02.592088+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d8c38bd131b3655725031faba25fdf2556230c3278641627f6f4540d5afc0c6b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1214/tests/capture.py b/tasks/preservim__nerdtree-1214/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1214/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/preservim__nerdtree-1214/tests/instruction.md b/tasks/preservim__nerdtree-1214/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..672ea22163aa90ed23f133f5baee5b9f07a7b5aa --- /dev/null +++ b/tasks/preservim__nerdtree-1214/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** New menu command: Run a system command in this directory. + +## Description + +### Description of Changes + + +Invoking this menu option - `m`, `s` - will prompt the user for a command to run in the selected directory (or the file's directory). If the command produces any output, it is echoed back to the screen. + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `628098fff1d7`. 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/preservim__nerdtree-1214/tests/oracle.patch b/tasks/preservim__nerdtree-1214/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9e1f399208ce3a41b407369cf5b97b6badfdadd1 --- /dev/null +++ b/tasks/preservim__nerdtree-1214/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 8d8eef9..1192d48 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.2**: New menu command: Run a system command in this directory. (PhilRunninger) [#1214](https://github.com/preservim/nerdtree/pull/1214) + - **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) + #### 6.9 +diff --git a/nerdtree_plugin/fs_menu.vim b/nerdtree_plugin/fs_menu.vim +index b3ef42e..09cb69b 100644 +--- a/nerdtree_plugin/fs_menu.vim ++++ b/nerdtree_plugin/fs_menu.vim +@@ -49,6 +49,10 @@ else + call NERDTreeAddMenuItem({'text': '(l)ist the current node', 'shortcut': 'l', 'callback': 'NERDTreeListNodeWin32'}) + endif + ++if exists('*system') ++ call NERDTreeAddMenuItem({'text': 'Run (s)ystem command in this directory', 'shortcut':'s', 'callback': 'NERDTreeSystemCommand'}) ++endif ++ + "FUNCTION: s:inputPrompt(action){{{1 + "returns the string that should be prompted to the user for the given action + " +@@ -460,4 +464,21 @@ function! NERDTreeExecuteFileWindows() + call system('cmd.exe /c start "" ' . shellescape(l:node.path.str())) + endfunction + ++" FUNCTION: NERDTreeSystemCommand() {{{1 ++function! NERDTreeSystemCommand() ++ let l:node = g:NERDTreeFileNode.GetSelected() ++ ++ if empty(l:node) ++ return ++ endif ++ ++ let l:cwd = getcwd() ++ let l:directory = l:node.path.isDirectory ? l:node.path.str() : l:node.parent.path.str() ++ execute 'cd '.l:directory ++ ++ let l:nl = nr2char(10) ++ echo l:nl . system(input(l:directory . (nerdtree#runningWindows() ? '> ' : ' $ '))) ++ execute 'cd '.l:cwd ++endfunction ++ + " vim: set sw=4 sts=4 et fdm=marker: diff --git a/tasks/preservim__nerdtree-1214/tests/test.sh b/tasks/preservim__nerdtree-1214/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b25efb46635c301f2a38dc50044947fec33924eb --- /dev/null +++ b/tasks/preservim__nerdtree-1214/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 628098fff1d75ad104934009b4ce60c4e23204ec > "$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/preservim__nerdtree-1214/tests/verifier.py b/tasks/preservim__nerdtree-1214/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/preservim__nerdtree-1214/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/preservim__nerdtree-1215/environment/Dockerfile b/tasks/preservim__nerdtree-1215/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..85ac31a35c4ff6efdad87d6ff6ad2a31acdf6c3d --- /dev/null +++ b/tasks/preservim__nerdtree-1215/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/preservim/nerdtree.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/preservim/nerdtree.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/preservim/nerdtree.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c8be9458dddb986dc17a3f5a00aaf29cd60b1b5f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c8be9458dddb986dc17a3f5a00aaf29cd60b1b5f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c8be9458dddb986dc17a3f5a00aaf29cd60b1b5f \ + && 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/preservim__nerdtree-1215/instruction.md b/tasks/preservim__nerdtree-1215/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45f3231d8b9e5106a0c6dbbefc63ca1254e6dbc7 --- /dev/null +++ b/tasks/preservim__nerdtree-1215/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add new FAQ and answer: How to prevent buffers replacing NERDTree. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c8be9458dddb`. 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/preservim__nerdtree-1215/solution/patch.diff b/tasks/preservim__nerdtree-1215/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ba750787490fe7919394af14f3133e49d3a92b4a --- /dev/null +++ b/tasks/preservim__nerdtree-1215/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 1192d48..409d631 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.3**: Add new FAQ and answer: How to prevent buffers replacing NERDTree. (PhilRunninger) [#1215](https://github.com/preservim/nerdtree/pull/1215) + - **.2**: New menu command: Run a system command in this directory. (PhilRunninger) [#1214](https://github.com/preservim/nerdtree/pull/1214) + - **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) +diff --git a/README.markdown b/README.markdown +index 7c6ba3c..843ebe2 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -156,6 +156,14 @@ autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTr + \ quit | endif + ``` + ++### How can I prevent other buffers replacing NERDTree in its window? ++ ++```vim ++" If another buffer tries to replace NERDTree, put in the other window, and bring back NERDTree. ++autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 | ++ \ let buf=bufnr() | buffer# | execute "normal! \w" | execute 'buffer'.buf | endif ++``` ++ + ### Can I have the same NERDTree on every tab automatically? + + ```vim diff --git a/tasks/preservim__nerdtree-1215/solution/solve.sh b/tasks/preservim__nerdtree-1215/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/preservim__nerdtree-1215/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/preservim__nerdtree-1215/task.toml b/tasks/preservim__nerdtree-1215/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e0c78ece38d281bdb411c3c2dc3048f3064ddf8 --- /dev/null +++ b/tasks/preservim__nerdtree-1215/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/preservim__nerdtree-1215" +description = "Add new FAQ and answer: How to prevent buffers replacing NERDTree." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "nerdtree", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "preservim/nerdtree" +ref = "c8be9458dddb986dc17a3f5a00aaf29cd60b1b5f" +reference = "https://github.com/preservim/nerdtree/pull/1215" +source_access = "auto" +built_at = "2026-11-16T16:10:02.384601+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7a97ebaf994dff9cef943164710ab095071bbe99b155c0e0440a6e83be0a230a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2021-01-31T05:19:59Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "README.markdown", +] +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:02.592612+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:349cac958ad84450903d1850b07ccd14589db4f5efad39b34cc8366bc89ef65b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/preservim__nerdtree-1215/tests/capture.py b/tasks/preservim__nerdtree-1215/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/preservim__nerdtree-1215/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/preservim__nerdtree-1215/tests/instruction.md b/tasks/preservim__nerdtree-1215/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45f3231d8b9e5106a0c6dbbefc63ca1254e6dbc7 --- /dev/null +++ b/tasks/preservim__nerdtree-1215/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add new FAQ and answer: How to prevent buffers replacing NERDTree. + +## Description + +### Description of Changes + + + +--- +### New Version Info + +#### Author's Instructions +- [x] Derive a new `MAJOR.MINOR.PATCH` version number. Increment the: + - `MAJOR` version when you make incompatible API changes + - `MINOR` version when you add functionality in a backwards-compatible manner + - `PATCH` version when you make backwards-compatible bug fixes +- [x] Update [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), following the established pattern. +#### Collaborator's Instructions +- [x] Review [CHANGELOG.md](https://github.com/scrooloose/nerdtree/blob/master/CHANGELOG.md), suggesting a different version number if necessary. +- [x] After merging, tag the commit using these (Mac-compatible) bash commands: + ```bash + git checkout master + git pull + sed -n "$(grep -n -m2 '####' CHANGELOG.md | cut -f1 -d: | sed 'N;s/\n/,/')p" CHANGELOG.md | sed '$d' + git tag -a $(read -p "Tag Name: " tag;echo $tag) -m"$(git show --quiet --pretty=%s)";git push origin --tags + ``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c8be9458dddb`. 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/preservim__nerdtree-1215/tests/oracle.patch b/tasks/preservim__nerdtree-1215/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ba750787490fe7919394af14f3133e49d3a92b4a --- /dev/null +++ b/tasks/preservim__nerdtree-1215/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index 1192d48..409d631 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -5,6 +5,7 @@ + - **.PATCH**: Pull Request Title (PR Author) [PR Number](Link to PR) + --> + #### 6.10 ++- **.3**: Add new FAQ and answer: How to prevent buffers replacing NERDTree. (PhilRunninger) [#1215](https://github.com/preservim/nerdtree/pull/1215) + - **.2**: New menu command: Run a system command in this directory. (PhilRunninger) [#1214](https://github.com/preservim/nerdtree/pull/1214) + - **.1**: Escape quotation marks so they can be used in key mappings. (PhilRunninger) [#1213](https://github.com/preservim/nerdtree/pull/1213) + - **.0**: Enable full path specifications for NERDTreeIgnore (PhilRunninger) [#1207](https://github.com/preservim/nerdtree/pull/1207) +diff --git a/README.markdown b/README.markdown +index 7c6ba3c..843ebe2 100644 +--- a/README.markdown ++++ b/README.markdown +@@ -156,6 +156,14 @@ autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTr + \ quit | endif + ``` + ++### How can I prevent other buffers replacing NERDTree in its window? ++ ++```vim ++" If another buffer tries to replace NERDTree, put in the other window, and bring back NERDTree. ++autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 | ++ \ let buf=bufnr() | buffer# | execute "normal! \w" | execute 'buffer'.buf | endif ++``` ++ + ### Can I have the same NERDTree on every tab automatically? + + ```vim