diff --git a/tasks/lite-xl__lite-xl-1039/tests/test.sh b/tasks/lite-xl__lite-xl-1039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..64fc8e5ea325ee0c184dfbb60c63557d4b38836f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1039/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 2d412ef64a76c1ba6f41786577061f5fd320e217 > "$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/lite-xl__lite-xl-1039/tests/verifier.py b/tasks/lite-xl__lite-xl-1039/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1039/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/lite-xl__lite-xl-1041/environment/Dockerfile b/tasks/lite-xl__lite-xl-1041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c6de59a6fdb6bf80efcab2344dd82048912370e4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 380cfb9a24fd3d6f671322dc74fb9b55650739cb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 380cfb9a24fd3d6f671322dc74fb9b55650739cb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 380cfb9a24fd3d6f671322dc74fb9b55650739cb \ + && 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/lite-xl__lite-xl-1041/instruction.md b/tasks/lite-xl__lite-xl-1041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7f9e05129f65b2c835926c4c39777e522676025 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Support UTF-8 on Windows (Lua) + +## Description + +This PR provides a patch and a corresponding option in `build.sh` to apply it. + +The changes allow lite-xl to launch from a directory containing non-ASCII characters and save/load files with non-ASCII filenames among other things. + +The changes are listed on [this page]. + +The way to test this is to run `./scripts/build.sh -U -f` and a patched version should be applied to `subproject/lua-*/`. + +After that, you can run lite-xl with a unicode filename from the command line (this is currently the easiest option, because treeview doesn't support unicode yet) and try to save said file. + +Inspect said file in File Explorer. If the file is saved incorrectly (without this patch), the filename will be garbled. +Example: +![image](https://user-images.githubusercontent.com/20792268/173999686-338ca354-6b36-48a8-aecf-272ebd4b20dd.png) + + +[this page]: https://github.com/takase1121/lua-unicode + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `380cfb9a24fd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1041/solution/patch.diff b/tasks/lite-xl__lite-xl-1041/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7c8dd6b4a7f3da3fd3a7cb5df8b53a9536a3d320 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/solution/patch.diff @@ -0,0 +1,256 @@ +diff --git a/.gitignore b/.gitignore +index 75dec714..13052b48 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -17,3 +17,5 @@ compile_commands.json + error.txt + lite-xl* + LiteXL* ++ ++!resources/windows/*.diff +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +new file mode 100644 +index 00000000..8306d354 +--- /dev/null ++++ b/resources/windows/001-lua-unicode.diff +@@ -0,0 +1,195 @@ ++diff -ruN lua-5.4.3/meson.build newlua/meson.build ++--- lua-5.4.3/meson.build 2022-05-29 21:04:17.850449500 +0800 +++++ newlua/meson.build 2022-06-10 19:23:55.685139800 +0800 ++@@ -82,6 +82,7 @@ ++ 'src/lutf8lib.c', ++ 'src/lvm.c', ++ 'src/lzio.c', +++ 'src/utf8_wrappers.c', ++ dependencies: lua_lib_deps, ++ override_options: project_options, ++ implicit_include_directories: false, ++Binary files lua-5.4.3/src/lua54.dll and newlua/src/lua54.dll differ ++diff -ruN lua-5.4.3/src/luaconf.h newlua/src/luaconf.h ++--- lua-5.4.3/src/luaconf.h 2021-03-15 21:32:52.000000000 +0800 +++++ newlua/src/luaconf.h 2022-06-10 19:15:03.014745300 +0800 ++@@ -786,5 +786,15 @@ ++ ++ ++ +++#if defined(lua_c) || defined(luac_c) || (defined(LUA_LIB) && \ +++ (defined(lauxlib_c) || defined(liolib_c) || \ +++ defined(loadlib_c) || defined(loslib_c))) +++#include "utf8_wrappers.h" +++#endif +++ +++ +++ +++ +++ ++ #endif ++ ++diff -ruN lua-5.4.3/src/Makefile newlua/src/Makefile ++--- lua-5.4.3/src/Makefile 2021-02-10 02:47:17.000000000 +0800 +++++ newlua/src/Makefile 2022-06-10 19:22:45.267931400 +0800 ++@@ -33,7 +33,7 @@ ++ PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris ++ ++ LUA_A= liblua.a ++-CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +++CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o ++ LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o ++ BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) ++ ++ ++diff -ruN lua-5.4.3/src/utf8_wrappers.c newlua/src/utf8_wrappers.c ++--- lua-5.4.3/src/utf8_wrappers.c 1970-01-01 07:30:00.000000000 +0730 +++++ newlua/src/utf8_wrappers.c 2022-06-10 19:13:11.904613300 +0800 ++@@ -0,0 +1,101 @@ +++/** +++ * Wrappers to provide Unicode (UTF-8) support on Windows. +++ * +++ * Copyright (c) 2018 Peter Wu +++ * SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +++ */ +++ +++#ifdef _WIN32 +++#include /* for MultiByteToWideChar */ +++#include /* for _wrename */ +++#include +++#include +++#include +++ +++// Set a high limit in case long paths are enabled. +++#define MAX_PATH_SIZE 4096 +++#define MAX_MODE_SIZE 128 +++// cmd.exe argument length is reportedly limited to 8192. +++#define MAX_CMD_SIZE 8192 +++ +++FILE *fopen_utf8(const char *pathname, const char *mode) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wfopen(pathname_w, mode_w); +++} +++ +++FILE *freopen_utf8(const char *pathname, const char *mode, FILE *stream) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ // Close stream as documented for the error case. +++ fclose(stream); +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wfreopen(pathname_w, mode_w, stream); +++} +++ +++int remove_utf8(const char *pathname) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wremove(pathname_w); +++} +++ +++int rename_utf8(const char *oldpath, const char *newpath) { +++ wchar_t oldpath_w[MAX_PATH_SIZE]; +++ wchar_t newpath_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, oldpath, -1, oldpath_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, newpath, -1, newpath_w, MAX_PATH_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wrename(oldpath_w, newpath_w); +++} +++ +++FILE *popen_utf8(const char *command, const char *mode) { +++ wchar_t command_w[MAX_CMD_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, command, -1, command_w, MAX_CMD_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wpopen(command_w, mode_w); +++} +++ +++int system_utf8(const char *command) { +++ wchar_t command_w[MAX_CMD_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, command, -1, command_w, MAX_CMD_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wsystem(command_w); +++} +++ +++DWORD GetModuleFileNameA_utf8(HMODULE hModule, LPSTR lpFilename, DWORD nSize) { +++ wchar_t filename_w[MAX_PATH + 1]; +++ if (!GetModuleFileNameW(hModule, filename_w, MAX_PATH + 1)) { +++ return 0; +++ } +++ return WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, filename_w, -1, lpFilename, nSize, NULL, NULL); +++} +++ +++HMODULE LoadLibraryExA_utf8(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, lpLibFileName, -1, pathname_w, MAX_PATH_SIZE)) { +++ SetLastError(ERROR_INVALID_NAME); +++ return NULL; +++ } +++ return LoadLibraryExW(pathname_w, hFile, dwFlags); +++} +++#endif ++diff -ruN lua-5.4.3/src/utf8_wrappers.h newlua/src/utf8_wrappers.h ++--- lua-5.4.3/src/utf8_wrappers.h 1970-01-01 07:30:00.000000000 +0730 +++++ newlua/src/utf8_wrappers.h 2022-06-10 19:22:53.554879400 +0800 ++@@ -0,0 +1,42 @@ +++/** +++ * Wrappers to provide Unicode (UTF-8) support on Windows. +++ * +++ * Copyright (c) 2018 Peter Wu +++ * SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +++ */ +++ +++#ifdef _WIN32 +++ +++#if defined(loadlib_c) || defined(lauxlib_c) || defined(liolib_c) || defined(luac_c) +++#include /* for loadlib_c */ +++FILE *fopen_utf8(const char *pathname, const char *mode); +++#define fopen fopen_utf8 +++#endif +++ +++#ifdef lauxlib_c +++FILE *freopen_utf8(const char *pathname, const char *mode, FILE *stream); +++#define freopen freopen_utf8 +++#endif +++ +++#ifdef liolib_c +++FILE *popen_utf8(const char *command, const char *mode); +++#define _popen popen_utf8 +++#endif +++ +++#ifdef loslib_c +++int remove_utf8(const char *pathname); +++int rename_utf8(const char *oldpath, const char *newpath); +++int system_utf8(const char *command); +++#define remove remove_utf8 +++#define rename rename_utf8 +++#define system system_utf8 +++#endif +++ +++#ifdef loadlib_c +++#include +++DWORD GetModuleFileNameA_utf8(HMODULE hModule, LPSTR lpFilename, DWORD nSize); +++HMODULE LoadLibraryExA_utf8(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); +++#define GetModuleFileNameA GetModuleFileNameA_utf8 +++#define LoadLibraryExA LoadLibraryExA_utf8 +++#endif +++#endif +diff --git a/scripts/build.sh b/scripts/build.sh +index 75212468..c1df96f7 100644 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -22,6 +22,7 @@ show_help() { + echo "-B --bundle Create an App bundle (macOS only)" + echo "-P --portable Create a portable binary package." + echo "-O --pgo Use profile guided optimizations (pgo)." ++ echo "-U --windows-lua-utf Use the UTF8 patch for Lua." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." + echo +@@ -35,6 +36,9 @@ main() { + local bundle + local portable + local pgo ++ local patch_lua ++ ++ local lua_subproject_path + + for i in "$@"; do + case $i in +@@ -76,6 +80,10 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; ++ -U|--windows-lua-utf) ++ patch_lua="true" ++ shift ++ ;; + *) + # unknown option + ;; +@@ -103,6 +111,11 @@ main() { + $pgo \ + "${build_dir}" + ++ lua_subproject_path=subprojects/lua-*/ ++ if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]] && [[ -d $lua_subproject_path ]]; then ++ patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff ++ fi ++ + meson compile -C "${build_dir}" + + if [ ! -z ${pgo+x} ]; then diff --git a/tasks/lite-xl__lite-xl-1041/solution/solve.sh b/tasks/lite-xl__lite-xl-1041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/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/lite-xl__lite-xl-1041/task.toml b/tasks/lite-xl__lite-xl-1041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6cecf0309b4ccd88914204191ff84a35773e8e15 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1041" +description = "Support UTF-8 on Windows (Lua)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "380cfb9a24fd3d6f671322dc74fb9b55650739cb" +reference = "https://github.com/lite-xl/lite-xl/pull/1041" +source_access = "auto" +built_at = "2026-11-16T16:09:56.265174+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4a583af226bc53e74741681a7fae09660a82cf8e31c97a50d853db9df47c3206" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-06-17T13:47:02Z" +diff_format = "unified" +context_files = [ + ".gitignore", + "resources/windows/001-lua-unicode.diff", + "scripts/build.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 210 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.275527+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a6ff1dd67aecc0e82bdd912d2d70b703bf30ae0f068e916ab290664d37560057" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1041/tests/capture.py b/tasks/lite-xl__lite-xl-1041/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/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/lite-xl__lite-xl-1041/tests/instruction.md b/tasks/lite-xl__lite-xl-1041/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7f9e05129f65b2c835926c4c39777e522676025 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Support UTF-8 on Windows (Lua) + +## Description + +This PR provides a patch and a corresponding option in `build.sh` to apply it. + +The changes allow lite-xl to launch from a directory containing non-ASCII characters and save/load files with non-ASCII filenames among other things. + +The changes are listed on [this page]. + +The way to test this is to run `./scripts/build.sh -U -f` and a patched version should be applied to `subproject/lua-*/`. + +After that, you can run lite-xl with a unicode filename from the command line (this is currently the easiest option, because treeview doesn't support unicode yet) and try to save said file. + +Inspect said file in File Explorer. If the file is saved incorrectly (without this patch), the filename will be garbled. +Example: +![image](https://user-images.githubusercontent.com/20792268/173999686-338ca354-6b36-48a8-aecf-272ebd4b20dd.png) + + +[this page]: https://github.com/takase1121/lua-unicode + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `380cfb9a24fd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1041/tests/oracle.patch b/tasks/lite-xl__lite-xl-1041/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7c8dd6b4a7f3da3fd3a7cb5df8b53a9536a3d320 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/tests/oracle.patch @@ -0,0 +1,256 @@ +diff --git a/.gitignore b/.gitignore +index 75dec714..13052b48 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -17,3 +17,5 @@ compile_commands.json + error.txt + lite-xl* + LiteXL* ++ ++!resources/windows/*.diff +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +new file mode 100644 +index 00000000..8306d354 +--- /dev/null ++++ b/resources/windows/001-lua-unicode.diff +@@ -0,0 +1,195 @@ ++diff -ruN lua-5.4.3/meson.build newlua/meson.build ++--- lua-5.4.3/meson.build 2022-05-29 21:04:17.850449500 +0800 +++++ newlua/meson.build 2022-06-10 19:23:55.685139800 +0800 ++@@ -82,6 +82,7 @@ ++ 'src/lutf8lib.c', ++ 'src/lvm.c', ++ 'src/lzio.c', +++ 'src/utf8_wrappers.c', ++ dependencies: lua_lib_deps, ++ override_options: project_options, ++ implicit_include_directories: false, ++Binary files lua-5.4.3/src/lua54.dll and newlua/src/lua54.dll differ ++diff -ruN lua-5.4.3/src/luaconf.h newlua/src/luaconf.h ++--- lua-5.4.3/src/luaconf.h 2021-03-15 21:32:52.000000000 +0800 +++++ newlua/src/luaconf.h 2022-06-10 19:15:03.014745300 +0800 ++@@ -786,5 +786,15 @@ ++ ++ ++ +++#if defined(lua_c) || defined(luac_c) || (defined(LUA_LIB) && \ +++ (defined(lauxlib_c) || defined(liolib_c) || \ +++ defined(loadlib_c) || defined(loslib_c))) +++#include "utf8_wrappers.h" +++#endif +++ +++ +++ +++ +++ ++ #endif ++ ++diff -ruN lua-5.4.3/src/Makefile newlua/src/Makefile ++--- lua-5.4.3/src/Makefile 2021-02-10 02:47:17.000000000 +0800 +++++ newlua/src/Makefile 2022-06-10 19:22:45.267931400 +0800 ++@@ -33,7 +33,7 @@ ++ PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris ++ ++ LUA_A= liblua.a ++-CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +++CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o ++ LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o ++ BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) ++ ++ ++diff -ruN lua-5.4.3/src/utf8_wrappers.c newlua/src/utf8_wrappers.c ++--- lua-5.4.3/src/utf8_wrappers.c 1970-01-01 07:30:00.000000000 +0730 +++++ newlua/src/utf8_wrappers.c 2022-06-10 19:13:11.904613300 +0800 ++@@ -0,0 +1,101 @@ +++/** +++ * Wrappers to provide Unicode (UTF-8) support on Windows. +++ * +++ * Copyright (c) 2018 Peter Wu +++ * SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +++ */ +++ +++#ifdef _WIN32 +++#include /* for MultiByteToWideChar */ +++#include /* for _wrename */ +++#include +++#include +++#include +++ +++// Set a high limit in case long paths are enabled. +++#define MAX_PATH_SIZE 4096 +++#define MAX_MODE_SIZE 128 +++// cmd.exe argument length is reportedly limited to 8192. +++#define MAX_CMD_SIZE 8192 +++ +++FILE *fopen_utf8(const char *pathname, const char *mode) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wfopen(pathname_w, mode_w); +++} +++ +++FILE *freopen_utf8(const char *pathname, const char *mode, FILE *stream) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ // Close stream as documented for the error case. +++ fclose(stream); +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wfreopen(pathname_w, mode_w, stream); +++} +++ +++int remove_utf8(const char *pathname) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, pathname, -1, pathname_w, MAX_PATH_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wremove(pathname_w); +++} +++ +++int rename_utf8(const char *oldpath, const char *newpath) { +++ wchar_t oldpath_w[MAX_PATH_SIZE]; +++ wchar_t newpath_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, oldpath, -1, oldpath_w, MAX_PATH_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, newpath, -1, newpath_w, MAX_PATH_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wrename(oldpath_w, newpath_w); +++} +++ +++FILE *popen_utf8(const char *command, const char *mode) { +++ wchar_t command_w[MAX_CMD_SIZE]; +++ wchar_t mode_w[MAX_MODE_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, command, -1, command_w, MAX_CMD_SIZE) || +++ !MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, mode, -1, mode_w, MAX_MODE_SIZE)) { +++ errno = EINVAL; +++ return NULL; +++ } +++ return _wpopen(command_w, mode_w); +++} +++ +++int system_utf8(const char *command) { +++ wchar_t command_w[MAX_CMD_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, command, -1, command_w, MAX_CMD_SIZE)) { +++ errno = EINVAL; +++ return -1; +++ } +++ return _wsystem(command_w); +++} +++ +++DWORD GetModuleFileNameA_utf8(HMODULE hModule, LPSTR lpFilename, DWORD nSize) { +++ wchar_t filename_w[MAX_PATH + 1]; +++ if (!GetModuleFileNameW(hModule, filename_w, MAX_PATH + 1)) { +++ return 0; +++ } +++ return WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, filename_w, -1, lpFilename, nSize, NULL, NULL); +++} +++ +++HMODULE LoadLibraryExA_utf8(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { +++ wchar_t pathname_w[MAX_PATH_SIZE]; +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, lpLibFileName, -1, pathname_w, MAX_PATH_SIZE)) { +++ SetLastError(ERROR_INVALID_NAME); +++ return NULL; +++ } +++ return LoadLibraryExW(pathname_w, hFile, dwFlags); +++} +++#endif ++diff -ruN lua-5.4.3/src/utf8_wrappers.h newlua/src/utf8_wrappers.h ++--- lua-5.4.3/src/utf8_wrappers.h 1970-01-01 07:30:00.000000000 +0730 +++++ newlua/src/utf8_wrappers.h 2022-06-10 19:22:53.554879400 +0800 ++@@ -0,0 +1,42 @@ +++/** +++ * Wrappers to provide Unicode (UTF-8) support on Windows. +++ * +++ * Copyright (c) 2018 Peter Wu +++ * SPDX-License-Identifier: (GPL-2.0-or-later OR MIT) +++ */ +++ +++#ifdef _WIN32 +++ +++#if defined(loadlib_c) || defined(lauxlib_c) || defined(liolib_c) || defined(luac_c) +++#include /* for loadlib_c */ +++FILE *fopen_utf8(const char *pathname, const char *mode); +++#define fopen fopen_utf8 +++#endif +++ +++#ifdef lauxlib_c +++FILE *freopen_utf8(const char *pathname, const char *mode, FILE *stream); +++#define freopen freopen_utf8 +++#endif +++ +++#ifdef liolib_c +++FILE *popen_utf8(const char *command, const char *mode); +++#define _popen popen_utf8 +++#endif +++ +++#ifdef loslib_c +++int remove_utf8(const char *pathname); +++int rename_utf8(const char *oldpath, const char *newpath); +++int system_utf8(const char *command); +++#define remove remove_utf8 +++#define rename rename_utf8 +++#define system system_utf8 +++#endif +++ +++#ifdef loadlib_c +++#include +++DWORD GetModuleFileNameA_utf8(HMODULE hModule, LPSTR lpFilename, DWORD nSize); +++HMODULE LoadLibraryExA_utf8(LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags); +++#define GetModuleFileNameA GetModuleFileNameA_utf8 +++#define LoadLibraryExA LoadLibraryExA_utf8 +++#endif +++#endif +diff --git a/scripts/build.sh b/scripts/build.sh +index 75212468..c1df96f7 100644 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -22,6 +22,7 @@ show_help() { + echo "-B --bundle Create an App bundle (macOS only)" + echo "-P --portable Create a portable binary package." + echo "-O --pgo Use profile guided optimizations (pgo)." ++ echo "-U --windows-lua-utf Use the UTF8 patch for Lua." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." + echo +@@ -35,6 +36,9 @@ main() { + local bundle + local portable + local pgo ++ local patch_lua ++ ++ local lua_subproject_path + + for i in "$@"; do + case $i in +@@ -76,6 +80,10 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; ++ -U|--windows-lua-utf) ++ patch_lua="true" ++ shift ++ ;; + *) + # unknown option + ;; +@@ -103,6 +111,11 @@ main() { + $pgo \ + "${build_dir}" + ++ lua_subproject_path=subprojects/lua-*/ ++ if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]] && [[ -d $lua_subproject_path ]]; then ++ patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff ++ fi ++ + meson compile -C "${build_dir}" + + if [ ! -z ${pgo+x} ]; then diff --git a/tasks/lite-xl__lite-xl-1041/tests/test.sh b/tasks/lite-xl__lite-xl-1041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0f03990bd830b6bc23e465bedf8bf47cdf7a74e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/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 380cfb9a24fd3d6f671322dc74fb9b55650739cb > "$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/lite-xl__lite-xl-1041/tests/verifier.py b/tasks/lite-xl__lite-xl-1041/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1041/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/lite-xl__lite-xl-1042/environment/Dockerfile b/tasks/lite-xl__lite-xl-1042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..edd8d318882dd1af5d05e52717094ae9c5d49e08 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3dadbd3a4912897fffc9dceb5dad108d7e700b29 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3dadbd3a4912897fffc9dceb5dad108d7e700b29 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3dadbd3a4912897fffc9dceb5dad108d7e700b29 \ + && 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/lite-xl__lite-xl-1042/instruction.md b/tasks/lite-xl__lite-xl-1042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88a9ff390e63b9b12d3d8b02ae4d814125ca91ae --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** make system.* functions support UTF8 filenames + +## Description + +This PR introduces utfconfv.h which contains 2 function, `utfconv_utf8towc()` and `utfconv_wctoutf8()`. Some of the functions in `system` is converted to convert arguments to WCHAR and use the Windows `*W` APIs. + +Affected functions: +- system.rmdir +- system.chdir +- system.list_dir +- system.absolute_path +- system.get_file_info +- system.mkdir + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3dadbd3a4912`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1042/solution/patch.diff b/tasks/lite-xl__lite-xl-1042/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c51b3c0be7a103165c8ada4cb4d5e9065241d92b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/solution/patch.diff @@ -0,0 +1,308 @@ +diff --git a/src/api/system.c b/src/api/system.c +index ff99ce6f..06d6bafe 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -2,9 +2,8 @@ + #include + #include + #include +-#include +-#include + #include ++#include + #include + #include "api.h" + #include "../rencache.h" +@@ -12,9 +11,16 @@ + #include + #include + #include +-#elif __linux__ ++ #include "../utfconv.h" ++#else ++ ++#include ++#include ++ ++#ifdef __linux__ + #include + #endif ++#endif + + extern SDL_Window *window; + +@@ -125,6 +131,31 @@ static const char *get_key_name(const SDL_Event *e, char *buf) { + } + } + ++#ifdef _WIN32 ++static char *win32_error(DWORD rc) { ++ LPSTR message; ++ FormatMessage( ++ FORMAT_MESSAGE_ALLOCATE_BUFFER | ++ FORMAT_MESSAGE_FROM_SYSTEM | ++ FORMAT_MESSAGE_IGNORE_INSERTS, ++ NULL, ++ rc, ++ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), ++ (LPTSTR) &message, ++ 0, ++ NULL ++ ); ++ ++ return message; ++} ++ ++static void push_win32_error(lua_State *L, DWORD rc) { ++ LPSTR message = win32_error(rc); ++ lua_pushstring(L, message); ++ LocalFree(message); ++} ++#endif ++ + static int f_poll_event(lua_State *L) { + char buf[16]; + int mx, my, wx, wy; +@@ -425,29 +456,14 @@ static int f_rmdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + + #ifdef _WIN32 +- int deleted = RemoveDirectoryA(path); +- if(deleted > 0) { ++ LPWSTR wpath = utfconv_utf8towc(path); ++ int deleted = RemoveDirectoryW(wpath); ++ free(wpath); ++ if (deleted > 0) { + lua_pushboolean(L, 1); + } else { +- DWORD error_code = GetLastError(); +- LPVOID message; +- +- FormatMessage( +- FORMAT_MESSAGE_ALLOCATE_BUFFER | +- FORMAT_MESSAGE_FROM_SYSTEM | +- FORMAT_MESSAGE_IGNORE_INSERTS, +- NULL, +- error_code, +- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), +- (LPTSTR) &message, +- 0, +- NULL +- ); +- + lua_pushboolean(L, 0); +- lua_pushlstring(L, (LPCTSTR)message, lstrlen((LPCTSTR)message)); +- LocalFree(message); +- ++ push_win32_error(L, GetLastError()); + return 2; + } + #else +@@ -468,8 +484,15 @@ static int f_rmdir(lua_State *L) { + + static int f_chdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); ++#ifdef _WIN32 ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { return luaL_error(L, UTFCONV_ERROR_INVALID_CONVERSION ); } ++ int err = _wchdir(wpath); ++ free(wpath); ++#else + int err = chdir(path); +- if (err) { luaL_error(L, "chdir() failed"); } ++#endif ++ if (err) { luaL_error(L, "chdir() failed: %s", strerror(errno)); } + return 0; + } + +@@ -477,6 +500,57 @@ static int f_chdir(lua_State *L) { + static int f_list_dir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++#ifdef _WIN32 ++ lua_settop(L, 1); ++ if (strchr("\\/", path[strlen(path) - 2]) != NULL) ++ lua_pushstring(L, "*"); ++ else ++ lua_pushstring(L, "/*"); ++ ++ lua_concat(L, 2); ++ path = lua_tostring(L, -1); ++ ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushnil(L); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ ++ WIN32_FIND_DATAW fd; ++ HANDLE find_handle = FindFirstFileExW(wpath, FindExInfoBasic, &fd, FindExSearchNameMatch, NULL, 0); ++ free(wpath); ++ if (find_handle == INVALID_HANDLE_VALUE) { ++ lua_pushnil(L); ++ push_win32_error(L, GetLastError()); ++ return 2; ++ } ++ ++ char mbpath[MAX_PATH * 4]; // utf-8 spans 4 bytes at most ++ int len, i = 1; ++ lua_newtable(L); ++ ++ do ++ { ++ if (wcscmp(fd.cFileName, L".") == 0) { continue; } ++ if (wcscmp(fd.cFileName, L"..") == 0) { continue; } ++ ++ len = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, mbpath, MAX_PATH * 4, NULL, NULL); ++ if (len == 0) { break; } ++ lua_pushlstring(L, mbpath, len - 1); // len includes \0 ++ lua_rawseti(L, -2, i++); ++ } while (FindNextFileW(find_handle, &fd)); ++ ++ if (GetLastError() != ERROR_NO_MORE_FILES) { ++ lua_pushnil(L); ++ push_win32_error(L, GetLastError()); ++ FindClose(find_handle); ++ return 2; ++ } ++ ++ FindClose(find_handle); ++ return 1; ++#else + DIR *dir = opendir(path); + if (!dir) { + lua_pushnil(L); +@@ -497,17 +571,29 @@ static int f_list_dir(lua_State *L) { + + closedir(dir); + return 1; ++#endif + } + + + #ifdef _WIN32 +- #include +- #define realpath(x, y) _fullpath(y, x, MAX_PATH) ++ #define realpath(x, y) _wfullpath(y, x, MAX_PATH) + #endif + + static int f_absolute_path(lua_State *L) { + const char *path = luaL_checkstring(L, 1); ++#ifdef _WIN32 ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (!wpath) { return 0; } ++ ++ LPWSTR wfullpath = realpath(wpath, NULL); ++ free(wpath); ++ if (!wfullpath) { return 0; } ++ ++ char *res = utfconv_wctoutf8(wfullpath); ++ free(wfullpath); ++#else + char *res = realpath(path, NULL); ++#endif + if (!res) { return 0; } + lua_pushstring(L, res); + free(res); +@@ -518,8 +604,20 @@ static int f_absolute_path(lua_State *L) { + static int f_get_file_info(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++#ifdef _WIN32 ++ struct _stat s; ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushnil(L); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ int err = _wstat(wpath, &s); ++ free(wpath); ++#else + struct stat s; + int err = stat(path, &s); ++#endif + if (err < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); +@@ -600,7 +698,15 @@ static int f_mkdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + + #ifdef _WIN32 +- int err = _mkdir(path); ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushboolean(L, 0); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ ++ int err = _wmkdir(wpath); ++ free(wpath); + #else + int err = mkdir(path, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); + #endif +diff --git a/src/utfconv.h b/src/utfconv.h +new file mode 100644 +index 00000000..059b3071 +--- /dev/null ++++ b/src/utfconv.h +@@ -0,0 +1,57 @@ ++#ifndef MBSEC_H ++#define MBSEC_H ++ ++#ifdef _WIN32 ++ ++#include ++#include ++ ++#define UTFCONV_ERROR_INVALID_CONVERSION "Input contains invalid byte sequences." ++ ++LPWSTR utfconv_utf8towc(const char *str) { ++ LPWSTR output; ++ int len; ++ ++ // len includes \0 ++ len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); ++ if (len == 0) ++ return NULL; ++ ++ output = (LPWSTR) malloc(sizeof(WCHAR) * len); ++ if (output == NULL) ++ return NULL; ++ ++ len = MultiByteToWideChar(CP_UTF8, 0, str, -1, output, len); ++ if (len == 0) { ++ free(output); ++ return NULL; ++ } ++ ++ return output; ++} ++ ++char *utfconv_wctoutf8(LPCWSTR str) { ++ char *output; ++ int len; ++ ++ // len includes \0 ++ len = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); ++ if (len == 0) ++ return NULL; ++ ++ output = (char *) malloc(sizeof(char) * len); ++ if (output == NULL) ++ return NULL; ++ ++ len = WideCharToMultiByte(CP_UTF8, 0, str, -1, output, len, NULL, NULL); ++ if (len == 0) { ++ free(output); ++ return NULL; ++ } ++ ++ return output; ++} ++ ++#endif ++ ++#endif diff --git a/tasks/lite-xl__lite-xl-1042/solution/solve.sh b/tasks/lite-xl__lite-xl-1042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/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/lite-xl__lite-xl-1042/task.toml b/tasks/lite-xl__lite-xl-1042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..329f8c77ddb1feb79d1fa7642aa24de5568b8fd1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1042" +description = "make system.* functions support UTF8 filenames" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "3dadbd3a4912897fffc9dceb5dad108d7e700b29" +reference = "https://github.com/lite-xl/lite-xl/pull/1042" +source_access = "auto" +built_at = "2026-11-16T16:09:56.270320+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:49fc561af24d9e7c9d95ca3b1410048f1510ad2238585b63411ba9da0e7884ef" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-06-17T13:31:53Z" +diff_format = "unified" +context_files = [ + "src/api/system.c", + "src/utfconv.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 217 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.275989+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6c2e88199ff19a2d5c17dff37d3cd886abaf901dedba5a8f98ec4dc385123ccf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1042/tests/capture.py b/tasks/lite-xl__lite-xl-1042/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/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/lite-xl__lite-xl-1042/tests/instruction.md b/tasks/lite-xl__lite-xl-1042/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88a9ff390e63b9b12d3d8b02ae4d814125ca91ae --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** make system.* functions support UTF8 filenames + +## Description + +This PR introduces utfconfv.h which contains 2 function, `utfconv_utf8towc()` and `utfconv_wctoutf8()`. Some of the functions in `system` is converted to convert arguments to WCHAR and use the Windows `*W` APIs. + +Affected functions: +- system.rmdir +- system.chdir +- system.list_dir +- system.absolute_path +- system.get_file_info +- system.mkdir + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3dadbd3a4912`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1042/tests/oracle.patch b/tasks/lite-xl__lite-xl-1042/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c51b3c0be7a103165c8ada4cb4d5e9065241d92b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/tests/oracle.patch @@ -0,0 +1,308 @@ +diff --git a/src/api/system.c b/src/api/system.c +index ff99ce6f..06d6bafe 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -2,9 +2,8 @@ + #include + #include + #include +-#include +-#include + #include ++#include + #include + #include "api.h" + #include "../rencache.h" +@@ -12,9 +11,16 @@ + #include + #include + #include +-#elif __linux__ ++ #include "../utfconv.h" ++#else ++ ++#include ++#include ++ ++#ifdef __linux__ + #include + #endif ++#endif + + extern SDL_Window *window; + +@@ -125,6 +131,31 @@ static const char *get_key_name(const SDL_Event *e, char *buf) { + } + } + ++#ifdef _WIN32 ++static char *win32_error(DWORD rc) { ++ LPSTR message; ++ FormatMessage( ++ FORMAT_MESSAGE_ALLOCATE_BUFFER | ++ FORMAT_MESSAGE_FROM_SYSTEM | ++ FORMAT_MESSAGE_IGNORE_INSERTS, ++ NULL, ++ rc, ++ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), ++ (LPTSTR) &message, ++ 0, ++ NULL ++ ); ++ ++ return message; ++} ++ ++static void push_win32_error(lua_State *L, DWORD rc) { ++ LPSTR message = win32_error(rc); ++ lua_pushstring(L, message); ++ LocalFree(message); ++} ++#endif ++ + static int f_poll_event(lua_State *L) { + char buf[16]; + int mx, my, wx, wy; +@@ -425,29 +456,14 @@ static int f_rmdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + + #ifdef _WIN32 +- int deleted = RemoveDirectoryA(path); +- if(deleted > 0) { ++ LPWSTR wpath = utfconv_utf8towc(path); ++ int deleted = RemoveDirectoryW(wpath); ++ free(wpath); ++ if (deleted > 0) { + lua_pushboolean(L, 1); + } else { +- DWORD error_code = GetLastError(); +- LPVOID message; +- +- FormatMessage( +- FORMAT_MESSAGE_ALLOCATE_BUFFER | +- FORMAT_MESSAGE_FROM_SYSTEM | +- FORMAT_MESSAGE_IGNORE_INSERTS, +- NULL, +- error_code, +- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), +- (LPTSTR) &message, +- 0, +- NULL +- ); +- + lua_pushboolean(L, 0); +- lua_pushlstring(L, (LPCTSTR)message, lstrlen((LPCTSTR)message)); +- LocalFree(message); +- ++ push_win32_error(L, GetLastError()); + return 2; + } + #else +@@ -468,8 +484,15 @@ static int f_rmdir(lua_State *L) { + + static int f_chdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); ++#ifdef _WIN32 ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { return luaL_error(L, UTFCONV_ERROR_INVALID_CONVERSION ); } ++ int err = _wchdir(wpath); ++ free(wpath); ++#else + int err = chdir(path); +- if (err) { luaL_error(L, "chdir() failed"); } ++#endif ++ if (err) { luaL_error(L, "chdir() failed: %s", strerror(errno)); } + return 0; + } + +@@ -477,6 +500,57 @@ static int f_chdir(lua_State *L) { + static int f_list_dir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++#ifdef _WIN32 ++ lua_settop(L, 1); ++ if (strchr("\\/", path[strlen(path) - 2]) != NULL) ++ lua_pushstring(L, "*"); ++ else ++ lua_pushstring(L, "/*"); ++ ++ lua_concat(L, 2); ++ path = lua_tostring(L, -1); ++ ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushnil(L); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ ++ WIN32_FIND_DATAW fd; ++ HANDLE find_handle = FindFirstFileExW(wpath, FindExInfoBasic, &fd, FindExSearchNameMatch, NULL, 0); ++ free(wpath); ++ if (find_handle == INVALID_HANDLE_VALUE) { ++ lua_pushnil(L); ++ push_win32_error(L, GetLastError()); ++ return 2; ++ } ++ ++ char mbpath[MAX_PATH * 4]; // utf-8 spans 4 bytes at most ++ int len, i = 1; ++ lua_newtable(L); ++ ++ do ++ { ++ if (wcscmp(fd.cFileName, L".") == 0) { continue; } ++ if (wcscmp(fd.cFileName, L"..") == 0) { continue; } ++ ++ len = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, mbpath, MAX_PATH * 4, NULL, NULL); ++ if (len == 0) { break; } ++ lua_pushlstring(L, mbpath, len - 1); // len includes \0 ++ lua_rawseti(L, -2, i++); ++ } while (FindNextFileW(find_handle, &fd)); ++ ++ if (GetLastError() != ERROR_NO_MORE_FILES) { ++ lua_pushnil(L); ++ push_win32_error(L, GetLastError()); ++ FindClose(find_handle); ++ return 2; ++ } ++ ++ FindClose(find_handle); ++ return 1; ++#else + DIR *dir = opendir(path); + if (!dir) { + lua_pushnil(L); +@@ -497,17 +571,29 @@ static int f_list_dir(lua_State *L) { + + closedir(dir); + return 1; ++#endif + } + + + #ifdef _WIN32 +- #include +- #define realpath(x, y) _fullpath(y, x, MAX_PATH) ++ #define realpath(x, y) _wfullpath(y, x, MAX_PATH) + #endif + + static int f_absolute_path(lua_State *L) { + const char *path = luaL_checkstring(L, 1); ++#ifdef _WIN32 ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (!wpath) { return 0; } ++ ++ LPWSTR wfullpath = realpath(wpath, NULL); ++ free(wpath); ++ if (!wfullpath) { return 0; } ++ ++ char *res = utfconv_wctoutf8(wfullpath); ++ free(wfullpath); ++#else + char *res = realpath(path, NULL); ++#endif + if (!res) { return 0; } + lua_pushstring(L, res); + free(res); +@@ -518,8 +604,20 @@ static int f_absolute_path(lua_State *L) { + static int f_get_file_info(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++#ifdef _WIN32 ++ struct _stat s; ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushnil(L); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ int err = _wstat(wpath, &s); ++ free(wpath); ++#else + struct stat s; + int err = stat(path, &s); ++#endif + if (err < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); +@@ -600,7 +698,15 @@ static int f_mkdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + + #ifdef _WIN32 +- int err = _mkdir(path); ++ LPWSTR wpath = utfconv_utf8towc(path); ++ if (wpath == NULL) { ++ lua_pushboolean(L, 0); ++ lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ ++ int err = _wmkdir(wpath); ++ free(wpath); + #else + int err = mkdir(path, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); + #endif +diff --git a/src/utfconv.h b/src/utfconv.h +new file mode 100644 +index 00000000..059b3071 +--- /dev/null ++++ b/src/utfconv.h +@@ -0,0 +1,57 @@ ++#ifndef MBSEC_H ++#define MBSEC_H ++ ++#ifdef _WIN32 ++ ++#include ++#include ++ ++#define UTFCONV_ERROR_INVALID_CONVERSION "Input contains invalid byte sequences." ++ ++LPWSTR utfconv_utf8towc(const char *str) { ++ LPWSTR output; ++ int len; ++ ++ // len includes \0 ++ len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); ++ if (len == 0) ++ return NULL; ++ ++ output = (LPWSTR) malloc(sizeof(WCHAR) * len); ++ if (output == NULL) ++ return NULL; ++ ++ len = MultiByteToWideChar(CP_UTF8, 0, str, -1, output, len); ++ if (len == 0) { ++ free(output); ++ return NULL; ++ } ++ ++ return output; ++} ++ ++char *utfconv_wctoutf8(LPCWSTR str) { ++ char *output; ++ int len; ++ ++ // len includes \0 ++ len = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); ++ if (len == 0) ++ return NULL; ++ ++ output = (char *) malloc(sizeof(char) * len); ++ if (output == NULL) ++ return NULL; ++ ++ len = WideCharToMultiByte(CP_UTF8, 0, str, -1, output, len, NULL, NULL); ++ if (len == 0) { ++ free(output); ++ return NULL; ++ } ++ ++ return output; ++} ++ ++#endif ++ ++#endif diff --git a/tasks/lite-xl__lite-xl-1042/tests/test.sh b/tasks/lite-xl__lite-xl-1042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..131412d87f938003c97026db79893bc42b2adcff --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/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 3dadbd3a4912897fffc9dceb5dad108d7e700b29 > "$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/lite-xl__lite-xl-1042/tests/verifier.py b/tasks/lite-xl__lite-xl-1042/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1042/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/lite-xl__lite-xl-1143/environment/Dockerfile b/tasks/lite-xl__lite-xl-1143/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea5e635059e81e3f84dbfebfbe34b93beaf5676f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d1c74f529a199425dfd47ec13977c6600f24ea3c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d1c74f529a199425dfd47ec13977c6600f24ea3c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d1c74f529a199425dfd47ec13977c6600f24ea3c \ + && 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/lite-xl__lite-xl-1143/instruction.md b/tasks/lite-xl__lite-xl-1143/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b005dcebd3b69ac59f25a17e841e1d818db26fd3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** draw lite-xl icon in TitleView + +## Description + +the original hamburger menu icon is confusing. It is not a menu and clicking it doesn't do anything. There is no reason why we can't draw lite-xl's icon in place of that. + +Dark theme: +![image](https://user-images.githubusercontent.com/20792268/194805273-31ac7e7a-d055-49eb-99da-f12d5b117c6e.png) + +Light theme: +![image](https://user-images.githubusercontent.com/20792268/194805312-8b5334a5-aa68-4d00-a44c-4bd055c3e52b.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1c74f529a19`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1143/solution/patch.diff b/tasks/lite-xl__lite-xl-1143/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eca982fd7e629f0c2c1a95365f10dcae3565738e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/solution/patch.diff @@ -0,0 +1,117 @@ +diff --git a/data/core/titleview.lua b/data/core/titleview.lua +index f9d7a961..f31d73e5 100644 +--- a/data/core/titleview.lua ++++ b/data/core/titleview.lua +@@ -3,6 +3,14 @@ local common = require "core.common" + local style = require "core.style" + local View = require "core.view" + ++local icon_colors = { ++ bg = { common.color "#2e2e32ff" }, ++ color6 = { common.color "#e1e1e6ff" }, ++ color7 = { common.color "#ffa94dff" }, ++ color8 = { common.color "#93ddfaff" }, ++ color9 = { common.color "#f7c95cff" } ++}; ++ + local restore_command = { + symbol = "w", action = function() system.set_window_mode("normal") end + } +@@ -55,7 +63,11 @@ function TitleView:draw_window_title() + local ox, oy = self:get_content_offset() + local color = style.text + local x, y = ox + style.padding.x, oy + style.padding.y +- x = common.draw_text(style.icon_font, color, "M ", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.bg, "5", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color6, "6", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color7, "7", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color8, "8", nil, x, y, 0, h) ++ x = common.draw_text(style.icon_font, icon_colors.color9, "9 ", nil, x, y, 0, h) + local title = core.compose_window_title(core.window_title) + common.draw_text(style.font, color, title, nil, x, y, 0, h) + end +diff --git a/data/fonts/icons.ttf b/data/fonts/icons.ttf +index 43ab3767..5fd6d9e9 100644 +Binary files a/data/fonts/icons.ttf and b/data/fonts/icons.ttf differ +diff --git a/scripts/fontello-config.json b/scripts/fontello-config.json +index 42334c2f..76349182 100644 +--- a/scripts/fontello-config.json ++++ b/scripts/fontello-config.json +@@ -125,6 +125,76 @@ + "css": "right-open", + "code": 62, + "src": "fontawesome" ++ }, ++ { ++ "uid": "ebf4bfe82c54f9beb94c5221a7bdd975", ++ "css": "lite-xlbg", ++ "code": 53, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M83.3 0H916.7C962.7 0 1000 37.3 1000 83.3V916.7C1000 962.7 962.7 1000 916.7 1000H83.3C37.3 1000 0 962.7 0 916.7V83.3C0 37.3 37.3 0 83.3 0Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xlbg" ++ ] ++ }, ++ { ++ "uid": "cde50fad6c2cd7a805a8d5026939d645", ++ "css": "lite-xl1", ++ "code": 54, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M395.8 562.5V312.5C395.8 289.5 377.2 270.8 354.2 270.8H270.8V625C270.8 682.5 317.5 729.2 375 729.2H729.2V645.8C729.2 622.8 710.5 604.2 687.5 604.2H437.5C414.5 604.2 395.8 585.5 395.8 562.5Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl1" ++ ] ++ }, ++ { ++ "uid": "526539ec7fcda0b3e7e7ceaa6ae416e6", ++ "css": "lite-xl2", ++ "code": 55, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M729.2 270.8H437.5L729.2 562.5Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl2" ++ ] ++ }, ++ { ++ "uid": "cccbe047c5cb17c63c41a1fb1fc022f4", ++ "css": "lite-xl3", ++ "code": 57, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M666.7 333.3H500L666.7 500Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl3" ++ ] ++ }, ++ { ++ "uid": "09d781dca1f50fcae90e67df9cc2f8dd", ++ "css": "lite-xl4", ++ "code": 56, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M500 458.3V333.3L604.2 395.8 666.7 500H541.7C518.7 500 500 481.3 500 458.3Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl4" ++ ] + } + ] + } +\ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1143/solution/solve.sh b/tasks/lite-xl__lite-xl-1143/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/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/lite-xl__lite-xl-1143/task.toml b/tasks/lite-xl__lite-xl-1143/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5bd8eef53cbc581e37f39e8ee4d473043944caa5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1143" +description = "draw lite-xl icon in TitleView" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d1c74f529a199425dfd47ec13977c6600f24ea3c" +reference = "https://github.com/lite-xl/lite-xl/pull/1143" +source_access = "auto" +built_at = "2026-11-16T16:09:56.278097+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d11aac149dd4ffdfd0d36c19e1e7770d68f110ef8170767abf61ad66c4af0b68" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-10-10T15:05:30Z" +diff_format = "unified" +context_files = [ + "data/core/titleview.lua", + "data/fonts/icons.ttf", + "scripts/fontello-config.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 84 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.276449+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a9bf2480db3f9f1455e64619028bff1815c2977c9504b206d7a2c78e52a3f1dd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1143/tests/capture.py b/tasks/lite-xl__lite-xl-1143/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/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/lite-xl__lite-xl-1143/tests/instruction.md b/tasks/lite-xl__lite-xl-1143/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b005dcebd3b69ac59f25a17e841e1d818db26fd3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** draw lite-xl icon in TitleView + +## Description + +the original hamburger menu icon is confusing. It is not a menu and clicking it doesn't do anything. There is no reason why we can't draw lite-xl's icon in place of that. + +Dark theme: +![image](https://user-images.githubusercontent.com/20792268/194805273-31ac7e7a-d055-49eb-99da-f12d5b117c6e.png) + +Light theme: +![image](https://user-images.githubusercontent.com/20792268/194805312-8b5334a5-aa68-4d00-a44c-4bd055c3e52b.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1c74f529a19`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1143/tests/oracle.patch b/tasks/lite-xl__lite-xl-1143/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eca982fd7e629f0c2c1a95365f10dcae3565738e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/tests/oracle.patch @@ -0,0 +1,117 @@ +diff --git a/data/core/titleview.lua b/data/core/titleview.lua +index f9d7a961..f31d73e5 100644 +--- a/data/core/titleview.lua ++++ b/data/core/titleview.lua +@@ -3,6 +3,14 @@ local common = require "core.common" + local style = require "core.style" + local View = require "core.view" + ++local icon_colors = { ++ bg = { common.color "#2e2e32ff" }, ++ color6 = { common.color "#e1e1e6ff" }, ++ color7 = { common.color "#ffa94dff" }, ++ color8 = { common.color "#93ddfaff" }, ++ color9 = { common.color "#f7c95cff" } ++}; ++ + local restore_command = { + symbol = "w", action = function() system.set_window_mode("normal") end + } +@@ -55,7 +63,11 @@ function TitleView:draw_window_title() + local ox, oy = self:get_content_offset() + local color = style.text + local x, y = ox + style.padding.x, oy + style.padding.y +- x = common.draw_text(style.icon_font, color, "M ", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.bg, "5", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color6, "6", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color7, "7", nil, x, y, 0, h) ++ common.draw_text(style.icon_font, icon_colors.color8, "8", nil, x, y, 0, h) ++ x = common.draw_text(style.icon_font, icon_colors.color9, "9 ", nil, x, y, 0, h) + local title = core.compose_window_title(core.window_title) + common.draw_text(style.font, color, title, nil, x, y, 0, h) + end +diff --git a/data/fonts/icons.ttf b/data/fonts/icons.ttf +index 43ab3767..5fd6d9e9 100644 +Binary files a/data/fonts/icons.ttf and b/data/fonts/icons.ttf differ +diff --git a/scripts/fontello-config.json b/scripts/fontello-config.json +index 42334c2f..76349182 100644 +--- a/scripts/fontello-config.json ++++ b/scripts/fontello-config.json +@@ -125,6 +125,76 @@ + "css": "right-open", + "code": 62, + "src": "fontawesome" ++ }, ++ { ++ "uid": "ebf4bfe82c54f9beb94c5221a7bdd975", ++ "css": "lite-xlbg", ++ "code": 53, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M83.3 0H916.7C962.7 0 1000 37.3 1000 83.3V916.7C1000 962.7 962.7 1000 916.7 1000H83.3C37.3 1000 0 962.7 0 916.7V83.3C0 37.3 37.3 0 83.3 0Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xlbg" ++ ] ++ }, ++ { ++ "uid": "cde50fad6c2cd7a805a8d5026939d645", ++ "css": "lite-xl1", ++ "code": 54, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M395.8 562.5V312.5C395.8 289.5 377.2 270.8 354.2 270.8H270.8V625C270.8 682.5 317.5 729.2 375 729.2H729.2V645.8C729.2 622.8 710.5 604.2 687.5 604.2H437.5C414.5 604.2 395.8 585.5 395.8 562.5Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl1" ++ ] ++ }, ++ { ++ "uid": "526539ec7fcda0b3e7e7ceaa6ae416e6", ++ "css": "lite-xl2", ++ "code": 55, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M729.2 270.8H437.5L729.2 562.5Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl2" ++ ] ++ }, ++ { ++ "uid": "cccbe047c5cb17c63c41a1fb1fc022f4", ++ "css": "lite-xl3", ++ "code": 57, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M666.7 333.3H500L666.7 500Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl3" ++ ] ++ }, ++ { ++ "uid": "09d781dca1f50fcae90e67df9cc2f8dd", ++ "css": "lite-xl4", ++ "code": 56, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M500 458.3V333.3L604.2 395.8 666.7 500H541.7C518.7 500 500 481.3 500 458.3Z", ++ "width": 1000 ++ }, ++ "search": [ ++ "lite-xl4" ++ ] + } + ] + } +\ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1143/tests/test.sh b/tasks/lite-xl__lite-xl-1143/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9328b42228424c4148618ea2105852040813513c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/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 d1c74f529a199425dfd47ec13977c6600f24ea3c > "$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/lite-xl__lite-xl-1143/tests/verifier.py b/tasks/lite-xl__lite-xl-1143/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1143/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/lite-xl__lite-xl-1145/environment/Dockerfile b/tasks/lite-xl__lite-xl-1145/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea5e635059e81e3f84dbfebfbe34b93beaf5676f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d1c74f529a199425dfd47ec13977c6600f24ea3c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d1c74f529a199425dfd47ec13977c6600f24ea3c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d1c74f529a199425dfd47ec13977c6600f24ea3c \ + && 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/lite-xl__lite-xl-1145/instruction.md b/tasks/lite-xl__lite-xl-1145/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d406aae837b74da76ae32e2026b9648b734ab1ce --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** add parameter validation to checkcolor and f_font_group + +## Description + +Added parameter validation to checkcolor. + +`renderer.font.group()` no longer allows tables larger than FONT_FALLBACK_MAX and nested font groups. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1c74f529a19`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1145/solution/patch.diff b/tasks/lite-xl__lite-xl-1145/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8a53e449153b8ea412f750f41d45c396500a601c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index c23e38ea..f663d80e 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -130,7 +130,20 @@ static int f_font_copy(lua_State *L) { + } + + static int f_font_group(lua_State* L) { ++ int table_size; + luaL_checktype(L, 1, LUA_TTABLE); ++ ++ table_size = lua_rawlen(L, 1); ++ if (table_size >= FONT_FALLBACK_MAX) ++ return luaL_error(L, "failed to create font group: table size too large"); ++ ++ // we also need to ensure that there are no fontgroups inside it ++ for (int i = 1; i <= table_size; i++) { ++ if (lua_rawgeti(L, 1, i) != LUA_TUSERDATA) ++ return luaL_typeerror(L, -1, API_TYPE_FONT "(userdata)"); ++ lua_pop(L, 1); ++ } ++ + luaL_setmetatable(L, API_TYPE_FONT); + return 1; + } +@@ -197,6 +210,7 @@ static RenColor checkcolor(lua_State *L, int idx, int def) { + if (lua_isnoneornil(L, idx)) { + return (RenColor) { def, def, def, 255 }; + } ++ luaL_checktype(L, idx, LUA_TTABLE); + lua_rawgeti(L, idx, 1); + lua_rawgeti(L, idx, 2); + lua_rawgeti(L, idx, 3); diff --git a/tasks/lite-xl__lite-xl-1145/solution/solve.sh b/tasks/lite-xl__lite-xl-1145/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/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/lite-xl__lite-xl-1145/task.toml b/tasks/lite-xl__lite-xl-1145/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c43bae536575be7abdfcd24995ca5a5f372ad825 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1145" +description = "add parameter validation to checkcolor and f_font_group" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d1c74f529a199425dfd47ec13977c6600f24ea3c" +reference = "https://github.com/lite-xl/lite-xl/pull/1145" +source_access = "auto" +built_at = "2026-11-16T16:09:56.269018+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0bc716ea8ea0209d95e6a8ebca3ae89e104fb3f579ba73881dfff8c2d883fdb4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-10-10T15:44:20Z" +diff_format = "unified" +context_files = [ + "src/api/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.276912+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a9bf2480db3f9f1455e64619028bff1815c2977c9504b206d7a2c78e52a3f1dd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1145/tests/capture.py b/tasks/lite-xl__lite-xl-1145/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/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/lite-xl__lite-xl-1145/tests/instruction.md b/tasks/lite-xl__lite-xl-1145/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d406aae837b74da76ae32e2026b9648b734ab1ce --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** add parameter validation to checkcolor and f_font_group + +## Description + +Added parameter validation to checkcolor. + +`renderer.font.group()` no longer allows tables larger than FONT_FALLBACK_MAX and nested font groups. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d1c74f529a19`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1145/tests/oracle.patch b/tasks/lite-xl__lite-xl-1145/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8a53e449153b8ea412f750f41d45c396500a601c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index c23e38ea..f663d80e 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -130,7 +130,20 @@ static int f_font_copy(lua_State *L) { + } + + static int f_font_group(lua_State* L) { ++ int table_size; + luaL_checktype(L, 1, LUA_TTABLE); ++ ++ table_size = lua_rawlen(L, 1); ++ if (table_size >= FONT_FALLBACK_MAX) ++ return luaL_error(L, "failed to create font group: table size too large"); ++ ++ // we also need to ensure that there are no fontgroups inside it ++ for (int i = 1; i <= table_size; i++) { ++ if (lua_rawgeti(L, 1, i) != LUA_TUSERDATA) ++ return luaL_typeerror(L, -1, API_TYPE_FONT "(userdata)"); ++ lua_pop(L, 1); ++ } ++ + luaL_setmetatable(L, API_TYPE_FONT); + return 1; + } +@@ -197,6 +210,7 @@ static RenColor checkcolor(lua_State *L, int idx, int def) { + if (lua_isnoneornil(L, idx)) { + return (RenColor) { def, def, def, 255 }; + } ++ luaL_checktype(L, idx, LUA_TTABLE); + lua_rawgeti(L, idx, 1); + lua_rawgeti(L, idx, 2); + lua_rawgeti(L, idx, 3); diff --git a/tasks/lite-xl__lite-xl-1145/tests/test.sh b/tasks/lite-xl__lite-xl-1145/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9328b42228424c4148618ea2105852040813513c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/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 d1c74f529a199425dfd47ec13977c6600f24ea3c > "$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/lite-xl__lite-xl-1145/tests/verifier.py b/tasks/lite-xl__lite-xl-1145/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1145/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/lite-xl__lite-xl-1156/environment/Dockerfile b/tasks/lite-xl__lite-xl-1156/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f09dfa258c0b31b92f19696120a48de5f1e9ce0f --- /dev/null +++ b/tasks/lite-xl__lite-xl-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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f89088d0ec9d440ee7e79405b1bde3f61aa74268 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f89088d0ec9d440ee7e79405b1bde3f61aa74268 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f89088d0ec9d440ee7e79405b1bde3f61aa74268 \ + && 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/lite-xl__lite-xl-1156/instruction.md b/tasks/lite-xl__lite-xl-1156/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b35113c72ee307464968232591393dd03989a42 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** font reference counting when using renderer.draw_text + +## Description + +Saves a reference of the font when calling `renderer.draw_text`. This prevents the GC from killing it. Apparently this can happen! + +```lua +core.add_thread(function() + while true do + core.root_view:defer_draw(function() + local font = renderer.font.load(DATADIR .. "/fonts/FiraSans-Regular.ttf", 14 * SCALE) + renderer.draw_text(font, "hello world help me", 600, 10, style.text) + font = nil + collectgarbage() + end) + coroutine.yield(0) + end +end) +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f89088d0ec9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1156/solution/patch.diff b/tasks/lite-xl__lite-xl-1156/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1995fbf687479bfe6f7921a5fa8aa4caf6a145db --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index c23e38ea..11ab71e5 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -3,6 +3,9 @@ + #include "../renderer.h" + #include "../rencache.h" + ++// a reference index to a table that stores the fonts ++static int RENDERER_FONT_REF = LUA_NOREF; ++ + static int font_get_options( + lua_State *L, + ERenFontAntialiasing *antialiasing, +@@ -234,6 +237,9 @@ static int f_begin_frame(UNUSED lua_State *L) { + + static int f_end_frame(UNUSED lua_State *L) { + rencache_end_frame(); ++ // clear the font reference table ++ lua_newtable(L); ++ lua_rawseti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); + return 0; + } + +@@ -270,6 +276,19 @@ static int f_draw_rect(lua_State *L) { + static int f_draw_text(lua_State *L) { + RenFont* fonts[FONT_FALLBACK_MAX]; + font_retrieve(L, fonts, 1); ++ ++ // stores a reference to this font to the reference table ++ lua_rawgeti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); ++ if (lua_istable(L, -1)) ++ { ++ lua_pushvalue(L, 1); ++ lua_pushboolean(L, 1); ++ lua_rawset(L, -3); ++ } else { ++ fprintf(stderr, "warning: failed to reference count fonts\n"); ++ } ++ lua_pop(L, 1); ++ + const char *text = luaL_checkstring(L, 2); + float x = luaL_checknumber(L, 3); + int y = luaL_checknumber(L, 4); +@@ -305,6 +324,10 @@ static const luaL_Reg fontLib[] = { + }; + + int luaopen_renderer(lua_State *L) { ++ // gets a reference on the registry to store font data ++ lua_newtable(L); ++ RENDERER_FONT_REF = luaL_ref(L, LUA_REGISTRYINDEX); ++ + luaL_newlib(L, lib); + luaL_newmetatable(L, API_TYPE_FONT); + luaL_setfuncs(L, fontLib, 0); diff --git a/tasks/lite-xl__lite-xl-1156/solution/solve.sh b/tasks/lite-xl__lite-xl-1156/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/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/lite-xl__lite-xl-1156/task.toml b/tasks/lite-xl__lite-xl-1156/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bba54cbbd6a590b9d9baa1922c8dffc075664d9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1156" +description = "font reference counting when using renderer.draw_text" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f89088d0ec9d440ee7e79405b1bde3f61aa74268" +reference = "https://github.com/lite-xl/lite-xl/pull/1156" +source_access = "auto" +built_at = "2026-11-16T16:09:56.276577+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dbbdd3317cbc391730da362e71ce052483b358f7d7ea6ec0f755c22df8f1e39b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-10-14T02:52:38Z" +diff_format = "unified" +context_files = [ + "src/api/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.277478+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f540077edece3b8b13665038458b900534b143e0bcf31707e973a0712fa5dce7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1156/tests/capture.py b/tasks/lite-xl__lite-xl-1156/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/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/lite-xl__lite-xl-1156/tests/instruction.md b/tasks/lite-xl__lite-xl-1156/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b35113c72ee307464968232591393dd03989a42 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** font reference counting when using renderer.draw_text + +## Description + +Saves a reference of the font when calling `renderer.draw_text`. This prevents the GC from killing it. Apparently this can happen! + +```lua +core.add_thread(function() + while true do + core.root_view:defer_draw(function() + local font = renderer.font.load(DATADIR .. "/fonts/FiraSans-Regular.ttf", 14 * SCALE) + renderer.draw_text(font, "hello world help me", 600, 10, style.text) + font = nil + collectgarbage() + end) + coroutine.yield(0) + end +end) +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f89088d0ec9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1156/tests/oracle.patch b/tasks/lite-xl__lite-xl-1156/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1995fbf687479bfe6f7921a5fa8aa4caf6a145db --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index c23e38ea..11ab71e5 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -3,6 +3,9 @@ + #include "../renderer.h" + #include "../rencache.h" + ++// a reference index to a table that stores the fonts ++static int RENDERER_FONT_REF = LUA_NOREF; ++ + static int font_get_options( + lua_State *L, + ERenFontAntialiasing *antialiasing, +@@ -234,6 +237,9 @@ static int f_begin_frame(UNUSED lua_State *L) { + + static int f_end_frame(UNUSED lua_State *L) { + rencache_end_frame(); ++ // clear the font reference table ++ lua_newtable(L); ++ lua_rawseti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); + return 0; + } + +@@ -270,6 +276,19 @@ static int f_draw_rect(lua_State *L) { + static int f_draw_text(lua_State *L) { + RenFont* fonts[FONT_FALLBACK_MAX]; + font_retrieve(L, fonts, 1); ++ ++ // stores a reference to this font to the reference table ++ lua_rawgeti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); ++ if (lua_istable(L, -1)) ++ { ++ lua_pushvalue(L, 1); ++ lua_pushboolean(L, 1); ++ lua_rawset(L, -3); ++ } else { ++ fprintf(stderr, "warning: failed to reference count fonts\n"); ++ } ++ lua_pop(L, 1); ++ + const char *text = luaL_checkstring(L, 2); + float x = luaL_checknumber(L, 3); + int y = luaL_checknumber(L, 4); +@@ -305,6 +324,10 @@ static const luaL_Reg fontLib[] = { + }; + + int luaopen_renderer(lua_State *L) { ++ // gets a reference on the registry to store font data ++ lua_newtable(L); ++ RENDERER_FONT_REF = luaL_ref(L, LUA_REGISTRYINDEX); ++ + luaL_newlib(L, lib); + luaL_newmetatable(L, API_TYPE_FONT); + luaL_setfuncs(L, fontLib, 0); diff --git a/tasks/lite-xl__lite-xl-1156/tests/test.sh b/tasks/lite-xl__lite-xl-1156/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1277505a9f30cb9e23469ab5414333db0ef4c6bd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1156/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 f89088d0ec9d440ee7e79405b1bde3f61aa74268 > "$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/lite-xl__lite-xl-1156/tests/verifier.py b/tasks/lite-xl__lite-xl-1156/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-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/lite-xl__lite-xl-1160/environment/Dockerfile b/tasks/lite-xl__lite-xl-1160/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..90f2ff429446e910cfe13a10ec124d3a03a5c528 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97ba91af8b855a10a14bdc5cad774c877156f4a9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97ba91af8b855a10a14bdc5cad774c877156f4a9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97ba91af8b855a10a14bdc5cad774c877156f4a9 \ + && 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/lite-xl__lite-xl-1160/instruction.md b/tasks/lite-xl__lite-xl-1160/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86d10508ff49eb73083db0d13770bbd863455d20 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** make the default core.ignore_files more specific + +## Description + +instead of blanket ignoring all dotfiles, we define a list of folders and files to ignore. this makes the overall experience better. + +The list is similar to Sublime Text. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ba91af8b85`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1160/solution/patch.diff b/tasks/lite-xl__lite-xl-1160/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eba3d4ed7ec87f845364772ec60ccd4217fcea83 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/data/core/config.lua b/data/core/config.lua +index efbe1f1b..87837439 100644 +--- a/data/core/config.lua ++++ b/data/core/config.lua +@@ -7,7 +7,16 @@ config.mouse_wheel_scroll = 50 * SCALE + config.animate_drag_scroll = false + config.scroll_past_end = true + config.file_size_limit = 10 +-config.ignore_files = { "^%." } ++config.ignore_files = { ++ -- folders ++ "^%.svn/", "^%.git/", "^%.hg/", "^CVS/", "^%.Trash/", "^%.Trash%-.*/", ++ "^node_modules/", "^%.cache/", "^__pycache__/", ++ -- files ++ "%.pyc$", "%.pyo$", "%.exe$", "%.dll$", "%.obj$", "%.o$", ++ "%.a$", "%.lib$", "%.so$", "%.dylib$", "%.ncb$", "%.sdf$", ++ "%.suo$", "%.pdb$", "%.idb$", "%.class$", "%.psd$", "%.db$", ++ "^desktop%.ini$", "^%.DS_Store$", "^%.directory$", ++} + config.symbol_pattern = "[%a_][%w_]*" + config.non_word_chars = " \t\n/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-" + config.undo_merge_timeout = 0.3 +diff --git a/data/core/init.lua b/data/core/init.lua +index a9ce4459..44e114e8 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -495,7 +495,6 @@ local style = require "core.style" + -- key binding: + -- keymap.add { ["ctrl+escape"] = "core:quit" } + +- + ------------------------------- Fonts ---------------------------------------- + + -- customize fonts: +@@ -535,6 +534,21 @@ local style = require "core.style" + -- + -- disable detectindent, otherwise it is enabled by default + -- config.plugins.detectindent = false ++ ++---------------------------- Miscellanous -------------------------------------- ++ ++-- modify list of files to ignore when indexing the project: ++-- config.ignore_files = { ++-- -- folders ++-- "^%.svn/", "^%.git/", "^%.hg/", "^CVS/", "^%.Trash/", "^%.Trash%-.*/", ++-- "^node_modules/", "^%.cache/", "^__pycache__/", ++-- -- files ++-- "%.pyc$", "%.pyo$", "%.exe$", "%.dll$", "%.obj$", "%.o$", ++-- "%.a$", "%.lib$", "%.so$", "%.dylib$", "%.ncb$", "%.sdf$", ++-- "%.suo$", "%.pdb$", "%.idb$", "%.class$", "%.psd$", "%.db$", ++-- "^desktop%.ini$", "^%.DS_Store$", "^%.directory$", ++-- } ++ + ]]) + init_file:close() + end diff --git a/tasks/lite-xl__lite-xl-1160/solution/solve.sh b/tasks/lite-xl__lite-xl-1160/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/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/lite-xl__lite-xl-1160/task.toml b/tasks/lite-xl__lite-xl-1160/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f568e5064f94842fb0a0ffef45b9bbbfaebc3cf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1160" +description = "make the default core.ignore_files more specific" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "97ba91af8b855a10a14bdc5cad774c877156f4a9" +reference = "https://github.com/lite-xl/lite-xl/pull/1160" +source_access = "auto" +built_at = "2026-11-16T16:09:56.275012+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7cb935b07dd18655fc9cc229535842df5590cf40fa785574596b0ea2a3123f70" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-10-20T02:23:01Z" +diff_format = "unified" +context_files = [ + "data/core/config.lua", + "data/core/init.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 27 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.277934+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2c12b72e2c0d8ff4e62cf36836ded6d2ee72a425b5dbab09578be0022585250" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1160/tests/capture.py b/tasks/lite-xl__lite-xl-1160/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/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/lite-xl__lite-xl-1160/tests/instruction.md b/tasks/lite-xl__lite-xl-1160/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86d10508ff49eb73083db0d13770bbd863455d20 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** make the default core.ignore_files more specific + +## Description + +instead of blanket ignoring all dotfiles, we define a list of folders and files to ignore. this makes the overall experience better. + +The list is similar to Sublime Text. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ba91af8b85`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1160/tests/oracle.patch b/tasks/lite-xl__lite-xl-1160/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eba3d4ed7ec87f845364772ec60ccd4217fcea83 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/data/core/config.lua b/data/core/config.lua +index efbe1f1b..87837439 100644 +--- a/data/core/config.lua ++++ b/data/core/config.lua +@@ -7,7 +7,16 @@ config.mouse_wheel_scroll = 50 * SCALE + config.animate_drag_scroll = false + config.scroll_past_end = true + config.file_size_limit = 10 +-config.ignore_files = { "^%." } ++config.ignore_files = { ++ -- folders ++ "^%.svn/", "^%.git/", "^%.hg/", "^CVS/", "^%.Trash/", "^%.Trash%-.*/", ++ "^node_modules/", "^%.cache/", "^__pycache__/", ++ -- files ++ "%.pyc$", "%.pyo$", "%.exe$", "%.dll$", "%.obj$", "%.o$", ++ "%.a$", "%.lib$", "%.so$", "%.dylib$", "%.ncb$", "%.sdf$", ++ "%.suo$", "%.pdb$", "%.idb$", "%.class$", "%.psd$", "%.db$", ++ "^desktop%.ini$", "^%.DS_Store$", "^%.directory$", ++} + config.symbol_pattern = "[%a_][%w_]*" + config.non_word_chars = " \t\n/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-" + config.undo_merge_timeout = 0.3 +diff --git a/data/core/init.lua b/data/core/init.lua +index a9ce4459..44e114e8 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -495,7 +495,6 @@ local style = require "core.style" + -- key binding: + -- keymap.add { ["ctrl+escape"] = "core:quit" } + +- + ------------------------------- Fonts ---------------------------------------- + + -- customize fonts: +@@ -535,6 +534,21 @@ local style = require "core.style" + -- + -- disable detectindent, otherwise it is enabled by default + -- config.plugins.detectindent = false ++ ++---------------------------- Miscellanous -------------------------------------- ++ ++-- modify list of files to ignore when indexing the project: ++-- config.ignore_files = { ++-- -- folders ++-- "^%.svn/", "^%.git/", "^%.hg/", "^CVS/", "^%.Trash/", "^%.Trash%-.*/", ++-- "^node_modules/", "^%.cache/", "^__pycache__/", ++-- -- files ++-- "%.pyc$", "%.pyo$", "%.exe$", "%.dll$", "%.obj$", "%.o$", ++-- "%.a$", "%.lib$", "%.so$", "%.dylib$", "%.ncb$", "%.sdf$", ++-- "%.suo$", "%.pdb$", "%.idb$", "%.class$", "%.psd$", "%.db$", ++-- "^desktop%.ini$", "^%.DS_Store$", "^%.directory$", ++-- } ++ + ]]) + init_file:close() + end diff --git a/tasks/lite-xl__lite-xl-1160/tests/test.sh b/tasks/lite-xl__lite-xl-1160/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..71378b67b8c1819a066123dbbc4979888ade4667 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/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 97ba91af8b855a10a14bdc5cad774c877156f4a9 > "$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/lite-xl__lite-xl-1160/tests/verifier.py b/tasks/lite-xl__lite-xl-1160/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1160/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/lite-xl__lite-xl-1201/environment/Dockerfile b/tasks/lite-xl__lite-xl-1201/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2906532b8d7f74f4468630c51b202d032ff3127a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 66198eb327522974e51449de707971e09ed334c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 66198eb327522974e51449de707971e09ed334c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 66198eb327522974e51449de707971e09ed334c1 \ + && 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/lite-xl__lite-xl-1201/instruction.md b/tasks/lite-xl__lite-xl-1201/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..613cb9c03ed799a41b8ba56721229692226331a2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Load fonts with UTF-8 filenames + +## Description + +This is another attempt of #1026 without the reference counting. + +Example config: +```lua +style.font = renderer.font.load("C:/msys64/home/takas/lite-xl/界面字母.ttf", 14 * SCALE) +``` +(Realistically, user might have lite-xl in some non-ACP home folder) + +without the patch: +![image](https://user-images.githubusercontent.com/20792268/201680381-2c9f78f2-e4b9-4cb9-907e-af42fdbbdb8b.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `66198eb32752`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1201/solution/patch.diff b/tasks/lite-xl__lite-xl-1201/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e90b39bb3bc73a695345d64f4f7d99b3b75c4554 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/solution/patch.diff @@ -0,0 +1,151 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 89bcdd50..e34c8504 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -8,6 +8,10 @@ + #include + #include FT_FREETYPE_H + ++#ifdef _WIN32 ++#include "utfconv.h" ++#endif ++ + #include "renderer.h" + #include "renwindow.h" + +@@ -51,7 +55,8 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; +- char path[1]; ++ unsigned char *file; ++ char path[]; + } RenFont; + + static const char* utf8_to_codepoint(const char *p, unsigned *dst) { +@@ -206,9 +211,48 @@ static void font_clear_glyph_cache(RenFont* font) { + } + + RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { +- FT_Face face; +- if (FT_New_Face( library, path, 0, &face)) ++ FT_Face face = NULL; ++ ++#ifdef _WIN32 ++ ++ HANDLE file = INVALID_HANDLE_VALUE; ++ DWORD read; ++ int font_file_len = 0; ++ unsigned char *font_file = NULL; ++ wchar_t *wpath = NULL; ++ ++ if ((wpath = utfconv_utf8towc(path)) == NULL) + return NULL; ++ ++ if ((file = CreateFileW(wpath, ++ GENERIC_READ, ++ 0, ++ NULL, ++ OPEN_EXISTING, ++ FILE_ATTRIBUTE_NORMAL, ++ NULL)) == INVALID_HANDLE_VALUE) ++ goto failure; ++ ++ if ((font_file_len = GetFileSize(file, NULL)) == INVALID_FILE_SIZE) ++ goto failure; ++ ++ font_file = check_alloc(malloc(font_file_len * sizeof(unsigned char))); ++ if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) ++ goto failure; ++ ++ CloseHandle(file); ++ free(wpath); ++ ++ if (FT_New_Memory_Face(library, font_file, read, 0, &face)) ++ goto failure; ++ ++#else ++ ++ if (FT_New_Face(library, path, 0, &face)) ++ return NULL; ++ ++#endif ++ + const int surface_scale = renwin_surface_scale(&window_renderer); + if (FT_Set_Pixel_Sizes(face, 0, (int)(size*surface_scale))) + goto failure; +@@ -223,6 +267,11 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + font->hinting = hinting; + font->style = style; + ++#ifdef _WIN32 ++ // we need to keep this for freetype ++ font->file = font_file; ++#endif ++ + if(FT_IS_SCALABLE(face)) + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); + if(!font->underline_thickness) font->underline_thickness = ceil((double) font->height / 14.0); +@@ -232,8 +281,15 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + font->space_advance = face->glyph->advance.x / 64.0f; + font->tab_advance = font->space_advance * 2; + return font; +- failure: +- FT_Done_Face(face); ++ ++failure: ++#ifdef _WIN32 ++ free(wpath); ++ free(font_file); ++ if (file != INVALID_HANDLE_VALUE) CloseHandle(file); ++#endif ++ if (face != NULL) ++ FT_Done_Face(face); + return NULL; + } + +@@ -252,6 +308,9 @@ const char* ren_font_get_path(RenFont *font) { + void ren_font_free(RenFont* font) { + font_clear_glyph_cache(font); + FT_Done_Face(font->face); ++#ifdef _WIN32 ++ free(font->file); ++#endif + free(font); + } + +diff --git a/src/utfconv.h b/src/utfconv.h +index 059b3071..59f98e4a 100644 +--- a/src/utfconv.h ++++ b/src/utfconv.h +@@ -1,6 +1,12 @@ + #ifndef MBSEC_H + #define MBSEC_H + ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ + #ifdef _WIN32 + + #include +@@ -8,7 +14,7 @@ + + #define UTFCONV_ERROR_INVALID_CONVERSION "Input contains invalid byte sequences." + +-LPWSTR utfconv_utf8towc(const char *str) { ++static UNUSED LPWSTR utfconv_utf8towc(const char *str) { + LPWSTR output; + int len; + +@@ -30,7 +36,7 @@ LPWSTR utfconv_utf8towc(const char *str) { + return output; + } + +-char *utfconv_wctoutf8(LPCWSTR str) { ++static UNUSED char *utfconv_wctoutf8(LPCWSTR str) { + char *output; + int len; + diff --git a/tasks/lite-xl__lite-xl-1201/solution/solve.sh b/tasks/lite-xl__lite-xl-1201/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/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/lite-xl__lite-xl-1201/task.toml b/tasks/lite-xl__lite-xl-1201/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..50ee3cbeb29d7567806cd21c4744f1cb133da931 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1201" +description = "Load fonts with UTF-8 filenames" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "66198eb327522974e51449de707971e09ed334c1" +reference = "https://github.com/lite-xl/lite-xl/pull/1201" +source_access = "auto" +built_at = "2026-11-16T16:09:56.273419+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4584518263f606e175567162f99595221abbc6d14132c3f3d977f5d37e688329" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-16T03:27:04Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", + "src/utfconv.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 79 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.278438+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c646bcb954a9f13ad633228e39a53a3957a60b7cc095973a3b219c4c4208779e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1201/tests/capture.py b/tasks/lite-xl__lite-xl-1201/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/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/lite-xl__lite-xl-1201/tests/instruction.md b/tasks/lite-xl__lite-xl-1201/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..613cb9c03ed799a41b8ba56721229692226331a2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Load fonts with UTF-8 filenames + +## Description + +This is another attempt of #1026 without the reference counting. + +Example config: +```lua +style.font = renderer.font.load("C:/msys64/home/takas/lite-xl/界面字母.ttf", 14 * SCALE) +``` +(Realistically, user might have lite-xl in some non-ACP home folder) + +without the patch: +![image](https://user-images.githubusercontent.com/20792268/201680381-2c9f78f2-e4b9-4cb9-907e-af42fdbbdb8b.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `66198eb32752`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1201/tests/oracle.patch b/tasks/lite-xl__lite-xl-1201/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e90b39bb3bc73a695345d64f4f7d99b3b75c4554 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/tests/oracle.patch @@ -0,0 +1,151 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 89bcdd50..e34c8504 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -8,6 +8,10 @@ + #include + #include FT_FREETYPE_H + ++#ifdef _WIN32 ++#include "utfconv.h" ++#endif ++ + #include "renderer.h" + #include "renwindow.h" + +@@ -51,7 +55,8 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; +- char path[1]; ++ unsigned char *file; ++ char path[]; + } RenFont; + + static const char* utf8_to_codepoint(const char *p, unsigned *dst) { +@@ -206,9 +211,48 @@ static void font_clear_glyph_cache(RenFont* font) { + } + + RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { +- FT_Face face; +- if (FT_New_Face( library, path, 0, &face)) ++ FT_Face face = NULL; ++ ++#ifdef _WIN32 ++ ++ HANDLE file = INVALID_HANDLE_VALUE; ++ DWORD read; ++ int font_file_len = 0; ++ unsigned char *font_file = NULL; ++ wchar_t *wpath = NULL; ++ ++ if ((wpath = utfconv_utf8towc(path)) == NULL) + return NULL; ++ ++ if ((file = CreateFileW(wpath, ++ GENERIC_READ, ++ 0, ++ NULL, ++ OPEN_EXISTING, ++ FILE_ATTRIBUTE_NORMAL, ++ NULL)) == INVALID_HANDLE_VALUE) ++ goto failure; ++ ++ if ((font_file_len = GetFileSize(file, NULL)) == INVALID_FILE_SIZE) ++ goto failure; ++ ++ font_file = check_alloc(malloc(font_file_len * sizeof(unsigned char))); ++ if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) ++ goto failure; ++ ++ CloseHandle(file); ++ free(wpath); ++ ++ if (FT_New_Memory_Face(library, font_file, read, 0, &face)) ++ goto failure; ++ ++#else ++ ++ if (FT_New_Face(library, path, 0, &face)) ++ return NULL; ++ ++#endif ++ + const int surface_scale = renwin_surface_scale(&window_renderer); + if (FT_Set_Pixel_Sizes(face, 0, (int)(size*surface_scale))) + goto failure; +@@ -223,6 +267,11 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + font->hinting = hinting; + font->style = style; + ++#ifdef _WIN32 ++ // we need to keep this for freetype ++ font->file = font_file; ++#endif ++ + if(FT_IS_SCALABLE(face)) + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); + if(!font->underline_thickness) font->underline_thickness = ceil((double) font->height / 14.0); +@@ -232,8 +281,15 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + font->space_advance = face->glyph->advance.x / 64.0f; + font->tab_advance = font->space_advance * 2; + return font; +- failure: +- FT_Done_Face(face); ++ ++failure: ++#ifdef _WIN32 ++ free(wpath); ++ free(font_file); ++ if (file != INVALID_HANDLE_VALUE) CloseHandle(file); ++#endif ++ if (face != NULL) ++ FT_Done_Face(face); + return NULL; + } + +@@ -252,6 +308,9 @@ const char* ren_font_get_path(RenFont *font) { + void ren_font_free(RenFont* font) { + font_clear_glyph_cache(font); + FT_Done_Face(font->face); ++#ifdef _WIN32 ++ free(font->file); ++#endif + free(font); + } + +diff --git a/src/utfconv.h b/src/utfconv.h +index 059b3071..59f98e4a 100644 +--- a/src/utfconv.h ++++ b/src/utfconv.h +@@ -1,6 +1,12 @@ + #ifndef MBSEC_H + #define MBSEC_H + ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ + #ifdef _WIN32 + + #include +@@ -8,7 +14,7 @@ + + #define UTFCONV_ERROR_INVALID_CONVERSION "Input contains invalid byte sequences." + +-LPWSTR utfconv_utf8towc(const char *str) { ++static UNUSED LPWSTR utfconv_utf8towc(const char *str) { + LPWSTR output; + int len; + +@@ -30,7 +36,7 @@ LPWSTR utfconv_utf8towc(const char *str) { + return output; + } + +-char *utfconv_wctoutf8(LPCWSTR str) { ++static UNUSED char *utfconv_wctoutf8(LPCWSTR str) { + char *output; + int len; + diff --git a/tasks/lite-xl__lite-xl-1201/tests/test.sh b/tasks/lite-xl__lite-xl-1201/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b53fd6e16284eedf330bb98f7adfaa3d7ebda99 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/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 66198eb327522974e51449de707971e09ed334c1 > "$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/lite-xl__lite-xl-1201/tests/verifier.py b/tasks/lite-xl__lite-xl-1201/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1201/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/lite-xl__lite-xl-1205/environment/Dockerfile b/tasks/lite-xl__lite-xl-1205/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fa957109c83cf496eeb65450f8c97adf4bfc2892 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c8e525c126fd15951a3c37d6652581406e7c6038 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c8e525c126fd15951a3c37d6652581406e7c6038 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c8e525c126fd15951a3c37d6652581406e7c6038 \ + && 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/lite-xl__lite-xl-1205/instruction.md b/tasks/lite-xl__lite-xl-1205/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78dfcd6e290261605675d1061f2dabaee45ebd02 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Windows font loading hotfix + +## Description + +Fixes bugs from #1201. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c8e525c126fd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1205/solution/patch.diff b/tasks/lite-xl__lite-xl-1205/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b992416d11078b406393f32b16ce68ff1655be32 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/solution/patch.diff @@ -0,0 +1,58 @@ +diff --git a/src/renderer.c b/src/renderer.c +index e34c8504..067df885 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -9,6 +9,7 @@ + #include FT_FREETYPE_H + + #ifdef _WIN32 ++#include + #include "utfconv.h" + #endif + +@@ -55,7 +56,10 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; ++#ifdef _WIN32 + unsigned char *file; ++ HANDLE file_handle; ++#endif + char path[]; + } RenFont; + +@@ -226,7 +230,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + + if ((file = CreateFileW(wpath, + GENERIC_READ, +- 0, ++ FILE_SHARE_READ, // or else we can't copy fonts + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, +@@ -240,8 +244,8 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) + goto failure; + +- CloseHandle(file); + free(wpath); ++ wpath = NULL; + + if (FT_New_Memory_Face(library, font_file, read, 0, &face)) + goto failure; +@@ -270,6 +274,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + #ifdef _WIN32 + // we need to keep this for freetype + font->file = font_file; ++ font->file_handle = file; + #endif + + if(FT_IS_SCALABLE(face)) +@@ -310,6 +315,7 @@ void ren_font_free(RenFont* font) { + FT_Done_Face(font->face); + #ifdef _WIN32 + free(font->file); ++ CloseHandle(font->file_handle); + #endif + free(font); + } diff --git a/tasks/lite-xl__lite-xl-1205/solution/solve.sh b/tasks/lite-xl__lite-xl-1205/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/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/lite-xl__lite-xl-1205/task.toml b/tasks/lite-xl__lite-xl-1205/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..33bf3c689a9e0a742480f986ec6df1c05e4ea429 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1205" +description = "Windows font loading hotfix" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c8e525c126fd15951a3c37d6652581406e7c6038" +reference = "https://github.com/lite-xl/lite-xl/pull/1205" +source_access = "auto" +built_at = "2026-11-16T16:09:56.267838+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d0e5e7793b9b4374fe6a0fb54011aa5b9e4f0e0439f929675063efeb3c570cfd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-17T05:09:38Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.278892+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4a4ac66c7429f254fbe8d77f8b5f1e37e4fab9afa38a380321f9f95f18ad7417" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1205/tests/capture.py b/tasks/lite-xl__lite-xl-1205/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/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/lite-xl__lite-xl-1205/tests/instruction.md b/tasks/lite-xl__lite-xl-1205/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78dfcd6e290261605675d1061f2dabaee45ebd02 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Windows font loading hotfix + +## Description + +Fixes bugs from #1201. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c8e525c126fd`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1205/tests/oracle.patch b/tasks/lite-xl__lite-xl-1205/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b992416d11078b406393f32b16ce68ff1655be32 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/tests/oracle.patch @@ -0,0 +1,58 @@ +diff --git a/src/renderer.c b/src/renderer.c +index e34c8504..067df885 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -9,6 +9,7 @@ + #include FT_FREETYPE_H + + #ifdef _WIN32 ++#include + #include "utfconv.h" + #endif + +@@ -55,7 +56,10 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; ++#ifdef _WIN32 + unsigned char *file; ++ HANDLE file_handle; ++#endif + char path[]; + } RenFont; + +@@ -226,7 +230,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + + if ((file = CreateFileW(wpath, + GENERIC_READ, +- 0, ++ FILE_SHARE_READ, // or else we can't copy fonts + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, +@@ -240,8 +244,8 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) + goto failure; + +- CloseHandle(file); + free(wpath); ++ wpath = NULL; + + if (FT_New_Memory_Face(library, font_file, read, 0, &face)) + goto failure; +@@ -270,6 +274,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + #ifdef _WIN32 + // we need to keep this for freetype + font->file = font_file; ++ font->file_handle = file; + #endif + + if(FT_IS_SCALABLE(face)) +@@ -310,6 +315,7 @@ void ren_font_free(RenFont* font) { + FT_Done_Face(font->face); + #ifdef _WIN32 + free(font->file); ++ CloseHandle(font->file_handle); + #endif + free(font); + } diff --git a/tasks/lite-xl__lite-xl-1205/tests/test.sh b/tasks/lite-xl__lite-xl-1205/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d50072f93e0635528b81d58707a6c17fca341675 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/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 c8e525c126fd15951a3c37d6652581406e7c6038 > "$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/lite-xl__lite-xl-1205/tests/verifier.py b/tasks/lite-xl__lite-xl-1205/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1205/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/lite-xl__lite-xl-1211/environment/Dockerfile b/tasks/lite-xl__lite-xl-1211/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f0dec545d99e7eb39ed9769c3bd0506e6bfd4240 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7fa51bb7abe61a7108e3a519df13803c3b82e7cd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7fa51bb7abe61a7108e3a519df13803c3b82e7cd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7fa51bb7abe61a7108e3a519df13803c3b82e7cd \ + && 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/lite-xl__lite-xl-1211/instruction.md b/tasks/lite-xl__lite-xl-1211/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f1244ecc09343456c89a57b12bfb1ff64a809ba3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** better error messages for checkcolor + +## Description + +`checkcolor` is used by renderer functions that accept color as input. When something went wrong (especially with invalid arguments, the error message can be cryptic. This PR fixes that. + +Before: +![image](https://user-images.githubusercontent.com/20792268/203201190-b48c0191-7d3c-442f-ae4a-fcead1d9a3fb.png) + +After: +![image](https://user-images.githubusercontent.com/20792268/203201198-52fd7a90-f22b-4169-a33b-f535d130d4d3.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fa51bb7abe6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1211/solution/patch.diff b/tasks/lite-xl__lite-xl-1211/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1cafd57846a3a5e0e5a67483ad86c69e9d6c03c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/solution/patch.diff @@ -0,0 +1,68 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index 383618b4..9e69dffb 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -2,6 +2,7 @@ + #include "api.h" + #include "../renderer.h" + #include "../rencache.h" ++#include "lua.h" + + // a reference index to a table that stores the fonts + static int RENDERER_FONT_REF = LUA_NOREF; +@@ -215,20 +216,47 @@ static int f_font_set_size(lua_State *L) { + return 0; + } + ++static int color_value_error(lua_State *L, int idx, int table_idx) { ++ const char *type, *msg; ++ // generate an appropriate error message ++ if (luaL_getmetafield(L, -1, "__name") == LUA_TSTRING) { ++ type = lua_tostring(L, -1); // metatable name ++ } else if (lua_type(L, -1) == LUA_TLIGHTUSERDATA) { ++ type = "light userdata"; // special name for light userdata ++ } else { ++ type = lua_typename(L, lua_type(L, -1)); // default name ++ } ++ // the reason it went through so much hoops is to generate the correct error ++ // message (with function name and proper index). ++ msg = lua_pushfstring(L, "table[%d]: %s expected, got %s", table_idx, lua_typename(L, LUA_TNUMBER), type); ++ return luaL_argerror(L, idx, msg); ++} ++ ++static int get_color_value(lua_State *L, int idx, int table_idx) { ++ lua_rawgeti(L, idx, table_idx); ++ return lua_isnumber(L, -1) ? lua_tonumber(L, -1) : color_value_error(L, idx, table_idx); ++} ++ ++static int get_color_value_opt(lua_State *L, int idx, int table_idx, int default_value) { ++ lua_rawgeti(L, idx, table_idx); ++ if (lua_isnoneornil(L, -1)) ++ return default_value; ++ else if (lua_isnumber(L, -1)) ++ return lua_tonumber(L, -1); ++ else ++ return color_value_error(L, idx, table_idx); ++} ++ + static RenColor checkcolor(lua_State *L, int idx, int def) { + RenColor color; + if (lua_isnoneornil(L, idx)) { + return (RenColor) { def, def, def, 255 }; + } + luaL_checktype(L, idx, LUA_TTABLE); +- lua_rawgeti(L, idx, 1); +- lua_rawgeti(L, idx, 2); +- lua_rawgeti(L, idx, 3); +- lua_rawgeti(L, idx, 4); +- color.r = luaL_checknumber(L, -4); +- color.g = luaL_checknumber(L, -3); +- color.b = luaL_checknumber(L, -2); +- color.a = luaL_optnumber(L, -1, 255); ++ color.r = get_color_value(L, idx, 1); ++ color.g = get_color_value(L, idx, 2); ++ color.b = get_color_value(L, idx, 3); ++ color.a = get_color_value_opt(L, idx, 4, 255); + lua_pop(L, 4); + return color; + } diff --git a/tasks/lite-xl__lite-xl-1211/solution/solve.sh b/tasks/lite-xl__lite-xl-1211/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/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/lite-xl__lite-xl-1211/task.toml b/tasks/lite-xl__lite-xl-1211/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b6f5c0363b9fbc2da74e13e96f26c783b13bff6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1211" +description = "better error messages for checkcolor" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7fa51bb7abe61a7108e3a519df13803c3b82e7cd" +reference = "https://github.com/lite-xl/lite-xl/pull/1211" +source_access = "auto" +built_at = "2026-11-16T16:09:56.263489+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e9d11d99ccfb21f927f4f1faebc1d0e6534a51b562166a266c5696f2323faab7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-30T05:38:35Z" +diff_format = "unified" +context_files = [ + "src/api/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 44 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.279327+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4c19f1479f3983ee3da78a00da8456d4de44615e5cf6a1ec908237b83ffea8aa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1211/tests/capture.py b/tasks/lite-xl__lite-xl-1211/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/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/lite-xl__lite-xl-1211/tests/instruction.md b/tasks/lite-xl__lite-xl-1211/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f1244ecc09343456c89a57b12bfb1ff64a809ba3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** better error messages for checkcolor + +## Description + +`checkcolor` is used by renderer functions that accept color as input. When something went wrong (especially with invalid arguments, the error message can be cryptic. This PR fixes that. + +Before: +![image](https://user-images.githubusercontent.com/20792268/203201190-b48c0191-7d3c-442f-ae4a-fcead1d9a3fb.png) + +After: +![image](https://user-images.githubusercontent.com/20792268/203201198-52fd7a90-f22b-4169-a33b-f535d130d4d3.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fa51bb7abe6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1211/tests/oracle.patch b/tasks/lite-xl__lite-xl-1211/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1cafd57846a3a5e0e5a67483ad86c69e9d6c03c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/tests/oracle.patch @@ -0,0 +1,68 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index 383618b4..9e69dffb 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -2,6 +2,7 @@ + #include "api.h" + #include "../renderer.h" + #include "../rencache.h" ++#include "lua.h" + + // a reference index to a table that stores the fonts + static int RENDERER_FONT_REF = LUA_NOREF; +@@ -215,20 +216,47 @@ static int f_font_set_size(lua_State *L) { + return 0; + } + ++static int color_value_error(lua_State *L, int idx, int table_idx) { ++ const char *type, *msg; ++ // generate an appropriate error message ++ if (luaL_getmetafield(L, -1, "__name") == LUA_TSTRING) { ++ type = lua_tostring(L, -1); // metatable name ++ } else if (lua_type(L, -1) == LUA_TLIGHTUSERDATA) { ++ type = "light userdata"; // special name for light userdata ++ } else { ++ type = lua_typename(L, lua_type(L, -1)); // default name ++ } ++ // the reason it went through so much hoops is to generate the correct error ++ // message (with function name and proper index). ++ msg = lua_pushfstring(L, "table[%d]: %s expected, got %s", table_idx, lua_typename(L, LUA_TNUMBER), type); ++ return luaL_argerror(L, idx, msg); ++} ++ ++static int get_color_value(lua_State *L, int idx, int table_idx) { ++ lua_rawgeti(L, idx, table_idx); ++ return lua_isnumber(L, -1) ? lua_tonumber(L, -1) : color_value_error(L, idx, table_idx); ++} ++ ++static int get_color_value_opt(lua_State *L, int idx, int table_idx, int default_value) { ++ lua_rawgeti(L, idx, table_idx); ++ if (lua_isnoneornil(L, -1)) ++ return default_value; ++ else if (lua_isnumber(L, -1)) ++ return lua_tonumber(L, -1); ++ else ++ return color_value_error(L, idx, table_idx); ++} ++ + static RenColor checkcolor(lua_State *L, int idx, int def) { + RenColor color; + if (lua_isnoneornil(L, idx)) { + return (RenColor) { def, def, def, 255 }; + } + luaL_checktype(L, idx, LUA_TTABLE); +- lua_rawgeti(L, idx, 1); +- lua_rawgeti(L, idx, 2); +- lua_rawgeti(L, idx, 3); +- lua_rawgeti(L, idx, 4); +- color.r = luaL_checknumber(L, -4); +- color.g = luaL_checknumber(L, -3); +- color.b = luaL_checknumber(L, -2); +- color.a = luaL_optnumber(L, -1, 255); ++ color.r = get_color_value(L, idx, 1); ++ color.g = get_color_value(L, idx, 2); ++ color.b = get_color_value(L, idx, 3); ++ color.a = get_color_value_opt(L, idx, 4, 255); + lua_pop(L, 4); + return color; + } diff --git a/tasks/lite-xl__lite-xl-1211/tests/test.sh b/tasks/lite-xl__lite-xl-1211/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c72e282f87b54521a8957abd1894dd536aee0abb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/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 7fa51bb7abe61a7108e3a519df13803c3b82e7cd > "$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/lite-xl__lite-xl-1211/tests/verifier.py b/tasks/lite-xl__lite-xl-1211/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1211/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/lite-xl__lite-xl-1243/environment/Dockerfile b/tasks/lite-xl__lite-xl-1243/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f8d290cf0452156ed3b981cabb2cafc1c253c40f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e152db2cce78c12fe771492060277133309d55f9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e152db2cce78c12fe771492060277133309d55f9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e152db2cce78c12fe771492060277133309d55f9 \ + && 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/lite-xl__lite-xl-1243/instruction.md b/tasks/lite-xl__lite-xl-1243/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ca906459c57185a0405743398d99c44760b603ec --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix some syntax errors + +## Description + +Some fixes for uncommon code paths (when compiling for everything other than linux, windows, mac, etc.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e152db2cce78`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1243/solution/patch.diff b/tasks/lite-xl__lite-xl-1243/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e35a8bc387899b54a23e19dcf7c85a46e57c28c0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/solution/patch.diff @@ -0,0 +1,35 @@ +diff --git a/src/main.c b/src/main.c +index 03edef6b..10910056 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -5,16 +5,16 @@ + #include "rencache.h" + #include "renderer.h" + ++#include ++ + #ifdef _WIN32 + #include +-#elif __linux__ ++#elif defined(__linux__) + #include +- #include +-#elif __APPLE__ ++#elif defined(__APPLE__) + #include +-#elif __FreeBSD__ ++#elif defined(__FreeBSD__) + #include +- #include + #endif + + +@@ -51,7 +51,7 @@ static void get_exe_filename(char *buf, int sz) { + const int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; + sysctl(mib, 4, buf, &len, NULL, 0); + #else +- *buf = NULL; ++ *buf = 0; + #endif + } + diff --git a/tasks/lite-xl__lite-xl-1243/solution/solve.sh b/tasks/lite-xl__lite-xl-1243/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/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/lite-xl__lite-xl-1243/task.toml b/tasks/lite-xl__lite-xl-1243/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52b602d16f1dcb052efc7c99361c064cbe8496fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1243" +description = "Fix some syntax errors" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e152db2cce78c12fe771492060277133309d55f9" +reference = "https://github.com/lite-xl/lite-xl/pull/1243" +source_access = "auto" +built_at = "2026-11-16T16:09:56.260423+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:31b0e2e0fa780977786e574b916c5228a529aa132233d3c22d8dd23a10e502bc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-12-20T22:11:05Z" +diff_format = "unified" +context_files = [ + "src/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.279796+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bfa970f95167cec0e63af965eb9bf6323b8b56a318724704c51d8b4ca0400b64" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1243/tests/capture.py b/tasks/lite-xl__lite-xl-1243/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/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/lite-xl__lite-xl-1243/tests/instruction.md b/tasks/lite-xl__lite-xl-1243/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ca906459c57185a0405743398d99c44760b603ec --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix some syntax errors + +## Description + +Some fixes for uncommon code paths (when compiling for everything other than linux, windows, mac, etc.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e152db2cce78`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1243/tests/oracle.patch b/tasks/lite-xl__lite-xl-1243/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e35a8bc387899b54a23e19dcf7c85a46e57c28c0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/tests/oracle.patch @@ -0,0 +1,35 @@ +diff --git a/src/main.c b/src/main.c +index 03edef6b..10910056 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -5,16 +5,16 @@ + #include "rencache.h" + #include "renderer.h" + ++#include ++ + #ifdef _WIN32 + #include +-#elif __linux__ ++#elif defined(__linux__) + #include +- #include +-#elif __APPLE__ ++#elif defined(__APPLE__) + #include +-#elif __FreeBSD__ ++#elif defined(__FreeBSD__) + #include +- #include + #endif + + +@@ -51,7 +51,7 @@ static void get_exe_filename(char *buf, int sz) { + const int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; + sysctl(mib, 4, buf, &len, NULL, 0); + #else +- *buf = NULL; ++ *buf = 0; + #endif + } + diff --git a/tasks/lite-xl__lite-xl-1243/tests/test.sh b/tasks/lite-xl__lite-xl-1243/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4e584624d6e9f78e4adeabb2fd1df68aa99ad23 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/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 e152db2cce78c12fe771492060277133309d55f9 > "$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/lite-xl__lite-xl-1243/tests/verifier.py b/tasks/lite-xl__lite-xl-1243/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1243/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/lite-xl__lite-xl-1363/environment/Dockerfile b/tasks/lite-xl__lite-xl-1363/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6be127879a4a0b2628f0ecdbecbfd967f4eba278 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8aa97291fe8a7a3f1d1bcd618b0834d1a9e1cf03 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8aa97291fe8a7a3f1d1bcd618b0834d1a9e1cf03 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8aa97291fe8a7a3f1d1bcd618b0834d1a9e1cf03 \ + && 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/lite-xl__lite-xl-1363/instruction.md b/tasks/lite-xl__lite-xl-1363/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..049157bb82a55c2a5b4c65ebcad60ec393c08e4c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: exec() error not returned to parent + +## Description + +This fixes a weird issue where when any of the child process syscalls fails, errors are not sent back to parent but is instead sent to stderr. This is not the case with previous [reproc-based API](https://github.com/DaanDeMeyer/reproc/blob/08675b1b1f1317afa4c8b39fa3a180e7b7ec4ced/reproc/src/process.posix.c#L201) and can be hard to debug. + +Squash me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8aa97291fe8a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1363/solution/patch.diff b/tasks/lite-xl__lite-xl-1363/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..634fd4a8113c04b148485fb65106c4c4910569bc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/solution/patch.diff @@ -0,0 +1,81 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 60efe5f9..081e6ab6 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -293,6 +293,7 @@ static int process_start(lua_State* L) { + CloseHandle(self->process_information.hProcess); + CloseHandle(self->process_information.hThread); + #else ++ int control_pipe[2] = { 0 }; + for (int i = 0; i < 3; ++i) { // Make only the parents fd's non-blocking. Children should block. + if (pipe(self->child_pipes[i]) || fcntl(self->child_pipes[i][i == STDIN_FD ? 1 : 0], F_SETFL, O_NONBLOCK) == -1) { + lua_pushfstring(L, "Error creating pipes: %s", strerror(errno)); +@@ -300,12 +301,25 @@ static int process_start(lua_State* L) { + goto cleanup; + } + } ++ // create a pipe to get the exit code of exec() ++ if (pipe(control_pipe) == -1) { ++ lua_pushfstring(L, "Error creating control pipe: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } ++ if (fcntl(control_pipe[1], F_SETFD, FD_CLOEXEC) == -1) { ++ lua_pushfstring(L, "Error setting FD_CLOEXEC: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } ++ + self->pid = (long)fork(); + if (self->pid < 0) { + lua_pushfstring(L, "Error running fork: %s.", strerror(errno)); + retval = -1; + goto cleanup; + } else if (!self->pid) { ++ // child process + if (!detach) + setpgid(0,0); + for (int stream = 0; stream < 3; ++stream) { +@@ -320,12 +334,39 @@ static int process_start(lua_State* L) { + for (set = 0; set < env_len && setenv(env_names[set], env_values[set], 1) == 0; ++set); + if (set == env_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) + execvp(cmd[0], (char** const)cmd); +- const char* msg = strerror(errno); +- size_t result = write(STDERR_FD, msg, strlen(msg)+1); +- _exit(result == strlen(msg)+1 ? -1 : -2); ++ write(control_pipe[1], &errno, sizeof(errno)); ++ _exit(-1); ++ } ++ // close our write side so we can read from child ++ close(control_pipe[1]); ++ control_pipe[1] = 0; ++ ++ // wait for child process to respond ++ int sz, process_rc; ++ while ((sz = read(control_pipe[0], &process_rc, sizeof(int))) == -1) { ++ if (errno == EPIPE) break; ++ if (errno != EINTR) { ++ lua_pushfstring(L, "Error getting child process status: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } + } ++ ++ if (sz) { ++ // read something from pipe; exec failed ++ int status; ++ waitpid(self->pid, &status, 0); ++ lua_pushfstring(L, "Error creating child process: %s", strerror(process_rc)); ++ retval = -1; ++ goto cleanup; ++ } ++ + #endif + cleanup: ++ #ifndef _WIN32 ++ if (control_pipe[0]) close(control_pipe[0]); ++ if (control_pipe[1]) close(control_pipe[1]); ++ #endif + for (size_t i = 0; i < env_len; ++i) { + free((char*)env_names[i]); + free((char*)env_values[i]); diff --git a/tasks/lite-xl__lite-xl-1363/solution/solve.sh b/tasks/lite-xl__lite-xl-1363/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/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/lite-xl__lite-xl-1363/task.toml b/tasks/lite-xl__lite-xl-1363/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6cc4e1a5b78e226be8524597e976b2c2f8b6750f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1363" +description = "fix: exec() error not returned to parent" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "8aa97291fe8a7a3f1d1bcd618b0834d1a9e1cf03" +reference = "https://github.com/lite-xl/lite-xl/pull/1363" +source_access = "auto" +built_at = "2026-11-16T16:09:56.259194+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4409aaabf5aff0b3a696211976972a6cfe2d747cc5f54fa5f4e08cc33fcbfc7b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-01-31T22:26:15Z" +diff_format = "unified" +context_files = [ + "src/api/process.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 47 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.280244+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:624332bdd10d9eea81c69a0d76cc6965ed4940f9b3295645355dfbbf0cc2de05" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1363/tests/capture.py b/tasks/lite-xl__lite-xl-1363/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/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/lite-xl__lite-xl-1363/tests/instruction.md b/tasks/lite-xl__lite-xl-1363/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..049157bb82a55c2a5b4c65ebcad60ec393c08e4c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: exec() error not returned to parent + +## Description + +This fixes a weird issue where when any of the child process syscalls fails, errors are not sent back to parent but is instead sent to stderr. This is not the case with previous [reproc-based API](https://github.com/DaanDeMeyer/reproc/blob/08675b1b1f1317afa4c8b39fa3a180e7b7ec4ced/reproc/src/process.posix.c#L201) and can be hard to debug. + +Squash me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8aa97291fe8a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1363/tests/oracle.patch b/tasks/lite-xl__lite-xl-1363/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..634fd4a8113c04b148485fb65106c4c4910569bc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/tests/oracle.patch @@ -0,0 +1,81 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 60efe5f9..081e6ab6 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -293,6 +293,7 @@ static int process_start(lua_State* L) { + CloseHandle(self->process_information.hProcess); + CloseHandle(self->process_information.hThread); + #else ++ int control_pipe[2] = { 0 }; + for (int i = 0; i < 3; ++i) { // Make only the parents fd's non-blocking. Children should block. + if (pipe(self->child_pipes[i]) || fcntl(self->child_pipes[i][i == STDIN_FD ? 1 : 0], F_SETFL, O_NONBLOCK) == -1) { + lua_pushfstring(L, "Error creating pipes: %s", strerror(errno)); +@@ -300,12 +301,25 @@ static int process_start(lua_State* L) { + goto cleanup; + } + } ++ // create a pipe to get the exit code of exec() ++ if (pipe(control_pipe) == -1) { ++ lua_pushfstring(L, "Error creating control pipe: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } ++ if (fcntl(control_pipe[1], F_SETFD, FD_CLOEXEC) == -1) { ++ lua_pushfstring(L, "Error setting FD_CLOEXEC: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } ++ + self->pid = (long)fork(); + if (self->pid < 0) { + lua_pushfstring(L, "Error running fork: %s.", strerror(errno)); + retval = -1; + goto cleanup; + } else if (!self->pid) { ++ // child process + if (!detach) + setpgid(0,0); + for (int stream = 0; stream < 3; ++stream) { +@@ -320,12 +334,39 @@ static int process_start(lua_State* L) { + for (set = 0; set < env_len && setenv(env_names[set], env_values[set], 1) == 0; ++set); + if (set == env_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) + execvp(cmd[0], (char** const)cmd); +- const char* msg = strerror(errno); +- size_t result = write(STDERR_FD, msg, strlen(msg)+1); +- _exit(result == strlen(msg)+1 ? -1 : -2); ++ write(control_pipe[1], &errno, sizeof(errno)); ++ _exit(-1); ++ } ++ // close our write side so we can read from child ++ close(control_pipe[1]); ++ control_pipe[1] = 0; ++ ++ // wait for child process to respond ++ int sz, process_rc; ++ while ((sz = read(control_pipe[0], &process_rc, sizeof(int))) == -1) { ++ if (errno == EPIPE) break; ++ if (errno != EINTR) { ++ lua_pushfstring(L, "Error getting child process status: %s", strerror(errno)); ++ retval = -1; ++ goto cleanup; ++ } + } ++ ++ if (sz) { ++ // read something from pipe; exec failed ++ int status; ++ waitpid(self->pid, &status, 0); ++ lua_pushfstring(L, "Error creating child process: %s", strerror(process_rc)); ++ retval = -1; ++ goto cleanup; ++ } ++ + #endif + cleanup: ++ #ifndef _WIN32 ++ if (control_pipe[0]) close(control_pipe[0]); ++ if (control_pipe[1]) close(control_pipe[1]); ++ #endif + for (size_t i = 0; i < env_len; ++i) { + free((char*)env_names[i]); + free((char*)env_values[i]); diff --git a/tasks/lite-xl__lite-xl-1363/tests/test.sh b/tasks/lite-xl__lite-xl-1363/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..935943b6a18bfd9befab164727c12fd1408b612c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/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 8aa97291fe8a7a3f1d1bcd618b0834d1a9e1cf03 > "$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/lite-xl__lite-xl-1363/tests/verifier.py b/tasks/lite-xl__lite-xl-1363/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1363/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/lite-xl__lite-xl-1396/environment/Dockerfile b/tasks/lite-xl__lite-xl-1396/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc2f23b50959a8387b3b7896a99bd14440ba4b52 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 \ + && 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/lite-xl__lite-xl-1396/instruction.md b/tasks/lite-xl__lite-xl-1396/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7dcc78e1e3313230f708342ffaa2f03b0b058ff8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix invalid EXEFILE and EXEDIR on Windows + +## Description + +This is because we still use GetModuleFileName instead of GetModuleFileNameW which will return ACP instead of UTF-8. This should allow DATADIR to be in UTF-8. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2035886fcd8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1396/solution/patch.diff b/tasks/lite-xl__lite-xl-1396/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f429c000ca7fe6042da122b49ac328f61b2abad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/solution/patch.diff @@ -0,0 +1,38 @@ +diff --git a/src/main.c b/src/main.c +index c5e15707..5adbfac1 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -32,8 +32,18 @@ static double get_scale(void) { + + static void get_exe_filename(char *buf, int sz) { + #if _WIN32 +- int len = GetModuleFileName(NULL, buf, sz - 1); +- buf[len] = '\0'; ++ int len; ++ wchar_t *buf_w = malloc(sizeof(wchar_t) * sz); ++ if (buf_w) { ++ len = GetModuleFileNameW(NULL, buf_w, sz - 1); ++ buf_w[len] = L'\0'; ++ // if the conversion failed we'll empty the string ++ if (!WideCharToMultiByte(CP_UTF8, 0, buf_w, -1, buf, sz, NULL, NULL)) ++ buf[0] = '\0'; ++ free(buf_w); ++ } else { ++ buf[0] = '\0'; ++ } + #elif __linux__ + char path[] = "/proc/self/exe"; + ssize_t len = readlink(path, buf, sz - 1); +@@ -220,9 +230,10 @@ init_lua: + const char *init_lite_code = \ + "local core\n" + "xpcall(function()\n" ++ " local match = require('utf8extra').match\n" + " HOME = os.getenv('" LITE_OS_HOME "')\n" +- " local exedir = EXEFILE:match('^(.*)" LITE_PATHSEP_PATTERN LITE_NONPATHSEP_PATTERN "$')\n" +- " local prefix = os.getenv('LITE_PREFIX') or exedir:match('^(.*)" LITE_PATHSEP_PATTERN "bin$')\n" ++ " local exedir = match(EXEFILE, '^(.*)" LITE_PATHSEP_PATTERN LITE_NONPATHSEP_PATTERN "$')\n" ++ " local prefix = os.getenv('LITE_PREFIX') or match(exedir, '^(.*)" LITE_PATHSEP_PATTERN "bin$')\n" + " dofile((MACOS_RESOURCES or (prefix and prefix .. '/share/lite-xl' or exedir .. '/data')) .. '/core/start.lua')\n" + " core = require(os.getenv('LITE_XL_RUNTIME') or 'core')\n" + " core.init()\n" diff --git a/tasks/lite-xl__lite-xl-1396/solution/solve.sh b/tasks/lite-xl__lite-xl-1396/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/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/lite-xl__lite-xl-1396/task.toml b/tasks/lite-xl__lite-xl-1396/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7128d8b83fd64af75b8eca4f22f7548f627cfd19 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1396" +description = "Fix invalid EXEFILE and EXEDIR on Windows" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9" +reference = "https://github.com/lite-xl/lite-xl/pull/1396" +source_access = "auto" +built_at = "2026-11-16T16:09:56.253339+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:226d7886855f5d0530fa2a6bdef99be0594b5b66d760bb16369be3f8af43664d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-07T17:06:01Z" +diff_format = "unified" +context_files = [ + "src/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.280683+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:61bfa8966694346a32d9492ea3d2ab22004a0ae1fbbbe28f50854d32bdce1916" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1396/tests/capture.py b/tasks/lite-xl__lite-xl-1396/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/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/lite-xl__lite-xl-1396/tests/instruction.md b/tasks/lite-xl__lite-xl-1396/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7dcc78e1e3313230f708342ffaa2f03b0b058ff8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix invalid EXEFILE and EXEDIR on Windows + +## Description + +This is because we still use GetModuleFileName instead of GetModuleFileNameW which will return ACP instead of UTF-8. This should allow DATADIR to be in UTF-8. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2035886fcd8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1396/tests/oracle.patch b/tasks/lite-xl__lite-xl-1396/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3f429c000ca7fe6042da122b49ac328f61b2abad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/tests/oracle.patch @@ -0,0 +1,38 @@ +diff --git a/src/main.c b/src/main.c +index c5e15707..5adbfac1 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -32,8 +32,18 @@ static double get_scale(void) { + + static void get_exe_filename(char *buf, int sz) { + #if _WIN32 +- int len = GetModuleFileName(NULL, buf, sz - 1); +- buf[len] = '\0'; ++ int len; ++ wchar_t *buf_w = malloc(sizeof(wchar_t) * sz); ++ if (buf_w) { ++ len = GetModuleFileNameW(NULL, buf_w, sz - 1); ++ buf_w[len] = L'\0'; ++ // if the conversion failed we'll empty the string ++ if (!WideCharToMultiByte(CP_UTF8, 0, buf_w, -1, buf, sz, NULL, NULL)) ++ buf[0] = '\0'; ++ free(buf_w); ++ } else { ++ buf[0] = '\0'; ++ } + #elif __linux__ + char path[] = "/proc/self/exe"; + ssize_t len = readlink(path, buf, sz - 1); +@@ -220,9 +230,10 @@ init_lua: + const char *init_lite_code = \ + "local core\n" + "xpcall(function()\n" ++ " local match = require('utf8extra').match\n" + " HOME = os.getenv('" LITE_OS_HOME "')\n" +- " local exedir = EXEFILE:match('^(.*)" LITE_PATHSEP_PATTERN LITE_NONPATHSEP_PATTERN "$')\n" +- " local prefix = os.getenv('LITE_PREFIX') or exedir:match('^(.*)" LITE_PATHSEP_PATTERN "bin$')\n" ++ " local exedir = match(EXEFILE, '^(.*)" LITE_PATHSEP_PATTERN LITE_NONPATHSEP_PATTERN "$')\n" ++ " local prefix = os.getenv('LITE_PREFIX') or match(exedir, '^(.*)" LITE_PATHSEP_PATTERN "bin$')\n" + " dofile((MACOS_RESOURCES or (prefix and prefix .. '/share/lite-xl' or exedir .. '/data')) .. '/core/start.lua')\n" + " core = require(os.getenv('LITE_XL_RUNTIME') or 'core')\n" + " core.init()\n" diff --git a/tasks/lite-xl__lite-xl-1396/tests/test.sh b/tasks/lite-xl__lite-xl-1396/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e77caa502c3fd45683fa75b2847f180af151a27a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/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 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 > "$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/lite-xl__lite-xl-1396/tests/verifier.py b/tasks/lite-xl__lite-xl-1396/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1396/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/lite-xl__lite-xl-1397/environment/Dockerfile b/tasks/lite-xl__lite-xl-1397/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc2f23b50959a8387b3b7896a99bd14440ba4b52 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 \ + && 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/lite-xl__lite-xl-1397/instruction.md b/tasks/lite-xl__lite-xl-1397/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8ac469aefc085f2a3ccf51bf94ce42fa1f25908e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Fix os.getenv() not supporting UTF-8 output + +## Description + +Mostly likely will fix #1359. + +EDIT: +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2035886fcd8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1397/solution/patch.diff b/tasks/lite-xl__lite-xl-1397/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8f5a8ab7e0e319add3c15c95c4706264dcccbd69 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/solution/patch.diff @@ -0,0 +1,124 @@ +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +index 7785b8ea..31fec364 100644 +--- a/resources/windows/001-lua-unicode.diff ++++ b/resources/windows/001-lua-unicode.diff +@@ -1,6 +1,6 @@ +-diff -ruN lua-5.4.4/meson.build lua-5.4.4-mod/meson.build +---- lua-5.4.4/meson.build 2022-11-16 10:33:38.424383300 +0800 +-+++ lua-5.4.4-mod/meson.build 2022-11-16 09:40:57.697918000 +0800 ++diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build ++--- lua-5.4.4\meson.build Wed Feb 22 18:16:56 2023 +++++ lua-5.4.4-patched\meson.build Wed Feb 22 04:10:01 2023 + @@ -85,6 +85,7 @@ + 'src/lutf8lib.c', + 'src/lvm.c', +@@ -9,9 +9,9 @@ diff -ruN lua-5.4.4/meson.build lua-5.4.4-mod/meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-mod/src/luaconf.h +---- lua-5.4.4/src/luaconf.h 2022-01-13 19:24:43.000000000 +0800 +-+++ lua-5.4.4-mod/src/luaconf.h 2022-11-16 09:40:57.703926000 +0800 ++diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h ++--- lua-5.4.4\src\luaconf.h Thu Jan 13 19:24:43 2022 +++++ lua-5.4.4-patched\src\luaconf.h Wed Feb 22 04:10:02 2023 + @@ -782,5 +782,15 @@ + + +@@ -28,9 +28,9 @@ diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-mod/src/luaconf.h + + + #endif + +-diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-mod/src/Makefile +---- lua-5.4.4/src/Makefile 2021-07-15 22:01:52.000000000 +0800 +-+++ lua-5.4.4-mod/src/Makefile 2022-11-16 09:40:57.708921800 +0800 ++diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile ++--- lua-5.4.4\src\Makefile Thu Jul 15 22:01:52 2021 +++++ lua-5.4.4-patched\src\Makefile Wed Feb 22 04:10:02 2023 + @@ -33,7 +33,7 @@ + PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris + +@@ -40,10 +40,10 @@ diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-mod/src/Makefile + LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o + BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) + +-diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c +---- lua-5.4.4/src/utf8_wrappers.c 1970-01-01 07:30:00.000000000 +0730 +-+++ lua-5.4.4-mod/src/utf8_wrappers.c 2022-11-16 10:09:04.583866600 +0800 +-@@ -0,0 +1,101 @@ ++diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c ++--- lua-5.4.4\src\utf8_wrappers.c Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched\src\utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++@@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. + + * +@@ -58,12 +58,17 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c + +#include + +#include + + +++// A environment variable has the maximum length of 32767 characters +++// including the terminator. +++#define MAX_ENV_SIZE 32767 + +// Set a high limit in case long paths are enabled. + +#define MAX_PATH_SIZE 4096 + +#define MAX_MODE_SIZE 128 + +// cmd.exe argument length is reportedly limited to 8192. + +#define MAX_CMD_SIZE 8192 + + +++static char env_value[MAX_ENV_SIZE]; +++ + +FILE *fopen_utf8(const char *pathname, const char *mode) { + + wchar_t pathname_w[MAX_PATH_SIZE]; + + wchar_t mode_w[MAX_MODE_SIZE]; +@@ -144,11 +149,34 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c + + } + + return LoadLibraryExW(pathname_w, hFile, dwFlags); + +} +++ +++char* getenv_utf8(const char *varname) { +++ /** This implementation is not thread safe. +++ * The string is only valid until the next call to getenv. +++ * This behavior is allowed per POSIX.1-2017 where it was said that: +++ * > The returned string pointer might be invalidated or the string content might be overwritten by a subsequent call to getenv(), setenv(), unsetenv(), or (if supported) putenv() but they shall not be affected by a call to any other function in this volume of POSIX.1-2017. +++ * > The returned string pointer might also be invalidated if the calling thread is terminated. +++ * > The getenv() function need not be thread-safe. +++ */ +++ wchar_t *value_w; +++ wchar_t varname_w[MAX_ENV_SIZE]; +++ +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, varname, -1, varname_w, MAX_ENV_SIZE)) +++ return NULL; +++ value_w = _wgetenv((const wchar_t *) varname_w); +++ if (!value_w) +++ return NULL; +++ +++ if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value_w, -1, env_value, MAX_ENV_SIZE, NULL, NULL)) +++ return NULL; +++ +++ return env_value; +++} + +#endif +-diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-mod/src/utf8_wrappers.h +---- lua-5.4.4/src/utf8_wrappers.h 1970-01-01 07:30:00.000000000 +0730 +-+++ lua-5.4.4-mod/src/utf8_wrappers.h 2022-11-16 10:29:46.044102000 +0800 +-@@ -0,0 +1,44 @@ ++diff -ruN lua-5.4.4\src\utf8_wrappers.h lua-5.4.4-patched\src\utf8_wrappers.h ++--- lua-5.4.4\src\utf8_wrappers.h Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched\src\utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++@@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. + + * +@@ -180,9 +208,11 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-mod/src/utf8_wrappers.h + +int remove_utf8(const char *pathname); + +int rename_utf8(const char *oldpath, const char *newpath); + +int system_utf8(const char *command); +++char *getenv_utf8(const char *varname); + +#define remove remove_utf8 + +#define rename rename_utf8 + +#define system system_utf8 +++#define getenv getenv_utf8 + +#endif + + + +#ifdef loadlib_c diff --git a/tasks/lite-xl__lite-xl-1397/solution/solve.sh b/tasks/lite-xl__lite-xl-1397/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/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/lite-xl__lite-xl-1397/task.toml b/tasks/lite-xl__lite-xl-1397/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..868d3e079830c598efb7faadc5919f9d0c35d69a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1397" +description = "Fix os.getenv() not supporting UTF-8 output" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9" +reference = "https://github.com/lite-xl/lite-xl/pull/1397" +source_access = "auto" +built_at = "2026-11-16T16:09:56.251934+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2f100a405f7d0a5ef652ebf5d7342767e930f7258c4cc95ced7dda8f7e5a0a03" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-07T17:11:02Z" +diff_format = "unified" +context_files = [ + "resources/windows/001-lua-unicode.diff", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 64 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.281132+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:61bfa8966694346a32d9492ea3d2ab22004a0ae1fbbbe28f50854d32bdce1916" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1397/tests/capture.py b/tasks/lite-xl__lite-xl-1397/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/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/lite-xl__lite-xl-1397/tests/instruction.md b/tasks/lite-xl__lite-xl-1397/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8ac469aefc085f2a3ccf51bf94ce42fa1f25908e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Fix os.getenv() not supporting UTF-8 output + +## Description + +Mostly likely will fix #1359. + +EDIT: +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2035886fcd8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1397/tests/oracle.patch b/tasks/lite-xl__lite-xl-1397/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8f5a8ab7e0e319add3c15c95c4706264dcccbd69 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/tests/oracle.patch @@ -0,0 +1,124 @@ +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +index 7785b8ea..31fec364 100644 +--- a/resources/windows/001-lua-unicode.diff ++++ b/resources/windows/001-lua-unicode.diff +@@ -1,6 +1,6 @@ +-diff -ruN lua-5.4.4/meson.build lua-5.4.4-mod/meson.build +---- lua-5.4.4/meson.build 2022-11-16 10:33:38.424383300 +0800 +-+++ lua-5.4.4-mod/meson.build 2022-11-16 09:40:57.697918000 +0800 ++diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build ++--- lua-5.4.4\meson.build Wed Feb 22 18:16:56 2023 +++++ lua-5.4.4-patched\meson.build Wed Feb 22 04:10:01 2023 + @@ -85,6 +85,7 @@ + 'src/lutf8lib.c', + 'src/lvm.c', +@@ -9,9 +9,9 @@ diff -ruN lua-5.4.4/meson.build lua-5.4.4-mod/meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-mod/src/luaconf.h +---- lua-5.4.4/src/luaconf.h 2022-01-13 19:24:43.000000000 +0800 +-+++ lua-5.4.4-mod/src/luaconf.h 2022-11-16 09:40:57.703926000 +0800 ++diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h ++--- lua-5.4.4\src\luaconf.h Thu Jan 13 19:24:43 2022 +++++ lua-5.4.4-patched\src\luaconf.h Wed Feb 22 04:10:02 2023 + @@ -782,5 +782,15 @@ + + +@@ -28,9 +28,9 @@ diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-mod/src/luaconf.h + + + #endif + +-diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-mod/src/Makefile +---- lua-5.4.4/src/Makefile 2021-07-15 22:01:52.000000000 +0800 +-+++ lua-5.4.4-mod/src/Makefile 2022-11-16 09:40:57.708921800 +0800 ++diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile ++--- lua-5.4.4\src\Makefile Thu Jul 15 22:01:52 2021 +++++ lua-5.4.4-patched\src\Makefile Wed Feb 22 04:10:02 2023 + @@ -33,7 +33,7 @@ + PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris + +@@ -40,10 +40,10 @@ diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-mod/src/Makefile + LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o + BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) + +-diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c +---- lua-5.4.4/src/utf8_wrappers.c 1970-01-01 07:30:00.000000000 +0730 +-+++ lua-5.4.4-mod/src/utf8_wrappers.c 2022-11-16 10:09:04.583866600 +0800 +-@@ -0,0 +1,101 @@ ++diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c ++--- lua-5.4.4\src\utf8_wrappers.c Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched\src\utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++@@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. + + * +@@ -58,12 +58,17 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c + +#include + +#include + + +++// A environment variable has the maximum length of 32767 characters +++// including the terminator. +++#define MAX_ENV_SIZE 32767 + +// Set a high limit in case long paths are enabled. + +#define MAX_PATH_SIZE 4096 + +#define MAX_MODE_SIZE 128 + +// cmd.exe argument length is reportedly limited to 8192. + +#define MAX_CMD_SIZE 8192 + + +++static char env_value[MAX_ENV_SIZE]; +++ + +FILE *fopen_utf8(const char *pathname, const char *mode) { + + wchar_t pathname_w[MAX_PATH_SIZE]; + + wchar_t mode_w[MAX_MODE_SIZE]; +@@ -144,11 +149,34 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-mod/src/utf8_wrappers.c + + } + + return LoadLibraryExW(pathname_w, hFile, dwFlags); + +} +++ +++char* getenv_utf8(const char *varname) { +++ /** This implementation is not thread safe. +++ * The string is only valid until the next call to getenv. +++ * This behavior is allowed per POSIX.1-2017 where it was said that: +++ * > The returned string pointer might be invalidated or the string content might be overwritten by a subsequent call to getenv(), setenv(), unsetenv(), or (if supported) putenv() but they shall not be affected by a call to any other function in this volume of POSIX.1-2017. +++ * > The returned string pointer might also be invalidated if the calling thread is terminated. +++ * > The getenv() function need not be thread-safe. +++ */ +++ wchar_t *value_w; +++ wchar_t varname_w[MAX_ENV_SIZE]; +++ +++ if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, varname, -1, varname_w, MAX_ENV_SIZE)) +++ return NULL; +++ value_w = _wgetenv((const wchar_t *) varname_w); +++ if (!value_w) +++ return NULL; +++ +++ if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value_w, -1, env_value, MAX_ENV_SIZE, NULL, NULL)) +++ return NULL; +++ +++ return env_value; +++} + +#endif +-diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-mod/src/utf8_wrappers.h +---- lua-5.4.4/src/utf8_wrappers.h 1970-01-01 07:30:00.000000000 +0730 +-+++ lua-5.4.4-mod/src/utf8_wrappers.h 2022-11-16 10:29:46.044102000 +0800 +-@@ -0,0 +1,44 @@ ++diff -ruN lua-5.4.4\src\utf8_wrappers.h lua-5.4.4-patched\src\utf8_wrappers.h ++--- lua-5.4.4\src\utf8_wrappers.h Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched\src\utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++@@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. + + * +@@ -180,9 +208,11 @@ diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-mod/src/utf8_wrappers.h + +int remove_utf8(const char *pathname); + +int rename_utf8(const char *oldpath, const char *newpath); + +int system_utf8(const char *command); +++char *getenv_utf8(const char *varname); + +#define remove remove_utf8 + +#define rename rename_utf8 + +#define system system_utf8 +++#define getenv getenv_utf8 + +#endif + + + +#ifdef loadlib_c diff --git a/tasks/lite-xl__lite-xl-1397/tests/test.sh b/tasks/lite-xl__lite-xl-1397/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e77caa502c3fd45683fa75b2847f180af151a27a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/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 2035886fcd8c5a1a6406f9adfb84d1a4d78abdc9 > "$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/lite-xl__lite-xl-1397/tests/verifier.py b/tasks/lite-xl__lite-xl-1397/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1397/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/lite-xl__lite-xl-1405/environment/Dockerfile b/tasks/lite-xl__lite-xl-1405/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f0938a7ce0ff6f091b8f3d3c65df8c53eb55667b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1ec3d28ff6aebb8a4702ff423377d0a79857035c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1ec3d28ff6aebb8a4702ff423377d0a79857035c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1ec3d28ff6aebb8a4702ff423377d0a79857035c \ + && 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/lite-xl__lite-xl-1405/instruction.md b/tasks/lite-xl__lite-xl-1405/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12b394b97c18fa76953cc073d6a6d073b21990b4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Add manifest on Windows + +## Description + +This manifest targets ComCtrl 6.0, which provides better looking MessageBox. + +Before: +![image](https://user-images.githubusercontent.com/20792268/222725195-5f10a2e3-1a5a-4547-8fce-03a91d7dfb54.png) + +After: +![image](https://user-images.githubusercontent.com/20792268/222725028-d7790167-8295-4c10-a2e9-6ff794afdc4d.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ec3d28ff6ae`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1405/solution/patch.diff b/tasks/lite-xl__lite-xl-1405/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1ac8ccd65f8e8ac54096df89490d110a3643f73f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/solution/patch.diff @@ -0,0 +1,102 @@ +diff --git a/.gitignore b/.gitignore +index b1d18a64..9b248455 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -21,3 +21,4 @@ lite-xl* + LiteXL* + + !resources/windows/*.diff ++!resources/windows/*.exe.manifest.in +diff --git a/meson.build b/meson.build +index 7bbecc68..cfef8ec8 100644 +--- a/meson.build ++++ b/meson.build +@@ -36,6 +36,7 @@ conf_data = configuration_data() + conf_data.set('PROJECT_BUILD_DIR', meson.current_build_dir()) + conf_data.set('PROJECT_SOURCE_DIR', meson.current_source_dir()) + conf_data.set('PROJECT_VERSION', version) ++conf_data.set('PROJECT_ASSEMBLY_VERSION', meson.project_version() + '.0') + + #=============================================================================== + # Compiler Settings +@@ -165,6 +166,11 @@ if get_option('portable') or host_machine.system() == 'windows' + lite_bindir = '/' + lite_docdir = '/doc' + lite_datadir = '/data' ++ configure_file( ++ input: 'resources/windows/lite-xl.exe.manifest.in', ++ output: 'lite-xl.exe.manifest', ++ configuration: conf_data ++ ) + elif get_option('bundle') and host_machine.system() == 'darwin' + lite_cargs += '-DMACOS_USE_BUNDLE' + lite_bindir = 'Contents/MacOS' +diff --git a/resources/windows/lite-xl.exe.manifest.in b/resources/windows/lite-xl.exe.manifest.in +new file mode 100644 +index 00000000..9e787587 +--- /dev/null ++++ b/resources/windows/lite-xl.exe.manifest.in +@@ -0,0 +1,41 @@ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/resources/windows/manifest.rc b/resources/windows/manifest.rc +new file mode 100644 +index 00000000..95b17e2d +--- /dev/null ++++ b/resources/windows/manifest.rc +@@ -0,0 +1,4 @@ ++#define IDR_RT_MANIFEST1 1 ++#define RT_MANIFEST 24 ++ ++IDR_RT_MANIFEST1 RT_MANIFEST "lite-xl.exe.manifest" +diff --git a/src/meson.build b/src/meson.build +index fee36d1d..a156ae3f 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -50,6 +50,7 @@ lite_rc = [] + if host_machine.system() == 'windows' + windows = import('windows') + lite_rc += windows.compile_resources('../resources/icons/icon.rc') ++ lite_rc += windows.compile_resources('../resources/windows/manifest.rc') + elif host_machine.system() == 'darwin' + lite_sources += 'bundle_open.m' + endif diff --git a/tasks/lite-xl__lite-xl-1405/solution/solve.sh b/tasks/lite-xl__lite-xl-1405/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/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/lite-xl__lite-xl-1405/task.toml b/tasks/lite-xl__lite-xl-1405/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49556cbf34ce6f567cc4c7c69ff3b66cbccc3736 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1405" +description = "Add manifest on Windows" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "1ec3d28ff6aebb8a4702ff423377d0a79857035c" +reference = "https://github.com/lite-xl/lite-xl/pull/1405" +source_access = "auto" +built_at = "2026-11-16T16:09:56.250253+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:95b5b821115d1dbc8dbddd33969d24ef70e34df87c967442125c47cff79ebc41" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-03-03T14:07:45Z" +diff_format = "unified" +context_files = [ + ".gitignore", + "meson.build", + "resources/windows/lite-xl.exe.manifest.in", + "resources/windows/manifest.rc", + "src/meson.build", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 53 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.281572+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6e371b0d19d815581640a79675a5f3d4d970a1585a8b19517c0cf7b416b3188c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1405/tests/capture.py b/tasks/lite-xl__lite-xl-1405/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/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/lite-xl__lite-xl-1405/tests/instruction.md b/tasks/lite-xl__lite-xl-1405/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12b394b97c18fa76953cc073d6a6d073b21990b4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Add manifest on Windows + +## Description + +This manifest targets ComCtrl 6.0, which provides better looking MessageBox. + +Before: +![image](https://user-images.githubusercontent.com/20792268/222725195-5f10a2e3-1a5a-4547-8fce-03a91d7dfb54.png) + +After: +![image](https://user-images.githubusercontent.com/20792268/222725028-d7790167-8295-4c10-a2e9-6ff794afdc4d.png) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ec3d28ff6ae`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1405/tests/oracle.patch b/tasks/lite-xl__lite-xl-1405/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1ac8ccd65f8e8ac54096df89490d110a3643f73f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/tests/oracle.patch @@ -0,0 +1,102 @@ +diff --git a/.gitignore b/.gitignore +index b1d18a64..9b248455 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -21,3 +21,4 @@ lite-xl* + LiteXL* + + !resources/windows/*.diff ++!resources/windows/*.exe.manifest.in +diff --git a/meson.build b/meson.build +index 7bbecc68..cfef8ec8 100644 +--- a/meson.build ++++ b/meson.build +@@ -36,6 +36,7 @@ conf_data = configuration_data() + conf_data.set('PROJECT_BUILD_DIR', meson.current_build_dir()) + conf_data.set('PROJECT_SOURCE_DIR', meson.current_source_dir()) + conf_data.set('PROJECT_VERSION', version) ++conf_data.set('PROJECT_ASSEMBLY_VERSION', meson.project_version() + '.0') + + #=============================================================================== + # Compiler Settings +@@ -165,6 +166,11 @@ if get_option('portable') or host_machine.system() == 'windows' + lite_bindir = '/' + lite_docdir = '/doc' + lite_datadir = '/data' ++ configure_file( ++ input: 'resources/windows/lite-xl.exe.manifest.in', ++ output: 'lite-xl.exe.manifest', ++ configuration: conf_data ++ ) + elif get_option('bundle') and host_machine.system() == 'darwin' + lite_cargs += '-DMACOS_USE_BUNDLE' + lite_bindir = 'Contents/MacOS' +diff --git a/resources/windows/lite-xl.exe.manifest.in b/resources/windows/lite-xl.exe.manifest.in +new file mode 100644 +index 00000000..9e787587 +--- /dev/null ++++ b/resources/windows/lite-xl.exe.manifest.in +@@ -0,0 +1,41 @@ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/resources/windows/manifest.rc b/resources/windows/manifest.rc +new file mode 100644 +index 00000000..95b17e2d +--- /dev/null ++++ b/resources/windows/manifest.rc +@@ -0,0 +1,4 @@ ++#define IDR_RT_MANIFEST1 1 ++#define RT_MANIFEST 24 ++ ++IDR_RT_MANIFEST1 RT_MANIFEST "lite-xl.exe.manifest" +diff --git a/src/meson.build b/src/meson.build +index fee36d1d..a156ae3f 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -50,6 +50,7 @@ lite_rc = [] + if host_machine.system() == 'windows' + windows = import('windows') + lite_rc += windows.compile_resources('../resources/icons/icon.rc') ++ lite_rc += windows.compile_resources('../resources/windows/manifest.rc') + elif host_machine.system() == 'darwin' + lite_sources += 'bundle_open.m' + endif diff --git a/tasks/lite-xl__lite-xl-1405/tests/test.sh b/tasks/lite-xl__lite-xl-1405/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a578fd868314e3827050cbbf92cd2b23974084ea --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/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 1ec3d28ff6aebb8a4702ff423377d0a79857035c > "$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/lite-xl__lite-xl-1405/tests/verifier.py b/tasks/lite-xl__lite-xl-1405/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1405/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/lite-xl__lite-xl-1412/environment/Dockerfile b/tasks/lite-xl__lite-xl-1412/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a5f45850a58f6943627188310341592e4a007672 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 73f3cd4fcdcf377cd42207cae1cbfce20997326f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 73f3cd4fcdcf377cd42207cae1cbfce20997326f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 73f3cd4fcdcf377cd42207cae1cbfce20997326f \ + && 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/lite-xl__lite-xl-1412/instruction.md b/tasks/lite-xl__lite-xl-1412/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1dc689ff2042d638e54906a95d14830d0aa60118 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Asynchronous process reaping + +## Description + +This PR allows process handles to be reaped asynchronously. +Previously, process reaping on `__gc` will stall the GC due to waiting for process to actually exit. +Now, this PR will allow the GC to run continuously while the process is sent to a background thread where it is terminated. + +This also fixes an issue on Windows where console applications are improperly kept open, holding lite-xl in the background. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73f3cd4fcdcf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1412/solution/patch.diff b/tasks/lite-xl__lite-xl-1412/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..be1218d7702c7d7235a14a423daaaa29af52a4c5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/solution/patch.diff @@ -0,0 +1,473 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 081e6ab6..2b0a5008 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -5,12 +5,13 @@ + #include + #include + #include ++#include + #include + + #if _WIN32 + // https://stackoverflow.com/questions/60645/overlapped-i-o-on-anonymous-pipe + // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output +- #include ++ #include + #else + #include + #include +@@ -21,11 +22,15 @@ + #endif + + #define READ_BUF_SIZE 2048 ++#define PROCESS_TERM_TRIES 3 ++#define PROCESS_TERM_DELAY 50 + + #if _WIN32 ++typedef HANDLE process_stream_handle; + typedef HANDLE process_handle; + #else +-typedef int process_handle; ++typedef int process_stream_handle; ++typedef pid_t process_handle; + #endif + + typedef struct { +@@ -38,9 +43,24 @@ typedef struct { + bool reading[2]; + char buffer[2][READ_BUF_SIZE]; + #endif +- process_handle child_pipes[3][2]; ++ process_stream_handle child_pipes[3][2]; + } process_t; + ++typedef struct process_kill_s { ++ int tries; ++ uint32_t start_time; ++ process_handle handle; ++ struct process_kill_s *next; ++} process_kill_t; ++ ++typedef struct { ++ bool stop; ++ SDL_mutex *mutex; ++ SDL_cond *has_work, *work_done; ++ process_kill_t *head; ++ process_kill_t *tail; ++} process_kill_list_t; ++ + typedef enum { + SIGNAL_KILL, + SIGNAL_TERM, +@@ -63,60 +83,201 @@ typedef enum { + REDIRECT_PARENT = -3, + } filed_e; + ++static process_kill_list_t kill_list = { 0 }; ++static SDL_Thread *kill_list_thread = NULL; ++ + #ifdef _WIN32 + static volatile long PipeSerialNumber; + static void close_fd(HANDLE* handle) { if (*handle) CloseHandle(*handle); *handle = INVALID_HANDLE_VALUE; } ++ #define PROCESS_GET_HANDLE(P) ((P)->process_information.hProcess) + #else + static void close_fd(int* fd) { if (*fd) close(*fd); *fd = 0; } ++ #define PROCESS_GET_HANDLE(P) ((P)->pid) + #endif + ++ ++static void kill_list_free(process_kill_list_t *list) { ++ process_kill_t *node, *temp; ++ SDL_DestroyMutex(list->mutex); ++ SDL_DestroyCond(list->has_work); ++ SDL_DestroyCond(list->work_done); ++ node = list->head; ++ while (node) { ++ temp = node; ++ node = node->next; ++ free(temp); ++ } ++} ++ ++ ++static bool kill_list_init(process_kill_list_t *list) { ++ list->mutex = SDL_CreateMutex(); ++ list->has_work = SDL_CreateCond(); ++ list->work_done = SDL_CreateCond(); ++ list->head = list->tail = NULL; ++ list->stop = false; ++ if (!list->mutex || !list->has_work || !list->work_done) { ++ kill_list_free(list); ++ return false; ++ } ++ return true; ++} ++ ++ ++static void kill_list_push(process_kill_list_t *list, process_kill_t *task) { ++ if (!list) return; ++ task->next = NULL; ++ if (list->tail) { ++ list->tail->next = task; ++ list->tail = task; ++ } else { ++ list->head = list->tail = task; ++ } ++} ++ ++ ++static void kill_list_pop(process_kill_list_t *list) { ++ if (!list || !list->head) return; ++ process_kill_t *head = list->head; ++ list->head = list->head->next; ++ if (!list->head) list->tail = NULL; ++ head->next = NULL; ++} ++ ++ ++static void kill_list_wait_all(process_kill_list_t *list) { ++ SDL_LockMutex(list->mutex); ++ // wait until list is empty ++ while (list->head) ++ SDL_CondWait(list->work_done, list->mutex); ++ // tell the worker to stop ++ list->stop = true; ++ SDL_CondSignal(list->has_work); ++ SDL_UnlockMutex(list->mutex); ++} ++ ++ ++static void process_handle_close(process_handle *handle) { ++#ifdef _WIN32 ++ if (*handle) { ++ CloseHandle(*handle); ++ *handle = NULL; ++ } ++#endif ++ (void) 0; ++} ++ ++ ++static bool process_handle_is_running(process_handle handle, int *status) { ++#ifdef _WIN32 ++ DWORD s; ++ if (GetExitCodeProcess(handle, &s) && s != STILL_ACTIVE) { ++ if (status != NULL) ++ *status = s; ++ return false; ++ } ++#else ++ int s; ++ if (waitpid(handle, &s, WNOHANG) != 0) { ++ if (status != NULL) ++ *status = WEXITSTATUS(s); ++ return false; ++ } ++#endif ++ return true; ++} ++ ++ ++static bool process_handle_signal(process_handle handle, signal_e sig) { ++#if _WIN32 ++ switch(sig) { ++ case SIGNAL_TERM: return GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId(handle)); ++ case SIGNAL_KILL: return TerminateProcess(handle, -1); ++ case SIGNAL_INTERRUPT: return DebugBreakProcess(handle); ++ } ++#else ++ switch (sig) { ++ case SIGNAL_TERM: return kill(-handle, SIGTERM) == 0; break; ++ case SIGNAL_KILL: return kill(-handle, SIGKILL) == 0; break; ++ case SIGNAL_INTERRUPT: return kill(-handle, SIGINT) == 0; break; ++ } ++#endif ++ return false; ++} ++ ++ ++static int kill_list_worker(void *ud) { ++ process_kill_list_t *list = (process_kill_list_t *) ud; ++ process_kill_t *current_task; ++ uint32_t delay; ++ ++ while (true) { ++ SDL_LockMutex(list->mutex); ++ ++ // wait until we have work to do ++ while (!list->head && !list->stop) ++ SDL_CondWait(list->has_work, list->mutex); // LOCK MUTEX ++ ++ if (list->stop) break; ++ ++ while ((current_task = list->head)) { ++ if ((SDL_GetTicks() - current_task->start_time) < PROCESS_TERM_DELAY) ++ break; ++ kill_list_pop(list); ++ if (process_handle_is_running(current_task->handle, NULL)) { ++ if (current_task->tries < PROCESS_TERM_TRIES) ++ process_handle_signal(current_task->handle, SIGNAL_TERM); ++ else if (current_task->tries == PROCESS_TERM_TRIES) ++ process_handle_signal(current_task->handle, SIGNAL_KILL); ++ else ++ goto free_task; ++ ++ // add the task back into the queue ++ current_task->tries++; ++ current_task->start_time = SDL_GetTicks(); ++ kill_list_push(list, current_task); ++ } else { ++ free_task: ++ SDL_CondSignal(list->work_done); ++ process_handle_close(¤t_task->handle); ++ free(current_task); ++ } ++ } ++ delay = list->head ? (list->head->start_time + PROCESS_TERM_DELAY) - SDL_GetTicks() : 0; ++ SDL_UnlockMutex(list->mutex); ++ SDL_Delay(delay); ++ } ++ SDL_UnlockMutex(list->mutex); ++ return 0; ++} ++ ++ + static bool poll_process(process_t* proc, int timeout) { ++ uint32_t ticks; ++ + if (!proc->running) + return false; +- uint32_t ticks = SDL_GetTicks(); ++ + if (timeout == WAIT_DEADLINE) + timeout = proc->deadline; + ++ ticks = SDL_GetTicks(); + do { +- #ifdef _WIN32 +- DWORD exit_code = -1; +- if (!GetExitCodeProcess( proc->process_information.hProcess, &exit_code ) || exit_code != STILL_ACTIVE) { +- proc->returncode = exit_code; +- proc->running = false; +- break; +- } +- #else +- int status; +- pid_t wait_response = waitpid(proc->pid, &status, WNOHANG); +- if (wait_response != 0) { +- proc->running = false; +- proc->returncode = WEXITSTATUS(status); +- break; +- } +- #endif ++ int status; ++ if (!process_handle_is_running(PROCESS_GET_HANDLE(proc), &status)) { ++ proc->running = false; ++ proc->returncode = status; ++ break; ++ } + if (timeout) +- SDL_Delay(5); ++ SDL_Delay(timeout >= 5 ? 5 : 0); + } while (timeout == WAIT_INFINITE || (int)SDL_GetTicks() - ticks < timeout); + + return proc->running; + } + + static bool signal_process(process_t* proc, signal_e sig) { +- bool terminate = false; +- #if _WIN32 +- switch(sig) { +- case SIGNAL_TERM: terminate = GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId(proc->process_information.hProcess)); break; +- case SIGNAL_KILL: terminate = TerminateProcess(proc->process_information.hProcess, -1); break; +- case SIGNAL_INTERRUPT: DebugBreakProcess(proc->process_information.hProcess); break; +- } +- #else +- switch (sig) { +- case SIGNAL_TERM: terminate = kill(-proc->pid, SIGTERM) == 1; break; +- case SIGNAL_KILL: terminate = kill(-proc->pid, SIGKILL) == 1; break; +- case SIGNAL_INTERRUPT: kill(-proc->pid, SIGINT); break; +- } +- #endif +- if (terminate) ++ if (process_handle_signal(PROCESS_GET_HANDLE(proc), sig)) + poll_process(proc, WAIT_NONE); + return true; + } +@@ -152,7 +313,7 @@ static int process_start(lua_State* L) { + if (arg_len > 1) { + lua_getfield(L, 2, "env"); + if (!lua_isnil(L, -1)) { +- lua_pushnil(L); ++ lua_pushnil(L); + while (lua_next(L, -2) != 0) { + const char* key = luaL_checklstring(L, -2, &key_len); + const char* val = luaL_checklstring(L, -1, &val_len); +@@ -179,7 +340,7 @@ static int process_start(lua_State* L) { + } + } + } +- ++ + process_t* self = lua_newuserdata(L, sizeof(process_t)); + memset(self, 0, sizeof(process_t)); + luaL_setmetatable(L, API_TYPE_PROCESS); +@@ -196,9 +357,9 @@ static int process_start(lua_State* L) { + } + self->child_pipes[i][i == STDIN_FD ? 1 : 0] = INVALID_HANDLE_VALUE; + break; +- case REDIRECT_DISCARD: +- self->child_pipes[i][0] = INVALID_HANDLE_VALUE; +- self->child_pipes[i][1] = INVALID_HANDLE_VALUE; ++ case REDIRECT_DISCARD: ++ self->child_pipes[i][0] = INVALID_HANDLE_VALUE; ++ self->child_pipes[i][1] = INVALID_HANDLE_VALUE; + break; + default: { + if (new_fds[i] == i) { +@@ -289,7 +450,7 @@ static int process_start(lua_State* L) { + goto cleanup; + } + self->pid = (long)self->process_information.dwProcessId; +- if (detach) ++ if (detach) + CloseHandle(self->process_information.hProcess); + CloseHandle(self->process_information.hThread); + #else +@@ -372,7 +533,7 @@ static int process_start(lua_State* L) { + free((char*)env_values[i]); + } + for (int stream = 0; stream < 3; ++stream) { +- process_handle* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; ++ process_stream_handle* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; + if (*pipe) { + close_fd(pipe); + } +@@ -467,7 +628,7 @@ static int f_close_stream(lua_State* L) { + static int process_strerror(lua_State* L) { + #if _WIN32 + return 1; +- #endif ++ #endif + int error_code = luaL_checknumber(L, 1); + if (error_code < 0) + lua_pushstring(L, strerror(error_code)); +@@ -525,14 +686,37 @@ static int self_signal(lua_State* L, signal_e sig) { + static int f_terminate(lua_State* L) { return self_signal(L, SIGNAL_TERM); } + static int f_kill(lua_State* L) { return self_signal(L, SIGNAL_KILL); } + static int f_interrupt(lua_State* L) { return self_signal(L, SIGNAL_INTERRUPT); } +-static int f_gc(lua_State* L) { ++ ++static int f_gc(lua_State* L) { + process_t* self = (process_t*) luaL_checkudata(L, 1, API_TYPE_PROCESS); +- if (!self->detached) ++ ++ if (poll_process(self, 0) && !self->detached) { ++ // attempt to kill the process if not detached ++ process_kill_t *p; ++ + signal_process(self, SIGNAL_TERM); ++ p = malloc(sizeof(process_kill_t)); ++ if (!p || !kill_list_thread) { ++ // if we can't allocate, we'll use the old method ++ poll_process(self, PROCESS_TERM_DELAY); ++ if (self->running) { ++ signal_process(self, SIGNAL_KILL); ++ poll_process(self, PROCESS_TERM_DELAY); ++ } ++ } else { ++ // send the handle to a queue for asynchronous waiting ++ p->handle = PROCESS_GET_HANDLE(self); ++ p->start_time = SDL_GetTicks(); ++ p->tries = 1; ++ SDL_LockMutex(kill_list.mutex); ++ kill_list_push(&kill_list, p); ++ SDL_CondSignal(kill_list.has_work); ++ SDL_UnlockMutex(kill_list.mutex); ++ } ++ } + close_fd(&self->child_pipes[STDIN_FD ][1]); + close_fd(&self->child_pipes[STDOUT_FD][0]); +- close_fd(&self->child_pipes[STDERR_FD][0]); +- poll_process(self, 10); ++ close_fd(&self->child_pipes[STDERR_FD][0]); + return 0; + } + +@@ -542,11 +726,16 @@ static int f_running(lua_State* L) { + return 1; + } + +-static const struct luaL_Reg lib[] = { ++static int process_gc(lua_State *L) { ++ kill_list_wait_all(&kill_list); ++ SDL_WaitThread(kill_list_thread, NULL); ++ kill_list_free(&kill_list); ++ return 0; ++} ++ ++static const struct luaL_Reg process_metatable[] = { + {"__gc", f_gc}, + {"__tostring", f_tostring}, +- {"start", process_start}, +- {"strerror", process_strerror}, + {"pid", f_pid}, + {"returncode", f_returncode}, + {"read", f_read}, +@@ -562,12 +751,29 @@ static const struct luaL_Reg lib[] = { + {NULL, NULL} + }; + ++static const struct luaL_Reg lib[] = { ++ { "start", process_start }, ++ { "strerror", process_strerror }, ++ { NULL, NULL } ++}; ++ + int luaopen_process(lua_State *L) { ++ if (kill_list_init(&kill_list)) ++ kill_list_thread = SDL_CreateThread(kill_list_worker, "process_kill", &kill_list); ++ ++ // create the process metatable + luaL_newmetatable(L, API_TYPE_PROCESS); +- luaL_setfuncs(L, lib, 0); ++ luaL_setfuncs(L, process_metatable, 0); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + ++ // create the process library ++ luaL_newlib(L, lib); ++ lua_newtable(L); ++ lua_pushcfunction(L, process_gc); ++ lua_setfield(L, -2, "__gc"); ++ lua_setmetatable(L, -2); ++ + API_CONSTANT_DEFINE(L, -1, "WAIT_INFINITE", WAIT_INFINITE); + API_CONSTANT_DEFINE(L, -1, "WAIT_DEADLINE", WAIT_DEADLINE); + +@@ -576,7 +782,7 @@ int luaopen_process(lua_State *L) { + API_CONSTANT_DEFINE(L, -1, "STREAM_STDERR", STDERR_FD); + + API_CONSTANT_DEFINE(L, -1, "REDIRECT_DEFAULT", REDIRECT_DEFAULT); +- API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDOUT", STDOUT_FD); ++ API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDOUT", STDOUT_FD); + API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDERR", STDERR_FD); + API_CONSTANT_DEFINE(L, -1, "REDIRECT_PARENT", REDIRECT_PARENT); // Redirects to parent's STDOUT/STDERR + API_CONSTANT_DEFINE(L, -1, "REDIRECT_DISCARD", REDIRECT_DISCARD); // Closes the filehandle, discarding it. +diff --git a/src/main.c b/src/main.c +index c5e15707..784fd181 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -259,8 +259,10 @@ init_lua: + goto init_lua; + } + +- lua_close(L); ++ // This allows the window to be destroyed before lite-xl is done with ++ // reaping child processes + ren_free_window_resources(&window_renderer); ++ lua_close(L); + + return EXIT_SUCCESS; + } diff --git a/tasks/lite-xl__lite-xl-1412/solution/solve.sh b/tasks/lite-xl__lite-xl-1412/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/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/lite-xl__lite-xl-1412/task.toml b/tasks/lite-xl__lite-xl-1412/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e995b505ae11b1da4c13716a0a3924ddefea3b1b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1412" +description = "Asynchronous process reaping" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "73f3cd4fcdcf377cd42207cae1cbfce20997326f" +reference = "https://github.com/lite-xl/lite-xl/pull/1412" +source_access = "auto" +built_at = "2026-11-16T16:09:56.257662+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1e98e4682e02e08aa4bb9af08764ee95d7cc62327eba8b0b854a14fa82ae565f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-03-22T12:36:05Z" +diff_format = "unified" +context_files = [ + "src/api/process.c", + "src/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 316 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.282029+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:53a7e3829477fa8d1129554f13b05db7b44d28b62c4c50750a988acea9c04bf3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1412/tests/capture.py b/tasks/lite-xl__lite-xl-1412/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/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/lite-xl__lite-xl-1412/tests/instruction.md b/tasks/lite-xl__lite-xl-1412/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1dc689ff2042d638e54906a95d14830d0aa60118 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Asynchronous process reaping + +## Description + +This PR allows process handles to be reaped asynchronously. +Previously, process reaping on `__gc` will stall the GC due to waiting for process to actually exit. +Now, this PR will allow the GC to run continuously while the process is sent to a background thread where it is terminated. + +This also fixes an issue on Windows where console applications are improperly kept open, holding lite-xl in the background. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73f3cd4fcdcf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1412/tests/oracle.patch b/tasks/lite-xl__lite-xl-1412/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..be1218d7702c7d7235a14a423daaaa29af52a4c5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/tests/oracle.patch @@ -0,0 +1,473 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 081e6ab6..2b0a5008 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -5,12 +5,13 @@ + #include + #include + #include ++#include + #include + + #if _WIN32 + // https://stackoverflow.com/questions/60645/overlapped-i-o-on-anonymous-pipe + // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output +- #include ++ #include + #else + #include + #include +@@ -21,11 +22,15 @@ + #endif + + #define READ_BUF_SIZE 2048 ++#define PROCESS_TERM_TRIES 3 ++#define PROCESS_TERM_DELAY 50 + + #if _WIN32 ++typedef HANDLE process_stream_handle; + typedef HANDLE process_handle; + #else +-typedef int process_handle; ++typedef int process_stream_handle; ++typedef pid_t process_handle; + #endif + + typedef struct { +@@ -38,9 +43,24 @@ typedef struct { + bool reading[2]; + char buffer[2][READ_BUF_SIZE]; + #endif +- process_handle child_pipes[3][2]; ++ process_stream_handle child_pipes[3][2]; + } process_t; + ++typedef struct process_kill_s { ++ int tries; ++ uint32_t start_time; ++ process_handle handle; ++ struct process_kill_s *next; ++} process_kill_t; ++ ++typedef struct { ++ bool stop; ++ SDL_mutex *mutex; ++ SDL_cond *has_work, *work_done; ++ process_kill_t *head; ++ process_kill_t *tail; ++} process_kill_list_t; ++ + typedef enum { + SIGNAL_KILL, + SIGNAL_TERM, +@@ -63,60 +83,201 @@ typedef enum { + REDIRECT_PARENT = -3, + } filed_e; + ++static process_kill_list_t kill_list = { 0 }; ++static SDL_Thread *kill_list_thread = NULL; ++ + #ifdef _WIN32 + static volatile long PipeSerialNumber; + static void close_fd(HANDLE* handle) { if (*handle) CloseHandle(*handle); *handle = INVALID_HANDLE_VALUE; } ++ #define PROCESS_GET_HANDLE(P) ((P)->process_information.hProcess) + #else + static void close_fd(int* fd) { if (*fd) close(*fd); *fd = 0; } ++ #define PROCESS_GET_HANDLE(P) ((P)->pid) + #endif + ++ ++static void kill_list_free(process_kill_list_t *list) { ++ process_kill_t *node, *temp; ++ SDL_DestroyMutex(list->mutex); ++ SDL_DestroyCond(list->has_work); ++ SDL_DestroyCond(list->work_done); ++ node = list->head; ++ while (node) { ++ temp = node; ++ node = node->next; ++ free(temp); ++ } ++} ++ ++ ++static bool kill_list_init(process_kill_list_t *list) { ++ list->mutex = SDL_CreateMutex(); ++ list->has_work = SDL_CreateCond(); ++ list->work_done = SDL_CreateCond(); ++ list->head = list->tail = NULL; ++ list->stop = false; ++ if (!list->mutex || !list->has_work || !list->work_done) { ++ kill_list_free(list); ++ return false; ++ } ++ return true; ++} ++ ++ ++static void kill_list_push(process_kill_list_t *list, process_kill_t *task) { ++ if (!list) return; ++ task->next = NULL; ++ if (list->tail) { ++ list->tail->next = task; ++ list->tail = task; ++ } else { ++ list->head = list->tail = task; ++ } ++} ++ ++ ++static void kill_list_pop(process_kill_list_t *list) { ++ if (!list || !list->head) return; ++ process_kill_t *head = list->head; ++ list->head = list->head->next; ++ if (!list->head) list->tail = NULL; ++ head->next = NULL; ++} ++ ++ ++static void kill_list_wait_all(process_kill_list_t *list) { ++ SDL_LockMutex(list->mutex); ++ // wait until list is empty ++ while (list->head) ++ SDL_CondWait(list->work_done, list->mutex); ++ // tell the worker to stop ++ list->stop = true; ++ SDL_CondSignal(list->has_work); ++ SDL_UnlockMutex(list->mutex); ++} ++ ++ ++static void process_handle_close(process_handle *handle) { ++#ifdef _WIN32 ++ if (*handle) { ++ CloseHandle(*handle); ++ *handle = NULL; ++ } ++#endif ++ (void) 0; ++} ++ ++ ++static bool process_handle_is_running(process_handle handle, int *status) { ++#ifdef _WIN32 ++ DWORD s; ++ if (GetExitCodeProcess(handle, &s) && s != STILL_ACTIVE) { ++ if (status != NULL) ++ *status = s; ++ return false; ++ } ++#else ++ int s; ++ if (waitpid(handle, &s, WNOHANG) != 0) { ++ if (status != NULL) ++ *status = WEXITSTATUS(s); ++ return false; ++ } ++#endif ++ return true; ++} ++ ++ ++static bool process_handle_signal(process_handle handle, signal_e sig) { ++#if _WIN32 ++ switch(sig) { ++ case SIGNAL_TERM: return GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId(handle)); ++ case SIGNAL_KILL: return TerminateProcess(handle, -1); ++ case SIGNAL_INTERRUPT: return DebugBreakProcess(handle); ++ } ++#else ++ switch (sig) { ++ case SIGNAL_TERM: return kill(-handle, SIGTERM) == 0; break; ++ case SIGNAL_KILL: return kill(-handle, SIGKILL) == 0; break; ++ case SIGNAL_INTERRUPT: return kill(-handle, SIGINT) == 0; break; ++ } ++#endif ++ return false; ++} ++ ++ ++static int kill_list_worker(void *ud) { ++ process_kill_list_t *list = (process_kill_list_t *) ud; ++ process_kill_t *current_task; ++ uint32_t delay; ++ ++ while (true) { ++ SDL_LockMutex(list->mutex); ++ ++ // wait until we have work to do ++ while (!list->head && !list->stop) ++ SDL_CondWait(list->has_work, list->mutex); // LOCK MUTEX ++ ++ if (list->stop) break; ++ ++ while ((current_task = list->head)) { ++ if ((SDL_GetTicks() - current_task->start_time) < PROCESS_TERM_DELAY) ++ break; ++ kill_list_pop(list); ++ if (process_handle_is_running(current_task->handle, NULL)) { ++ if (current_task->tries < PROCESS_TERM_TRIES) ++ process_handle_signal(current_task->handle, SIGNAL_TERM); ++ else if (current_task->tries == PROCESS_TERM_TRIES) ++ process_handle_signal(current_task->handle, SIGNAL_KILL); ++ else ++ goto free_task; ++ ++ // add the task back into the queue ++ current_task->tries++; ++ current_task->start_time = SDL_GetTicks(); ++ kill_list_push(list, current_task); ++ } else { ++ free_task: ++ SDL_CondSignal(list->work_done); ++ process_handle_close(¤t_task->handle); ++ free(current_task); ++ } ++ } ++ delay = list->head ? (list->head->start_time + PROCESS_TERM_DELAY) - SDL_GetTicks() : 0; ++ SDL_UnlockMutex(list->mutex); ++ SDL_Delay(delay); ++ } ++ SDL_UnlockMutex(list->mutex); ++ return 0; ++} ++ ++ + static bool poll_process(process_t* proc, int timeout) { ++ uint32_t ticks; ++ + if (!proc->running) + return false; +- uint32_t ticks = SDL_GetTicks(); ++ + if (timeout == WAIT_DEADLINE) + timeout = proc->deadline; + ++ ticks = SDL_GetTicks(); + do { +- #ifdef _WIN32 +- DWORD exit_code = -1; +- if (!GetExitCodeProcess( proc->process_information.hProcess, &exit_code ) || exit_code != STILL_ACTIVE) { +- proc->returncode = exit_code; +- proc->running = false; +- break; +- } +- #else +- int status; +- pid_t wait_response = waitpid(proc->pid, &status, WNOHANG); +- if (wait_response != 0) { +- proc->running = false; +- proc->returncode = WEXITSTATUS(status); +- break; +- } +- #endif ++ int status; ++ if (!process_handle_is_running(PROCESS_GET_HANDLE(proc), &status)) { ++ proc->running = false; ++ proc->returncode = status; ++ break; ++ } + if (timeout) +- SDL_Delay(5); ++ SDL_Delay(timeout >= 5 ? 5 : 0); + } while (timeout == WAIT_INFINITE || (int)SDL_GetTicks() - ticks < timeout); + + return proc->running; + } + + static bool signal_process(process_t* proc, signal_e sig) { +- bool terminate = false; +- #if _WIN32 +- switch(sig) { +- case SIGNAL_TERM: terminate = GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, GetProcessId(proc->process_information.hProcess)); break; +- case SIGNAL_KILL: terminate = TerminateProcess(proc->process_information.hProcess, -1); break; +- case SIGNAL_INTERRUPT: DebugBreakProcess(proc->process_information.hProcess); break; +- } +- #else +- switch (sig) { +- case SIGNAL_TERM: terminate = kill(-proc->pid, SIGTERM) == 1; break; +- case SIGNAL_KILL: terminate = kill(-proc->pid, SIGKILL) == 1; break; +- case SIGNAL_INTERRUPT: kill(-proc->pid, SIGINT); break; +- } +- #endif +- if (terminate) ++ if (process_handle_signal(PROCESS_GET_HANDLE(proc), sig)) + poll_process(proc, WAIT_NONE); + return true; + } +@@ -152,7 +313,7 @@ static int process_start(lua_State* L) { + if (arg_len > 1) { + lua_getfield(L, 2, "env"); + if (!lua_isnil(L, -1)) { +- lua_pushnil(L); ++ lua_pushnil(L); + while (lua_next(L, -2) != 0) { + const char* key = luaL_checklstring(L, -2, &key_len); + const char* val = luaL_checklstring(L, -1, &val_len); +@@ -179,7 +340,7 @@ static int process_start(lua_State* L) { + } + } + } +- ++ + process_t* self = lua_newuserdata(L, sizeof(process_t)); + memset(self, 0, sizeof(process_t)); + luaL_setmetatable(L, API_TYPE_PROCESS); +@@ -196,9 +357,9 @@ static int process_start(lua_State* L) { + } + self->child_pipes[i][i == STDIN_FD ? 1 : 0] = INVALID_HANDLE_VALUE; + break; +- case REDIRECT_DISCARD: +- self->child_pipes[i][0] = INVALID_HANDLE_VALUE; +- self->child_pipes[i][1] = INVALID_HANDLE_VALUE; ++ case REDIRECT_DISCARD: ++ self->child_pipes[i][0] = INVALID_HANDLE_VALUE; ++ self->child_pipes[i][1] = INVALID_HANDLE_VALUE; + break; + default: { + if (new_fds[i] == i) { +@@ -289,7 +450,7 @@ static int process_start(lua_State* L) { + goto cleanup; + } + self->pid = (long)self->process_information.dwProcessId; +- if (detach) ++ if (detach) + CloseHandle(self->process_information.hProcess); + CloseHandle(self->process_information.hThread); + #else +@@ -372,7 +533,7 @@ static int process_start(lua_State* L) { + free((char*)env_values[i]); + } + for (int stream = 0; stream < 3; ++stream) { +- process_handle* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; ++ process_stream_handle* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; + if (*pipe) { + close_fd(pipe); + } +@@ -467,7 +628,7 @@ static int f_close_stream(lua_State* L) { + static int process_strerror(lua_State* L) { + #if _WIN32 + return 1; +- #endif ++ #endif + int error_code = luaL_checknumber(L, 1); + if (error_code < 0) + lua_pushstring(L, strerror(error_code)); +@@ -525,14 +686,37 @@ static int self_signal(lua_State* L, signal_e sig) { + static int f_terminate(lua_State* L) { return self_signal(L, SIGNAL_TERM); } + static int f_kill(lua_State* L) { return self_signal(L, SIGNAL_KILL); } + static int f_interrupt(lua_State* L) { return self_signal(L, SIGNAL_INTERRUPT); } +-static int f_gc(lua_State* L) { ++ ++static int f_gc(lua_State* L) { + process_t* self = (process_t*) luaL_checkudata(L, 1, API_TYPE_PROCESS); +- if (!self->detached) ++ ++ if (poll_process(self, 0) && !self->detached) { ++ // attempt to kill the process if not detached ++ process_kill_t *p; ++ + signal_process(self, SIGNAL_TERM); ++ p = malloc(sizeof(process_kill_t)); ++ if (!p || !kill_list_thread) { ++ // if we can't allocate, we'll use the old method ++ poll_process(self, PROCESS_TERM_DELAY); ++ if (self->running) { ++ signal_process(self, SIGNAL_KILL); ++ poll_process(self, PROCESS_TERM_DELAY); ++ } ++ } else { ++ // send the handle to a queue for asynchronous waiting ++ p->handle = PROCESS_GET_HANDLE(self); ++ p->start_time = SDL_GetTicks(); ++ p->tries = 1; ++ SDL_LockMutex(kill_list.mutex); ++ kill_list_push(&kill_list, p); ++ SDL_CondSignal(kill_list.has_work); ++ SDL_UnlockMutex(kill_list.mutex); ++ } ++ } + close_fd(&self->child_pipes[STDIN_FD ][1]); + close_fd(&self->child_pipes[STDOUT_FD][0]); +- close_fd(&self->child_pipes[STDERR_FD][0]); +- poll_process(self, 10); ++ close_fd(&self->child_pipes[STDERR_FD][0]); + return 0; + } + +@@ -542,11 +726,16 @@ static int f_running(lua_State* L) { + return 1; + } + +-static const struct luaL_Reg lib[] = { ++static int process_gc(lua_State *L) { ++ kill_list_wait_all(&kill_list); ++ SDL_WaitThread(kill_list_thread, NULL); ++ kill_list_free(&kill_list); ++ return 0; ++} ++ ++static const struct luaL_Reg process_metatable[] = { + {"__gc", f_gc}, + {"__tostring", f_tostring}, +- {"start", process_start}, +- {"strerror", process_strerror}, + {"pid", f_pid}, + {"returncode", f_returncode}, + {"read", f_read}, +@@ -562,12 +751,29 @@ static const struct luaL_Reg lib[] = { + {NULL, NULL} + }; + ++static const struct luaL_Reg lib[] = { ++ { "start", process_start }, ++ { "strerror", process_strerror }, ++ { NULL, NULL } ++}; ++ + int luaopen_process(lua_State *L) { ++ if (kill_list_init(&kill_list)) ++ kill_list_thread = SDL_CreateThread(kill_list_worker, "process_kill", &kill_list); ++ ++ // create the process metatable + luaL_newmetatable(L, API_TYPE_PROCESS); +- luaL_setfuncs(L, lib, 0); ++ luaL_setfuncs(L, process_metatable, 0); + lua_pushvalue(L, -1); + lua_setfield(L, -2, "__index"); + ++ // create the process library ++ luaL_newlib(L, lib); ++ lua_newtable(L); ++ lua_pushcfunction(L, process_gc); ++ lua_setfield(L, -2, "__gc"); ++ lua_setmetatable(L, -2); ++ + API_CONSTANT_DEFINE(L, -1, "WAIT_INFINITE", WAIT_INFINITE); + API_CONSTANT_DEFINE(L, -1, "WAIT_DEADLINE", WAIT_DEADLINE); + +@@ -576,7 +782,7 @@ int luaopen_process(lua_State *L) { + API_CONSTANT_DEFINE(L, -1, "STREAM_STDERR", STDERR_FD); + + API_CONSTANT_DEFINE(L, -1, "REDIRECT_DEFAULT", REDIRECT_DEFAULT); +- API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDOUT", STDOUT_FD); ++ API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDOUT", STDOUT_FD); + API_CONSTANT_DEFINE(L, -1, "REDIRECT_STDERR", STDERR_FD); + API_CONSTANT_DEFINE(L, -1, "REDIRECT_PARENT", REDIRECT_PARENT); // Redirects to parent's STDOUT/STDERR + API_CONSTANT_DEFINE(L, -1, "REDIRECT_DISCARD", REDIRECT_DISCARD); // Closes the filehandle, discarding it. +diff --git a/src/main.c b/src/main.c +index c5e15707..784fd181 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -259,8 +259,10 @@ init_lua: + goto init_lua; + } + +- lua_close(L); ++ // This allows the window to be destroyed before lite-xl is done with ++ // reaping child processes + ren_free_window_resources(&window_renderer); ++ lua_close(L); + + return EXIT_SUCCESS; + } diff --git a/tasks/lite-xl__lite-xl-1412/tests/test.sh b/tasks/lite-xl__lite-xl-1412/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e2dcd159f7f435028fa718eae37b93bb87539ca --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/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 73f3cd4fcdcf377cd42207cae1cbfce20997326f > "$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/lite-xl__lite-xl-1412/tests/verifier.py b/tasks/lite-xl__lite-xl-1412/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1412/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/lite-xl__lite-xl-1413/environment/Dockerfile b/tasks/lite-xl__lite-xl-1413/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a5f45850a58f6943627188310341592e4a007672 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 73f3cd4fcdcf377cd42207cae1cbfce20997326f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 73f3cd4fcdcf377cd42207cae1cbfce20997326f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 73f3cd4fcdcf377cd42207cae1cbfce20997326f \ + && 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/lite-xl__lite-xl-1413/instruction.md b/tasks/lite-xl__lite-xl-1413/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49cc19475e8641cebbe70c238a1753a38dcb0487 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Move SetProcessDPIAware to manifests + +## Description + +This is the recommended way by MS. + +> Note It is recommended that you set the process-default DPI awareness via application manifest, not an API call. See [Setting the default DPI awareness for a process](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/mt846517(v=vs.85)) for more information. Setting the process-default DPI awareness via API call can lead to unexpected application behavior. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73f3cd4fcdcf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1413/solution/patch.diff b/tasks/lite-xl__lite-xl-1413/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..31d02f937e0363628459ecbe5a9fa569352ab4ee --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/solution/patch.diff @@ -0,0 +1,35 @@ +diff --git a/resources/windows/lite-xl.exe.manifest.in b/resources/windows/lite-xl.exe.manifest.in +index 9e787587..a01ac8d2 100644 +--- a/resources/windows/lite-xl.exe.manifest.in ++++ b/resources/windows/lite-xl.exe.manifest.in +@@ -24,6 +24,13 @@ + /> + + ++ ++ ++ ++ true ++ ++ ++ + + + +diff --git a/src/main.c b/src/main.c +index c5e15707..7bc57b6e 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -120,11 +120,7 @@ void set_macos_bundle_resources(lua_State *L); + #endif + + int main(int argc, char **argv) { +-#ifdef _WIN32 +- HINSTANCE lib = LoadLibrary("user32.dll"); +- int (*SetProcessDPIAware)() = (void*) GetProcAddress(lib, "SetProcessDPIAware"); +- SetProcessDPIAware(); +-#else ++#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); + #endif + diff --git a/tasks/lite-xl__lite-xl-1413/solution/solve.sh b/tasks/lite-xl__lite-xl-1413/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/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/lite-xl__lite-xl-1413/task.toml b/tasks/lite-xl__lite-xl-1413/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10bea4e517f306f8350fb519b36dd93c9a52d977 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1413" +description = "Move SetProcessDPIAware to manifests" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "73f3cd4fcdcf377cd42207cae1cbfce20997326f" +reference = "https://github.com/lite-xl/lite-xl/pull/1413" +source_access = "auto" +built_at = "2026-11-16T16:09:56.256253+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b7445ee175b9a8438054a827d615dad898cff490d20313e79afed7d5ac4f2eae" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-03-09T13:58:33Z" +diff_format = "unified" +context_files = [ + "resources/windows/lite-xl.exe.manifest.in", + "src/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.282468+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:53a7e3829477fa8d1129554f13b05db7b44d28b62c4c50750a988acea9c04bf3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1413/tests/capture.py b/tasks/lite-xl__lite-xl-1413/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/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/lite-xl__lite-xl-1413/tests/instruction.md b/tasks/lite-xl__lite-xl-1413/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49cc19475e8641cebbe70c238a1753a38dcb0487 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Move SetProcessDPIAware to manifests + +## Description + +This is the recommended way by MS. + +> Note It is recommended that you set the process-default DPI awareness via application manifest, not an API call. See [Setting the default DPI awareness for a process](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/mt846517(v=vs.85)) for more information. Setting the process-default DPI awareness via API call can lead to unexpected application behavior. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `73f3cd4fcdcf`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1413/tests/oracle.patch b/tasks/lite-xl__lite-xl-1413/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..31d02f937e0363628459ecbe5a9fa569352ab4ee --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/tests/oracle.patch @@ -0,0 +1,35 @@ +diff --git a/resources/windows/lite-xl.exe.manifest.in b/resources/windows/lite-xl.exe.manifest.in +index 9e787587..a01ac8d2 100644 +--- a/resources/windows/lite-xl.exe.manifest.in ++++ b/resources/windows/lite-xl.exe.manifest.in +@@ -24,6 +24,13 @@ + /> + + ++ ++ ++ ++ true ++ ++ ++ + + + +diff --git a/src/main.c b/src/main.c +index c5e15707..7bc57b6e 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -120,11 +120,7 @@ void set_macos_bundle_resources(lua_State *L); + #endif + + int main(int argc, char **argv) { +-#ifdef _WIN32 +- HINSTANCE lib = LoadLibrary("user32.dll"); +- int (*SetProcessDPIAware)() = (void*) GetProcAddress(lib, "SetProcessDPIAware"); +- SetProcessDPIAware(); +-#else ++#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); + #endif + diff --git a/tasks/lite-xl__lite-xl-1413/tests/test.sh b/tasks/lite-xl__lite-xl-1413/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e2dcd159f7f435028fa718eae37b93bb87539ca --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/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 73f3cd4fcdcf377cd42207cae1cbfce20997326f > "$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/lite-xl__lite-xl-1413/tests/verifier.py b/tasks/lite-xl__lite-xl-1413/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1413/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/lite-xl__lite-xl-1434/environment/Dockerfile b/tasks/lite-xl__lite-xl-1434/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3f9ddd624cc9c0d284868e39f495cb50622a632 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d15108309c8ce98f9a5412e87a05d39a177e5765 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && 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/lite-xl__lite-xl-1434/instruction.md b/tasks/lite-xl__lite-xl-1434/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ecb2858f23516748d022676bf067ae2702efa19b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(CI): bump dependency versions + +## Description + +This shouldn't change anything and remove all those warnings in the CI runs. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1434/solution/patch.diff b/tasks/lite-xl__lite-xl-1434/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9697c63d48659b518381361be02d62dc6c667310 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/solution/patch.diff @@ -0,0 +1,155 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 8fb880ff..a3cbb2a4 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -30,9 +30,9 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-linux-$(uname -m)-portable" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Update Packages +@@ -47,7 +47,7 @@ jobs: + if: ${{ matrix.config.cc == 'gcc' }} + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + if: ${{ matrix.config.cc == 'gcc' }} + with: + name: Linux Artifacts +@@ -71,9 +71,9 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-$(uname -m)" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Install Dependencies +@@ -85,7 +85,7 @@ jobs: + - name: Create DMG Image + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg + - name: Upload DMG Image +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: macOS DMG Image + path: ${{ env.INSTALL_NAME }}.dmg +@@ -100,7 +100,7 @@ jobs: + run: + shell: msys2 {0} + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: msys2/setup-msys2@v2 + with: + msystem: ${{ matrix.msystem }} +@@ -127,7 +127,7 @@ jobs: + - name: Package + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: Windows Artifacts + path: ${{ env.INSTALL_NAME }}.zip +@@ -137,20 +137,22 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- arch: [amd64, amd64_x86] ++ arch: ++ - { target: x86, name: i686 } ++ - { target: x64, name: x86_64 } + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: ilammy/msvc-dev-cmd@v1 + with: +- arch: ${{ matrix.arch }} +- - uses: actions/setup-python@v1 ++ arch: ${{ matrix.arch.target }} ++ - uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install meson and ninja + run: pip install meson ninja + - name: Set up environment variables + run: | +- "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch }}" >> $env:GITHUB_ENV ++ "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV + - name: Configure +@@ -158,13 +160,14 @@ jobs: + meson setup --wrap-mode=forcefallback build + Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward + - name: Build +- run: meson install -C build --destdir="../lite-xl" ++ run: | ++ meson install -C build --destdir="../lite-xl" + - name: Package + run: | + Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" + Compress-Archive -Path lite-xl -DestinationPath "$env:INSTALL_NAME.zip" + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: Windows Artifacts (MSVC) + path: ${{ env.INSTALL_NAME }}.zip +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index ea0e1848..47b826dd 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -21,7 +21,7 @@ jobs: + version: ${{ steps.tag.outputs.version }} + steps: + - name: Checkout code +- uses: actions/checkout@v2 ++ uses: actions/checkout@v3 + - name: Fetch Version + id: tag + run: | +@@ -58,9 +58,9 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Update Packages +@@ -115,9 +115,9 @@ jobs: + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Install Dependencies +@@ -150,7 +150,7 @@ jobs: + run: + shell: msys2 {0} + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: msys2/setup-msys2@v2 + with: + msystem: ${{ matrix.msystem }} diff --git a/tasks/lite-xl__lite-xl-1434/solution/solve.sh b/tasks/lite-xl__lite-xl-1434/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/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/lite-xl__lite-xl-1434/task.toml b/tasks/lite-xl__lite-xl-1434/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfc59e4b7a8b0f344d66b82502500fdf4cf92231 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1434" +description = "fix(CI): bump dependency versions" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d15108309c8ce98f9a5412e87a05d39a177e5765" +reference = "https://github.com/lite-xl/lite-xl/pull/1434" +source_access = "auto" +built_at = "2026-11-16T16:09:56.261859+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a9441c5438fc28aa3369cab6215e7eb4500efa07759e0182001251bca091a810" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-07T17:24:28Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + ".github/workflows/release.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 45 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.282908+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b6c61ddfbb69aef1d91f6ffaa60bbb9dc01ad5e4648f032c7c292080515a96f0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1434/tests/capture.py b/tasks/lite-xl__lite-xl-1434/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/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/lite-xl__lite-xl-1434/tests/instruction.md b/tasks/lite-xl__lite-xl-1434/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ecb2858f23516748d022676bf067ae2702efa19b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(CI): bump dependency versions + +## Description + +This shouldn't change anything and remove all those warnings in the CI runs. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1434/tests/oracle.patch b/tasks/lite-xl__lite-xl-1434/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9697c63d48659b518381361be02d62dc6c667310 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/tests/oracle.patch @@ -0,0 +1,155 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 8fb880ff..a3cbb2a4 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -30,9 +30,9 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-linux-$(uname -m)-portable" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Update Packages +@@ -47,7 +47,7 @@ jobs: + if: ${{ matrix.config.cc == 'gcc' }} + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + if: ${{ matrix.config.cc == 'gcc' }} + with: + name: Linux Artifacts +@@ -71,9 +71,9 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-$(uname -m)" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Install Dependencies +@@ -85,7 +85,7 @@ jobs: + - name: Create DMG Image + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg + - name: Upload DMG Image +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: macOS DMG Image + path: ${{ env.INSTALL_NAME }}.dmg +@@ -100,7 +100,7 @@ jobs: + run: + shell: msys2 {0} + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: msys2/setup-msys2@v2 + with: + msystem: ${{ matrix.msystem }} +@@ -127,7 +127,7 @@ jobs: + - name: Package + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: Windows Artifacts + path: ${{ env.INSTALL_NAME }}.zip +@@ -137,20 +137,22 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- arch: [amd64, amd64_x86] ++ arch: ++ - { target: x86, name: i686 } ++ - { target: x64, name: x86_64 } + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: ilammy/msvc-dev-cmd@v1 + with: +- arch: ${{ matrix.arch }} +- - uses: actions/setup-python@v1 ++ arch: ${{ matrix.arch.target }} ++ - uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install meson and ninja + run: pip install meson ninja + - name: Set up environment variables + run: | +- "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch }}" >> $env:GITHUB_ENV ++ "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV + - name: Configure +@@ -158,13 +160,14 @@ jobs: + meson setup --wrap-mode=forcefallback build + Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward + - name: Build +- run: meson install -C build --destdir="../lite-xl" ++ run: | ++ meson install -C build --destdir="../lite-xl" + - name: Package + run: | + Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" + Compress-Archive -Path lite-xl -DestinationPath "$env:INSTALL_NAME.zip" + - name: Upload Artifacts +- uses: actions/upload-artifact@v2 ++ uses: actions/upload-artifact@v3 + with: + name: Windows Artifacts (MSVC) + path: ${{ env.INSTALL_NAME }}.zip +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index ea0e1848..47b826dd 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -21,7 +21,7 @@ jobs: + version: ${{ steps.tag.outputs.version }} + steps: + - name: Checkout code +- uses: actions/checkout@v2 ++ uses: actions/checkout@v3 + - name: Fetch Version + id: tag + run: | +@@ -58,9 +58,9 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Update Packages +@@ -115,9 +115,9 @@ jobs: + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v4 + with: + python-version: 3.9 + - name: Install Dependencies +@@ -150,7 +150,7 @@ jobs: + run: + shell: msys2 {0} + steps: +- - uses: actions/checkout@v2 ++ - uses: actions/checkout@v3 + - uses: msys2/setup-msys2@v2 + with: + msystem: ${{ matrix.msystem }} diff --git a/tasks/lite-xl__lite-xl-1434/tests/test.sh b/tasks/lite-xl__lite-xl-1434/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..65f52460d338893b2e5faa96ba58bc9e3e70538e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/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 d15108309c8ce98f9a5412e87a05d39a177e5765 > "$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/lite-xl__lite-xl-1434/tests/verifier.py b/tasks/lite-xl__lite-xl-1434/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1434/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/lite-xl__lite-xl-1435/environment/Dockerfile b/tasks/lite-xl__lite-xl-1435/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3f9ddd624cc9c0d284868e39f495cb50622a632 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d15108309c8ce98f9a5412e87a05d39a177e5765 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && 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/lite-xl__lite-xl-1435/instruction.md b/tasks/lite-xl__lite-xl-1435/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73a2531e06c472289a833a86c2d62e94f2fca987 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Optimizing MSYS2 CI + +## Description + +This PR tries to reduce CI build times. + +1. MSYS2 updates are not run. This usually isn't necessary. +2. Install MSYS2 packages in the setup phase. If you look at the workflow, MSYS2 packages installed when running in MSYS2 will not be cached since there is no post-build step. +3. Download the subprojects before patching. This prevents meson from reconfiguring the project due to file changes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1435/solution/patch.diff b/tasks/lite-xl__lite-xl-1435/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7c3042f518301bac312254eab9884df8d11dd671 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/solution/patch.diff @@ -0,0 +1,88 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 8fb880ff..7bf2adda 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -95,7 +95,9 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- msystem: [MINGW32, MINGW64] ++ config: ++ - {msystem: MINGW32, arch: i686} ++ - {msystem: MINGW64, arch: x86_64} + defaults: + run: + shell: msys2 {0} +@@ -103,12 +105,16 @@ jobs: + - uses: actions/checkout@v2 + - uses: msys2/setup-msys2@v2 + with: +- msystem: ${{ matrix.msystem }} +- update: true ++ msystem: ${{ matrix.config.msystem }} + install: >- + base-devel + git + zip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" +@@ -119,6 +125,7 @@ jobs: + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" + fi + - name: Install Dependencies ++ if: false + run: bash scripts/install-dependencies.sh --debug + - name: Build + run: | +@@ -155,8 +162,11 @@ jobs: + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV + - name: Configure + run: | +- meson setup --wrap-mode=forcefallback build ++ # Download the subprojects first so we can patch it before configuring. ++ # This avoids reconfiguring the subprojects when compiling. ++ meson subprojects download + Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward ++ meson setup --wrap-mode=forcefallback build + - name: Build + run: meson install -C build --destdir="../lite-xl" + - name: Package +diff --git a/scripts/build.sh b/scripts/build.sh +index 82eb95f0..0cd4e8d8 100644 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -124,6 +124,16 @@ main() { + + rm -rf "${build_dir}" + ++ if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]]; then ++ # download the subprojects so we can start patching before configure. ++ # this will prevent reconfiguring the project. ++ meson subprojects download ++ lua_subproject_path=$(echo subprojects/lua-*/) ++ if [[ -d $lua_subproject_path ]]; then ++ patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff ++ fi ++ fi ++ + CFLAGS=$CFLAGS LDFLAGS=$LDFLAGS meson setup \ + --buildtype=$build_type \ + --prefix "$prefix" \ +@@ -134,11 +144,6 @@ main() { + $pgo \ + "${build_dir}" + +- lua_subproject_path=$(echo subprojects/lua-*/) +- if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]] && [[ -d $lua_subproject_path ]]; then +- patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff +- fi +- + meson compile -C "${build_dir}" + + if [[ $pgo != "" ]]; then diff --git a/tasks/lite-xl__lite-xl-1435/solution/solve.sh b/tasks/lite-xl__lite-xl-1435/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/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/lite-xl__lite-xl-1435/task.toml b/tasks/lite-xl__lite-xl-1435/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..263a77aff14e1171f3169598547f6752c93064ce --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1435" +description = "Optimizing MSYS2 CI" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d15108309c8ce98f9a5412e87a05d39a177e5765" +reference = "https://github.com/lite-xl/lite-xl/pull/1435" +source_access = "auto" +built_at = "2026-11-16T16:09:56.254929+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:989d16f2acb1903c60b28c39fbbf831a17ec3ee629392a4cf3457f90912d2cdd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-07T17:25:32Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + "scripts/build.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 33 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.283358+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b6c61ddfbb69aef1d91f6ffaa60bbb9dc01ad5e4648f032c7c292080515a96f0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1435/tests/capture.py b/tasks/lite-xl__lite-xl-1435/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/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/lite-xl__lite-xl-1435/tests/instruction.md b/tasks/lite-xl__lite-xl-1435/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73a2531e06c472289a833a86c2d62e94f2fca987 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Optimizing MSYS2 CI + +## Description + +This PR tries to reduce CI build times. + +1. MSYS2 updates are not run. This usually isn't necessary. +2. Install MSYS2 packages in the setup phase. If you look at the workflow, MSYS2 packages installed when running in MSYS2 will not be cached since there is no post-build step. +3. Download the subprojects before patching. This prevents meson from reconfiguring the project due to file changes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1435/tests/oracle.patch b/tasks/lite-xl__lite-xl-1435/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7c3042f518301bac312254eab9884df8d11dd671 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/tests/oracle.patch @@ -0,0 +1,88 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 8fb880ff..7bf2adda 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -95,7 +95,9 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- msystem: [MINGW32, MINGW64] ++ config: ++ - {msystem: MINGW32, arch: i686} ++ - {msystem: MINGW64, arch: x86_64} + defaults: + run: + shell: msys2 {0} +@@ -103,12 +105,16 @@ jobs: + - uses: actions/checkout@v2 + - uses: msys2/setup-msys2@v2 + with: +- msystem: ${{ matrix.msystem }} +- update: true ++ msystem: ${{ matrix.config.msystem }} + install: >- + base-devel + git + zip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" +@@ -119,6 +125,7 @@ jobs: + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" + fi + - name: Install Dependencies ++ if: false + run: bash scripts/install-dependencies.sh --debug + - name: Build + run: | +@@ -155,8 +162,11 @@ jobs: + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV + - name: Configure + run: | +- meson setup --wrap-mode=forcefallback build ++ # Download the subprojects first so we can patch it before configuring. ++ # This avoids reconfiguring the subprojects when compiling. ++ meson subprojects download + Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward ++ meson setup --wrap-mode=forcefallback build + - name: Build + run: meson install -C build --destdir="../lite-xl" + - name: Package +diff --git a/scripts/build.sh b/scripts/build.sh +index 82eb95f0..0cd4e8d8 100644 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -124,6 +124,16 @@ main() { + + rm -rf "${build_dir}" + ++ if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]]; then ++ # download the subprojects so we can start patching before configure. ++ # this will prevent reconfiguring the project. ++ meson subprojects download ++ lua_subproject_path=$(echo subprojects/lua-*/) ++ if [[ -d $lua_subproject_path ]]; then ++ patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff ++ fi ++ fi ++ + CFLAGS=$CFLAGS LDFLAGS=$LDFLAGS meson setup \ + --buildtype=$build_type \ + --prefix "$prefix" \ +@@ -134,11 +144,6 @@ main() { + $pgo \ + "${build_dir}" + +- lua_subproject_path=$(echo subprojects/lua-*/) +- if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]] && [[ -d $lua_subproject_path ]]; then +- patch -d $lua_subproject_path -p1 --forward < resources/windows/001-lua-unicode.diff +- fi +- + meson compile -C "${build_dir}" + + if [[ $pgo != "" ]]; then diff --git a/tasks/lite-xl__lite-xl-1435/tests/test.sh b/tasks/lite-xl__lite-xl-1435/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..65f52460d338893b2e5faa96ba58bc9e3e70538e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/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 d15108309c8ce98f9a5412e87a05d39a177e5765 > "$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/lite-xl__lite-xl-1435/tests/verifier.py b/tasks/lite-xl__lite-xl-1435/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1435/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/lite-xl__lite-xl-1436/environment/Dockerfile b/tasks/lite-xl__lite-xl-1436/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3f9ddd624cc9c0d284868e39f495cb50622a632 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d15108309c8ce98f9a5412e87a05d39a177e5765 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d15108309c8ce98f9a5412e87a05d39a177e5765 \ + && 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/lite-xl__lite-xl-1436/instruction.md b/tasks/lite-xl__lite-xl-1436/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a536a743400194426a399879a78e9516be2a34c9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** upgrade header files to Lua 5.4 + +## Description + +Old header. New Lua. Me compile no work. + +Updated the function prototypes, macros and structures to Lua 5.4. +Polyfills for backward compatibility with other Lua versions are removed. +lite_xl_plugin_init is now extern so that dlls with multiple entrypoints (eventually) can use it. + +I've tested this new header with [cffi-lua][1] and [ltreesitter][2]. +No warnings. + +Requires #1440. + + +[1]: https://github.com/q66/cffi-lua +[2]: https://github.com/euclidianAce/ltreesitter + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1436/solution/patch.diff b/tasks/lite-xl__lite-xl-1436/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f23d49172a8f8d6761b5706179d2a32e7c6f78e8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/solution/patch.diff @@ -0,0 +1,3700 @@ +diff --git a/resources/include/lite_xl_plugin_api.h b/resources/include/lite_xl_plugin_api.h +new file mode 100644 +index 00000000..2947039e +--- /dev/null ++++ b/resources/include/lite_xl_plugin_api.h +@@ -0,0 +1,2563 @@ ++/** ++ * lite_xl_plugin_api.h ++ * API for writing C extension modules loaded by Lite XL. ++ * This file is licensed under MIT. ++ * ++ * The Lite XL plugin API is quite simple. ++ * You would write a lua C extension and replace any references to lua.h, lauxlib.h ++ * and lualib.h with lite_xl_plugin_api.h. ++ * In your main file (where your entrypoint resides), define LITE_XL_PLUGIN_ENTRYPOINT. ++ * If you have multiple entrypoints, define LITE_XL_PLUGIN_ENTRYPOINT in one of them. ++ * ++ * After that, you need to create a Lite XL entrypoint, which is formatted as ++ * luaopen_lite_xl_xxxxx instead of luaopen_xxxxx. ++ * This entrypoint accepts a lua_State and an extra parameter of type void *. ++ * In this entrypoint, call lite_xl_plugin_init() with the extra parameter. ++ * If you have multiple entrypoints, you must call lite_xl_plugin_init() in ++ * each of them. ++ * This function is not thread safe, so don't try to do anything stupid. ++ * ++ * An example: ++ * ++ * #define LITE_XL_PLUGIN_ENTRYPOINT ++ * #include "lite_xl_plugin_api.h" ++ * int luaopen_lite_xl_xxxxx(lua_State* L, void* XL) { ++ * lite_xl_plugin_init(XL); ++ * ... ++ * return 1; ++ * } ++ * ++ * You can compile the library just like any Lua library without linking to Lua. ++ * An example command would be: gcc -shared -o xxxxx.so xxxxx.c ++ * You must not link to ANY lua library to avoid symbol collision. ++ * ++ * This file contains stock configuration for a typical installation of Lua 5.4. ++ * DO NOT MODIFY ANYTHING. MODIFYING STUFFS IN HERE WILL BREAK ++ * COMPATIBILITY WITH LITE XL AND CAUSE UNDEBUGGABLE BUGS. ++**/ ++#ifndef LITE_XL_PLUGIN_API ++#define LITE_XL_PLUGIN_API ++ ++#include ++#include ++ ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ ++/* FOR_EACH macro */ ++#define CONCAT(arg1, arg2) CONCAT1(arg1, arg2) ++#define CONCAT1(arg1, arg2) CONCAT2(arg1, arg2) ++#define CONCAT2(arg1, arg2) arg1##arg2 ++#define FE_1(what, x) what x ++#define FE_2(what, x, ...) what x,FE_1(what, __VA_ARGS__) ++#define FE_3(what, x, ...) what x,FE_2(what, __VA_ARGS__) ++#define FE_4(what, x, ...) what x,FE_3(what, __VA_ARGS__) ++#define FE_5(what, x, ...) what x,FE_4(what, __VA_ARGS__) ++#define FE_6(what, x, ...) what x,FE_5(what, __VA_ARGS__) ++#define FE_7(what, x, ...) what x,FE_6(what, __VA_ARGS__) ++#define FE_8(what, x, ...) what x,FE_7(what, __VA_ARGS__) ++#define FOR_EACH_NARG(...) FOR_EACH_NARG_(__VA_ARGS__, FOR_EACH_RSEQ_N()) ++#define FOR_EACH_NARG_(...) FOR_EACH_ARG_N(__VA_ARGS__) ++#define FOR_EACH_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N ++#define FOR_EACH_RSEQ_N() 8, 7, 6, 5, 4, 3, 2, 1, 0 ++#define FOR_EACH_(N, what, ...) CONCAT(FE_, N)(what, __VA_ARGS__) ++#define FOR_EACH(what, ...) FOR_EACH_(FOR_EACH_NARG(__VA_ARGS__), what, __VA_ARGS__) ++ ++#define SYMBOL_WRAP_DECL(ret, name, ...) \ ++ ret name(__VA_ARGS__) ++ ++#define SYMBOL_WRAP_CALL(name, ...) \ ++ __##name(__VA_ARGS__) ++ ++#define SYMBOL_WRAP_CALL_FB(name, ...) \ ++ return __lite_xl_fallback_##name(__VA_ARGS__) ++ ++#ifdef LITE_XL_PLUGIN_ENTRYPOINT ++ #define SYMBOL_DECLARE(ret, name, ...) \ ++ static ret (*__##name) (__VA_ARGS__); \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); \ ++ static ret __lite_xl_fallback_##name(FOR_EACH(UNUSED, __VA_ARGS__)) { \ ++ fputs("warning: " #name " is a stub", stderr); \ ++ exit(1); \ ++ } ++ #define SYMBOL_DECLARE_VARARG(ret, name, ...) \ ++ static ret (*__##name) (__VA_ARGS__, ...); \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__, ...); \ ++ static ret __lite_xl_fallback_##name(FOR_EACH(UNUSED, __VA_ARGS__), ...) { \ ++ fputs("warning: " #name " is a stub", stderr); \ ++ exit(1); \ ++ } ++#else ++ #define SYMBOL_DECLARE(ret, name, ...) \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); ++ #define SYMBOL_DECLARE_VARARG(ret, name, ...) \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__, ...); ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: luaconf.h $ ++** Configuration file for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef luaconf_h ++#define luaconf_h ++ ++#include ++#include ++ ++ ++/* ++** =================================================================== ++** General Configuration File for Lua ++** ++** Some definitions here can be changed externally, through the compiler ++** (e.g., with '-D' options): They are commented out or protected ++** by '#if !defined' guards. However, several other definitions ++** should be changed directly here, either because they affect the ++** Lua ABI (by making the changes here, you ensure that all software ++** connected to Lua, such as C libraries, will be compiled with the same ++** configuration); or because they are seldom changed. ++** ++** Search for "@@" to find all configurable definitions. ++** =================================================================== ++*/ ++ ++ ++/* ++** {==================================================================== ++** System Configuration: macros to adapt (if needed) Lua to some ++** particular platform, for instance restricting it to C89. ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_USE_C89 controls the use of non-ISO-C89 features. ++** Define it if you want Lua to avoid the use of a few C99 features ++** or Windows-specific features on Windows. ++*/ ++/* #define LUA_USE_C89 */ ++ ++ ++/* ++** By default, Lua on Windows use (some) specific Windows features ++*/ ++#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) ++#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ ++#endif ++ ++ ++#if defined(LUA_USE_WINDOWS) ++#define LUA_DL_DLL /* enable support for DLL */ ++#define LUA_USE_C89 /* broadly, Windows is C89 */ ++#endif ++ ++ ++#if defined(LUA_USE_LINUX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ ++#endif ++ ++ ++#if defined(LUA_USE_MACOSX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ ++#endif ++ ++ ++/* ++@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits. ++*/ ++#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3) ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Number types. These options should not be ++** set externally, because any other code connected to Lua must ++** use the same configuration. ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_INT_TYPE defines the type for Lua integers. ++@@ LUA_FLOAT_TYPE defines the type for Lua floats. ++** Lua should work fine with any mix of these options supported ++** by your C compiler. The usual configurations are 64-bit integers ++** and 'double' (the default), 32-bit integers and 'float' (for ++** restricted platforms), and 'long'/'double' (for C compilers not ++** compliant with C99, which may not have support for 'long long'). ++*/ ++ ++/* predefined options for LUA_INT_TYPE */ ++#define LUA_INT_INT 1 ++#define LUA_INT_LONG 2 ++#define LUA_INT_LONGLONG 3 ++ ++/* predefined options for LUA_FLOAT_TYPE */ ++#define LUA_FLOAT_FLOAT 1 ++#define LUA_FLOAT_DOUBLE 2 ++#define LUA_FLOAT_LONGDOUBLE 3 ++ ++ ++/* Default configuration ('long long' and 'double', for 64-bit Lua) */ ++#define LUA_INT_DEFAULT LUA_INT_LONGLONG ++#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE ++ ++ ++/* ++@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. ++*/ ++#define LUA_32BITS 0 ++ ++ ++/* ++@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for ++** C89 ('long' and 'double'); Windows always has '__int64', so it does ++** not need to use this case. ++*/ ++#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) ++#define LUA_C89_NUMBERS 1 ++#else ++#define LUA_C89_NUMBERS 0 ++#endif ++ ++ ++#if LUA_32BITS /* { */ ++/* ++** 32-bit integers and 'float' ++*/ ++#if LUAI_IS32INT /* use 'int' if big enough */ ++#define LUA_INT_TYPE LUA_INT_INT ++#else /* otherwise use 'long' */ ++#define LUA_INT_TYPE LUA_INT_LONG ++#endif ++#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT ++ ++#elif LUA_C89_NUMBERS /* }{ */ ++/* ++** largest types available for C89 ('long' and 'double') ++*/ ++#define LUA_INT_TYPE LUA_INT_LONG ++#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE ++ ++#else /* }{ */ ++/* use defaults */ ++ ++#define LUA_INT_TYPE LUA_INT_DEFAULT ++#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT ++ ++#endif /* } */ ++ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Paths. ++** =================================================================== ++*/ ++ ++/* ++** LUA_PATH_SEP is the character that separates templates in a path. ++** LUA_PATH_MARK is the string that marks the substitution points in a ++** template. ++** LUA_EXEC_DIR in a Windows path is replaced by the executable's ++** directory. ++*/ ++#define LUA_PATH_SEP ";" ++#define LUA_PATH_MARK "?" ++#define LUA_EXEC_DIR "!" ++ ++ ++/* ++@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for ++** Lua libraries. ++@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for ++** C libraries. ++** CHANGE them if your machine has a non-conventional directory ++** hierarchy or if you want to install your libraries in ++** non-conventional directories. ++*/ ++ ++#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#if defined(_WIN32) /* { */ ++/* ++** In Windows, any exclamation mark ('!') in the path is replaced by the ++** path of the directory of the executable file of the current process. ++*/ ++#define LUA_LDIR "!\\lua\\" ++#define LUA_CDIR "!\\" ++#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ ++ LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ ++ ".\\?.lua;" ".\\?\\init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.dll;" \ ++ LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ ++ LUA_CDIR"loadall.dll;" ".\\?.dll" ++#endif ++ ++#else /* }{ */ ++ ++#define LUA_ROOT "/usr/local/" ++#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" ++#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ ++ "./?.lua;" "./?/init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" ++#endif ++ ++#endif /* } */ ++ ++ ++/* ++@@ LUA_DIRSEP is the directory separator (for submodules). ++** CHANGE it if your machine does not use "/" as the directory separator ++** and is not Windows. (On Windows Lua automatically uses "\".) ++*/ ++#if !defined(LUA_DIRSEP) ++ ++#if defined(_WIN32) ++#define LUA_DIRSEP "\\" ++#else ++#define LUA_DIRSEP "/" ++#endif ++ ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Marks for exported symbols in the C code ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_API is a mark for all core API functions. ++@@ LUALIB_API is a mark for all auxiliary library functions. ++@@ LUAMOD_API is a mark for all standard library opening functions. ++** CHANGE them if you need to define those functions in some special way. ++** For instance, if you want to create one Windows DLL with the core and ++** the libraries, you may want to use the following definition (define ++** LUA_BUILD_AS_DLL to get it). ++*/ ++#if defined(LUA_BUILD_AS_DLL) /* { */ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ ++#define LUA_API __declspec(dllexport) ++#else /* }{ */ ++#define LUA_API __declspec(dllimport) ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#define LUA_API extern ++ ++#endif /* } */ ++ ++ ++/* ++** More often than not the libs go together with the core. ++*/ ++#define LUALIB_API LUA_API ++#define LUAMOD_API LUA_API ++ ++ ++/* ++@@ LUAI_FUNC is a mark for all extern functions that are not to be ++** exported to outside modules. ++@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, ++** none of which to be exported to outside modules (LUAI_DDEF for ++** definitions and LUAI_DDEC for declarations). ++** CHANGE them if you need to mark them in some special way. Elf/gcc ++** (versions 3.2 and later) mark them as "hidden" to optimize access ++** when Lua is compiled as a shared library. Not all elf targets support ++** this attribute. Unfortunately, gcc does not offer a way to check ++** whether the target offers that support, and those without support ++** give a warning about it. To avoid these warnings, change to the ++** default definition. ++*/ ++#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ ++ defined(__ELF__) /* { */ ++#define LUAI_FUNC __attribute__((visibility("internal"))) extern ++#else /* }{ */ ++#define LUAI_FUNC extern ++#endif /* } */ ++ ++#define LUAI_DDEC(dec) LUAI_FUNC dec ++#define LUAI_DDEF /* empty */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Compatibility with previous versions ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3. ++** You can define it to get all options, or change specific options ++** to fit your specific needs. ++*/ ++#if defined(LUA_COMPAT_5_3) /* { */ ++ ++/* ++@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated ++** functions in the mathematical library. ++** (These functions were already officially removed in 5.3; ++** nevertheless they are still available here.) ++*/ ++#define LUA_COMPAT_MATHLIB ++ ++/* ++@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for ++** manipulating other integer types (lua_pushunsigned, lua_tounsigned, ++** luaL_checkint, luaL_checklong, etc.) ++** (These macros were also officially removed in 5.3, but they are still ++** available here.) ++*/ ++#define LUA_COMPAT_APIINTCASTS ++ ++ ++/* ++@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod ++** using '__lt'. ++*/ ++#define LUA_COMPAT_LT_LE ++ ++ ++/* ++@@ The following macros supply trivial compatibility for some ++** changes in the API. The macros themselves document how to ++** change your code to avoid using them. ++** (Once more, these macros were officially removed in 5.3, but they are ++** still available here.) ++*/ ++#define lua_strlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_objlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) ++#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Numbers (low-level part). ++** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* ++** satisfy your needs. ++** =================================================================== ++*/ ++ ++/* ++@@ LUAI_UACNUMBER is the result of a 'default argument promotion' ++@@ over a floating number. ++@@ l_floatatt(x) corrects float attribute 'x' to the proper float type ++** by prefixing it with one of FLT/DBL/LDBL. ++@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. ++@@ LUA_NUMBER_FMT is the format for writing floats. ++@@ lua_number2str converts a float to a string. ++@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. ++@@ l_floor takes the floor of a float. ++@@ lua_str2number converts a decimal numeral to a number. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define l_floor(x) (l_mathop(floor)(x)) ++ ++#define lua_number2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) ++ ++/* ++@@ lua_numbertointeger converts a float number with an integral value ++** to an integer, or returns 0 if float is not within the range of ++** a lua_Integer. (The range comparisons are tricky because of ++** rounding. The tests here assume a two-complement representation, ++** where MININTEGER always has an exact representation as a float; ++** MAXINTEGER may not have one, and therefore its conversion to float ++** may have an ill-defined value.) ++*/ ++#define lua_numbertointeger(n,p) \ ++ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ ++ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ ++ (*(p) = (LUA_INTEGER)(n), 1)) ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ ++ ++#define LUA_NUMBER float ++ ++#define l_floatatt(n) (FLT_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.7g" ++ ++#define l_mathop(op) op##f ++ ++#define lua_str2number(s,p) strtof((s), (p)) ++ ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ ++ ++#define LUA_NUMBER long double ++ ++#define l_floatatt(n) (LDBL_##n) ++ ++#define LUAI_UACNUMBER long double ++ ++#define LUA_NUMBER_FRMLEN "L" ++#define LUA_NUMBER_FMT "%.19Lg" ++ ++#define l_mathop(op) op##l ++ ++#define lua_str2number(s,p) strtold((s), (p)) ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ ++ ++#define LUA_NUMBER double ++ ++#define l_floatatt(n) (DBL_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.14g" ++ ++#define l_mathop(op) op ++ ++#define lua_str2number(s,p) strtod((s), (p)) ++ ++#else /* }{ */ ++ ++#error "numeric float type not defined" ++ ++#endif /* } */ ++ ++ ++ ++/* ++@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. ++@@ LUAI_UACINT is the result of a 'default argument promotion' ++@@ over a LUA_INTEGER. ++@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. ++@@ LUA_INTEGER_FMT is the format for writing integers. ++@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. ++@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. ++@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED. ++@@ lua_integer2str converts an integer to a string. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" ++ ++#define LUAI_UACINT LUA_INTEGER ++ ++#define lua_integer2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) ++ ++/* ++** use LUAI_UACINT here to avoid problems with promotions (which ++** can turn a comparison between unsigneds into a signed comparison) ++*/ ++#define LUA_UNSIGNED unsigned LUAI_UACINT ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_INT_TYPE == LUA_INT_INT /* { int */ ++ ++#define LUA_INTEGER int ++#define LUA_INTEGER_FRMLEN "" ++ ++#define LUA_MAXINTEGER INT_MAX ++#define LUA_MININTEGER INT_MIN ++ ++#define LUA_MAXUNSIGNED UINT_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ ++ ++#define LUA_INTEGER long ++#define LUA_INTEGER_FRMLEN "l" ++ ++#define LUA_MAXINTEGER LONG_MAX ++#define LUA_MININTEGER LONG_MIN ++ ++#define LUA_MAXUNSIGNED ULONG_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ ++ ++/* use presence of macro LLONG_MAX as proxy for C99 compliance */ ++#if defined(LLONG_MAX) /* { */ ++/* use ISO C99 stuff */ ++ ++#define LUA_INTEGER long long ++#define LUA_INTEGER_FRMLEN "ll" ++ ++#define LUA_MAXINTEGER LLONG_MAX ++#define LUA_MININTEGER LLONG_MIN ++ ++#define LUA_MAXUNSIGNED ULLONG_MAX ++ ++#elif defined(LUA_USE_WINDOWS) /* }{ */ ++/* in Windows, can use specific Windows types */ ++ ++#define LUA_INTEGER __int64 ++#define LUA_INTEGER_FRMLEN "I64" ++ ++#define LUA_MAXINTEGER _I64_MAX ++#define LUA_MININTEGER _I64_MIN ++ ++#define LUA_MAXUNSIGNED _UI64_MAX ++ ++#else /* }{ */ ++ ++#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ ++ or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" ++ ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#error "numeric integer type not defined" ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Dependencies with C99 and other C details ++** =================================================================== ++*/ ++ ++/* ++@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. ++** (All uses in Lua have only one format item.) ++*/ ++#if !defined(LUA_USE_C89) ++#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) ++#else ++#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) ++#endif ++ ++ ++/* ++@@ lua_strx2number converts a hexadecimal numeral to a number. ++** In C99, 'strtod' does that conversion. Otherwise, you can ++** leave 'lua_strx2number' undefined and Lua will provide its own ++** implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_strx2number(s,p) lua_str2number(s,p) ++#endif ++ ++ ++/* ++@@ lua_pointer2str converts a pointer to a readable string in a ++** non-specified way. ++*/ ++#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) ++ ++ ++/* ++@@ lua_number2strx converts a float to a hexadecimal numeral. ++** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. ++** Otherwise, you can leave 'lua_number2strx' undefined and Lua will ++** provide its own implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_number2strx(L,b,sz,f,n) \ ++ ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) ++#endif ++ ++ ++/* ++** 'strtof' and 'opf' variants for math functions are not valid in ++** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the ++** availability of these variants. ('math.h' is already included in ++** all files that use these macros.) ++*/ ++#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) ++#undef l_mathop /* variants not available */ ++#undef lua_str2number ++#define l_mathop(op) (lua_Number)op /* no variant */ ++#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) ++#endif ++ ++ ++/* ++@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation ++** functions. It must be a numerical type; Lua will use 'intptr_t' if ++** available, otherwise it will use 'ptrdiff_t' (the nearest thing to ++** 'intptr_t' in C89) ++*/ ++#define LUA_KCONTEXT ptrdiff_t ++ ++#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ ++ __STDC_VERSION__ >= 199901L ++#include ++#if defined(INTPTR_MAX) /* even in C99 this type is optional */ ++#undef LUA_KCONTEXT ++#define LUA_KCONTEXT intptr_t ++#endif ++#endif ++ ++ ++/* ++@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). ++** Change that if you do not want to use C locales. (Code using this ++** macro must include the header 'locale.h'.) ++*/ ++#if !defined(lua_getlocaledecpoint) ++#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) ++#endif ++ ++ ++/* ++** macros to improve jump prediction, used mostly for error handling ++** and debug facilities. (Some macros in the Lua API use these macros. ++** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your ++** code.) ++*/ ++#if !defined(luai_likely) ++ ++#if defined(__GNUC__) && !defined(LUA_NOBUILTIN) ++#define luai_likely(x) (__builtin_expect(((x) != 0), 1)) ++#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0)) ++#else ++#define luai_likely(x) (x) ++#define luai_unlikely(x) (x) ++#endif ++ ++#endif ++ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) ++/* shorter names for Lua's own use */ ++#define l_likely(x) luai_likely(x) ++#define l_unlikely(x) luai_unlikely(x) ++#endif ++ ++ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Language Variations ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some ++** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from ++** numbers to strings. Define LUA_NOCVTS2N to turn off automatic ++** coercion from strings to numbers. ++*/ ++/* #define LUA_NOCVTN2S */ ++/* #define LUA_NOCVTS2N */ ++ ++ ++/* ++@@ LUA_USE_APICHECK turns on several consistency checks on the C API. ++** Define it as a help when debugging C code. ++*/ ++#if defined(LUA_USE_APICHECK) ++#include ++#define luai_apicheck(l,e) assert(e) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Macros that affect the API and must be stable (that is, must be the ++** same when you compile Lua and when you compile code that links to ++** Lua). ++** ===================================================================== ++*/ ++ ++/* ++@@ LUAI_MAXSTACK limits the size of the Lua stack. ++** CHANGE it if you need a different limit. This limit is arbitrary; ++** its only purpose is to stop Lua from consuming unlimited stack ++** space (and to reserve some numbers for pseudo-indices). ++** (It must fit into max(size_t)/32.) ++*/ ++#if LUAI_IS32INT ++#define LUAI_MAXSTACK 1000000 ++#else ++#define LUAI_MAXSTACK 15000 ++#endif ++ ++ ++/* ++@@ LUA_EXTRASPACE defines the size of a raw memory area associated with ++** a Lua state with very fast access. ++** CHANGE it if you need a different size. ++*/ ++#define LUA_EXTRASPACE (sizeof(void *)) ++ ++ ++/* ++@@ LUA_IDSIZE gives the maximum size for the description of the source ++@@ of a function in debug information. ++** CHANGE it if you want a different size. ++*/ ++#define LUA_IDSIZE 60 ++ ++ ++/* ++@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. ++*/ ++#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number))) ++ ++ ++/* ++@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure ++** maximum alignment for the other items in that union. ++*/ ++#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l ++ ++/* }================================================================== */ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lua.h $ ++** Lua - A Scripting Language ++** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ++** See Copyright Notice at the end of this file ++*/ ++ ++ ++#ifndef lua_h ++#define lua_h ++ ++#include ++#include ++ ++ ++#define LUA_VERSION_MAJOR "5" ++#define LUA_VERSION_MINOR "4" ++#define LUA_VERSION_RELEASE "4" ++ ++#define LUA_VERSION_NUM 504 ++#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 4) ++ ++#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE ++#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2022 Lua.org, PUC-Rio" ++#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" ++ ++ ++/* mark for precompiled code ('Lua') */ ++#define LUA_SIGNATURE "\x1bLua" ++ ++/* option for multiple returns in 'lua_pcall' and 'lua_call' */ ++#define LUA_MULTRET (-1) ++ ++ ++/* ++** Pseudo-indices ++** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty ++** space after that to help overflow detection) ++*/ ++#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) ++#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) ++ ++ ++/* thread status */ ++#define LUA_OK 0 ++#define LUA_YIELD 1 ++#define LUA_ERRRUN 2 ++#define LUA_ERRSYNTAX 3 ++#define LUA_ERRMEM 4 ++#define LUA_ERRERR 5 ++ ++ ++typedef struct lua_State lua_State; ++ ++ ++/* ++** basic types ++*/ ++#define LUA_TNONE (-1) ++ ++#define LUA_TNIL 0 ++#define LUA_TBOOLEAN 1 ++#define LUA_TLIGHTUSERDATA 2 ++#define LUA_TNUMBER 3 ++#define LUA_TSTRING 4 ++#define LUA_TTABLE 5 ++#define LUA_TFUNCTION 6 ++#define LUA_TUSERDATA 7 ++#define LUA_TTHREAD 8 ++ ++#define LUA_NUMTYPES 9 ++ ++ ++ ++/* minimum Lua stack available to a C function */ ++#define LUA_MINSTACK 20 ++ ++ ++/* predefined values in the registry */ ++#define LUA_RIDX_MAINTHREAD 1 ++#define LUA_RIDX_GLOBALS 2 ++#define LUA_RIDX_LAST LUA_RIDX_GLOBALS ++ ++ ++/* type of numbers in Lua */ ++typedef LUA_NUMBER lua_Number; ++ ++ ++/* type for integer functions */ ++typedef LUA_INTEGER lua_Integer; ++ ++/* unsigned integer type */ ++typedef LUA_UNSIGNED lua_Unsigned; ++ ++/* type for continuation-function contexts */ ++typedef LUA_KCONTEXT lua_KContext; ++ ++ ++/* ++** Type for C functions registered with Lua ++*/ ++typedef int (*lua_CFunction) (lua_State *L); ++ ++/* ++** Type for continuation functions ++*/ ++typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); ++ ++ ++/* ++** Type for functions that read/write blocks when loading/dumping Lua chunks ++*/ ++typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); ++ ++typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); ++ ++ ++/* ++** Type for memory-allocation functions ++*/ ++typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); ++ ++ ++/* ++** Type for warning functions ++*/ ++typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); ++ ++ ++ ++ ++/* ++** generic extra include file ++*/ ++#if defined(LUA_USER_H) ++#include LUA_USER_H ++#endif ++ ++ ++/* ++** RCS ident string ++*/ ++extern const char lua_ident[]; ++ ++ ++/* ++** state manipulation ++*/ ++SYMBOL_DECLARE(lua_State *, lua_newstate, lua_Alloc f, void *ud) ++SYMBOL_DECLARE(void, lua_close, lua_State *L) ++SYMBOL_DECLARE(lua_State *, lua_newthread, lua_State *L) ++SYMBOL_DECLARE(int, lua_resetthread, lua_State *L) ++ ++SYMBOL_DECLARE(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) ++ ++ ++SYMBOL_DECLARE(lua_Number, lua_version, lua_State *L) ++ ++ ++/* ++** basic stack manipulation ++*/ ++SYMBOL_DECLARE(int , lua_absindex, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_gettop, lua_State *L) ++SYMBOL_DECLARE(void, lua_settop, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_pushvalue, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_rotate, lua_State *L, int idx, int n) ++SYMBOL_DECLARE(void, lua_copy, lua_State *L, int fromidx, int toidx) ++SYMBOL_DECLARE(int , lua_checkstack, lua_State *L, int n) ++ ++SYMBOL_DECLARE(void, lua_xmove, lua_State *from, lua_State *to, int n) ++ ++ ++/* ++** access functions (stack -> C) ++*/ ++ ++SYMBOL_DECLARE(int , lua_isnumber, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isstring, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_iscfunction, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isinteger, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isuserdata, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_type, lua_State *L, int idx) ++SYMBOL_DECLARE(const char *, lua_typename, lua_State *L, int tp) ++ ++SYMBOL_DECLARE(lua_Number , lua_tonumberx, lua_State *L, int idx, int *isnum) ++SYMBOL_DECLARE(lua_Integer , lua_tointegerx, lua_State *L, int idx, int *isnum) ++SYMBOL_DECLARE(int , lua_toboolean, lua_State *L, int idx) ++SYMBOL_DECLARE(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) ++SYMBOL_DECLARE(lua_Unsigned , lua_rawlen, lua_State *L, int idx) ++SYMBOL_DECLARE(lua_CFunction , lua_tocfunction, lua_State *L, int idx) ++SYMBOL_DECLARE(void *, lua_touserdata, lua_State *L, int idx) ++SYMBOL_DECLARE(lua_State *, lua_tothread, lua_State *L, int idx) ++SYMBOL_DECLARE(const void *, lua_topointer, lua_State *L, int idx) ++ ++ ++/* ++** Comparison and arithmetic functions ++*/ ++ ++#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ ++#define LUA_OPSUB 1 ++#define LUA_OPMUL 2 ++#define LUA_OPMOD 3 ++#define LUA_OPPOW 4 ++#define LUA_OPDIV 5 ++#define LUA_OPIDIV 6 ++#define LUA_OPBAND 7 ++#define LUA_OPBOR 8 ++#define LUA_OPBXOR 9 ++#define LUA_OPSHL 10 ++#define LUA_OPSHR 11 ++#define LUA_OPUNM 12 ++#define LUA_OPBNOT 13 ++ ++SYMBOL_DECLARE(void , lua_arith, lua_State *L, int op) ++ ++#define LUA_OPEQ 0 ++#define LUA_OPLT 1 ++#define LUA_OPLE 2 ++ ++SYMBOL_DECLARE(int , lua_rawequal, lua_State *L, int idx1, int idx2) ++SYMBOL_DECLARE(int , lua_compare, lua_State *L, int idx1, int idx2, int op) ++ ++ ++/* ++** push functions (C -> stack) ++*/ ++SYMBOL_DECLARE(void , lua_pushnil, lua_State *L) ++SYMBOL_DECLARE(void , lua_pushnumber, lua_State *L, lua_Number n) ++SYMBOL_DECLARE(void , lua_pushinteger, lua_State *L, lua_Integer n) ++SYMBOL_DECLARE(const char *, lua_pushlstring, lua_State *L, const char *s, size_t len) ++SYMBOL_DECLARE(const char *, lua_pushstring, lua_State *L, const char *s) ++SYMBOL_DECLARE(const char *, lua_pushvfstring, lua_State *L, const char *fmt, ++ va_list argp) ++SYMBOL_DECLARE_VARARG(const char *, lua_pushfstring, lua_State *L, const char *fmt) ++SYMBOL_DECLARE(void , lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) ++SYMBOL_DECLARE(void , lua_pushboolean, lua_State *L, int b) ++SYMBOL_DECLARE(void , lua_pushlightuserdata, lua_State *L, void *p) ++SYMBOL_DECLARE(int , lua_pushthread, lua_State *L) ++ ++ ++/* ++** get functions (Lua -> stack) ++*/ ++SYMBOL_DECLARE(int , lua_getglobal, lua_State *L, const char *name) ++SYMBOL_DECLARE(int , lua_gettable, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_getfield, lua_State *L, int idx, const char *k) ++SYMBOL_DECLARE(int , lua_geti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(int , lua_rawget, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_rawgeti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(int , lua_rawgetp, lua_State *L, int idx, const void *p) ++ ++SYMBOL_DECLARE(void , lua_createtable, lua_State *L, int narr, int nrec) ++SYMBOL_DECLARE(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) ++SYMBOL_DECLARE(int , lua_getmetatable, lua_State *L, int objindex) ++SYMBOL_DECLARE(int , lua_getiuservalue, lua_State *L, int idx, int n) ++ ++ ++/* ++** set functions (stack -> Lua) ++*/ ++SYMBOL_DECLARE(void , lua_setglobal, lua_State *L, const char *name) ++SYMBOL_DECLARE(void , lua_settable, lua_State *L, int idx) ++SYMBOL_DECLARE(void , lua_setfield, lua_State *L, int idx, const char *k) ++SYMBOL_DECLARE(void , lua_seti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(void , lua_rawset, lua_State *L, int idx) ++SYMBOL_DECLARE(void , lua_rawseti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(void , lua_rawsetp, lua_State *L, int idx, const void *p) ++SYMBOL_DECLARE(int , lua_setmetatable, lua_State *L, int objindex) ++SYMBOL_DECLARE(int , lua_setiuservalue, lua_State *L, int idx, int n) ++ ++ ++/* ++** 'load' and 'call' functions (load and run Lua code) ++*/ ++SYMBOL_DECLARE(void, lua_callk, lua_State *L, int nargs, int nresults, ++ lua_KContext ctx, lua_KFunction k) ++#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) ++ ++SYMBOL_DECLARE(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, ++ lua_KContext ctx, lua_KFunction k) ++#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) ++ ++SYMBOL_DECLARE(int, lua_load, lua_State *L, lua_Reader reader, void *dt, ++ const char *chunkname, const char *mode) ++ ++SYMBOL_DECLARE(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) ++ ++ ++/* ++** coroutine functions ++*/ ++SYMBOL_DECLARE(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, ++ lua_KFunction k) ++SYMBOL_DECLARE(int, lua_resume, lua_State *L, lua_State *from, int narg, ++ int *nres) ++SYMBOL_DECLARE(int, lua_status, lua_State *L) ++SYMBOL_DECLARE(int, lua_isyieldable, lua_State *L) ++ ++#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) ++ ++ ++/* ++** Warning-related functions ++*/ ++SYMBOL_DECLARE(void, lua_setwarnf, lua_State *L, lua_WarnFunction f, void *ud) ++SYMBOL_DECLARE(void, lua_warning, lua_State *L, const char *msg, int tocont) ++ ++ ++/* ++** garbage-collection function and options ++*/ ++ ++#define LUA_GCSTOP 0 ++#define LUA_GCRESTART 1 ++#define LUA_GCCOLLECT 2 ++#define LUA_GCCOUNT 3 ++#define LUA_GCCOUNTB 4 ++#define LUA_GCSTEP 5 ++#define LUA_GCSETPAUSE 6 ++#define LUA_GCSETSTEPMUL 7 ++#define LUA_GCISRUNNING 9 ++#define LUA_GCGEN 10 ++#define LUA_GCINC 11 ++ ++SYMBOL_DECLARE_VARARG(int, lua_gc, lua_State *L, int what) ++ ++ ++/* ++** miscellaneous functions ++*/ ++ ++SYMBOL_DECLARE(int , lua_error, lua_State *L) ++ ++SYMBOL_DECLARE(int , lua_next, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(void, lua_concat, lua_State *L, int n) ++SYMBOL_DECLARE(void, lua_len, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(size_t, lua_stringtonumber, lua_State *L, const char *s) ++ ++SYMBOL_DECLARE(lua_Alloc, lua_getallocf, lua_State *L, void **ud) ++SYMBOL_DECLARE(void , lua_setallocf, lua_State *L, lua_Alloc f, void *ud) ++ ++SYMBOL_DECLARE(void, lua_toclose, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_closeslot, lua_State *L, int idx) ++ ++ ++/* ++** {============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) ++ ++#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) ++#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) ++ ++#define lua_pop(L,n) lua_settop(L, -(n)-1) ++ ++#define lua_newtable(L) lua_createtable(L, 0, 0) ++ ++#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) ++ ++#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) ++ ++#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) ++#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) ++#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) ++#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) ++#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) ++#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) ++#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) ++#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) ++ ++#define lua_pushliteral(L, s) lua_pushstring(L, "" s) ++ ++#define lua_pushglobaltable(L) \ ++ ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) ++ ++#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) ++ ++ ++#define lua_insert(L,idx) lua_rotate(L, (idx), 1) ++ ++#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) ++ ++#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) ++ ++/* }============================================================== */ ++ ++ ++/* ++** {============================================================== ++** compatibility macros ++** =============================================================== ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) ++#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) ++#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) ++ ++#endif ++ ++#define lua_newuserdata(L,s) lua_newuserdatauv(L,s,1) ++#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1) ++#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1) ++ ++#define LUA_NUMTAGS LUA_NUMTYPES ++ ++/* }============================================================== */ ++ ++/* ++** {====================================================================== ++** Debug API ++** ======================================================================= ++*/ ++ ++ ++/* ++** Event codes ++*/ ++#define LUA_HOOKCALL 0 ++#define LUA_HOOKRET 1 ++#define LUA_HOOKLINE 2 ++#define LUA_HOOKCOUNT 3 ++#define LUA_HOOKTAILCALL 4 ++ ++ ++/* ++** Event masks ++*/ ++#define LUA_MASKCALL (1 << LUA_HOOKCALL) ++#define LUA_MASKRET (1 << LUA_HOOKRET) ++#define LUA_MASKLINE (1 << LUA_HOOKLINE) ++#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) ++ ++typedef struct lua_Debug lua_Debug; /* activation record */ ++ ++ ++/* Functions to be called by the debugger in specific events */ ++typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); ++ ++ ++SYMBOL_DECLARE(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) ++SYMBOL_DECLARE(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) ++SYMBOL_DECLARE(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) ++SYMBOL_DECLARE(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) ++SYMBOL_DECLARE(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) ++SYMBOL_DECLARE(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) ++ ++SYMBOL_DECLARE(void *, lua_upvalueid, lua_State *L, int fidx, int n) ++SYMBOL_DECLARE(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, ++ int fidx2, int n2) ++ ++SYMBOL_DECLARE(void, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) ++SYMBOL_DECLARE(lua_Hook, lua_gethook, lua_State *L) ++SYMBOL_DECLARE(int, lua_gethookmask, lua_State *L) ++SYMBOL_DECLARE(int, lua_gethookcount, lua_State *L) ++ ++SYMBOL_DECLARE(int, lua_setcstacklimit, lua_State *L, unsigned int limit) ++ ++struct lua_Debug { ++ int event; ++ const char *name; /* (n) */ ++ const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ ++ const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ ++ const char *source; /* (S) */ ++ size_t srclen; /* (S) */ ++ int currentline; /* (l) */ ++ int linedefined; /* (S) */ ++ int lastlinedefined; /* (S) */ ++ unsigned char nups; /* (u) number of upvalues */ ++ unsigned char nparams;/* (u) number of parameters */ ++ char isvararg; /* (u) */ ++ char istailcall; /* (t) */ ++ unsigned short ftransfer; /* (r) index of first value transferred */ ++ unsigned short ntransfer; /* (r) number of transferred values */ ++ char short_src[LUA_IDSIZE]; /* (S) */ ++ /* private part */ ++ struct CallInfo *i_ci; /* active function */ ++}; ++ ++/* }====================================================================== */ ++ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lauxlib.h $ ++** Auxiliary functions for building Lua libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lauxlib_h ++#define lauxlib_h ++ ++ ++#include ++#include ++ ++ ++/* global table */ ++#define LUA_GNAME "_G" ++ ++ ++typedef struct luaL_Buffer luaL_Buffer; ++ ++ ++/* extra error code for 'luaL_loadfilex' */ ++#define LUA_ERRFILE (LUA_ERRERR+1) ++ ++ ++/* key, in the registry, for table of loaded modules */ ++#define LUA_LOADED_TABLE "_LOADED" ++ ++ ++/* key, in the registry, for table of preloaded loaders */ ++#define LUA_PRELOAD_TABLE "_PRELOAD" ++ ++ ++typedef struct luaL_Reg { ++ const char *name; ++ lua_CFunction func; ++} luaL_Reg; ++ ++ ++#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) ++ ++SYMBOL_DECLARE(void, luaL_checkversion_, lua_State *L, lua_Number ver, size_t sz) ++#define luaL_checkversion(L) \ ++ luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) ++ ++SYMBOL_DECLARE(int, luaL_getmetafield, lua_State *L, int obj, const char *e) ++SYMBOL_DECLARE(int, luaL_callmeta, lua_State *L, int obj, const char *e) ++SYMBOL_DECLARE(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) ++SYMBOL_DECLARE(int, luaL_argerror, lua_State *L, int arg, const char *extramsg) ++SYMBOL_DECLARE(int, luaL_typeerror, lua_State *L, int arg, const char *tname) ++SYMBOL_DECLARE(const char *, luaL_checklstring, lua_State *L, int arg, ++ size_t *l) ++SYMBOL_DECLARE(const char *, luaL_optlstring, lua_State *L, int arg, ++ const char *def, size_t *l) ++SYMBOL_DECLARE(lua_Number, luaL_checknumber, lua_State *L, int arg) ++SYMBOL_DECLARE(lua_Number, luaL_optnumber, lua_State *L, int arg, lua_Number def) ++ ++SYMBOL_DECLARE(lua_Integer, luaL_checkinteger, lua_State *L, int arg) ++SYMBOL_DECLARE(lua_Integer, luaL_optinteger, lua_State *L, int arg, ++ lua_Integer def) ++ ++SYMBOL_DECLARE(void, luaL_checkstack, lua_State *L, int sz, const char *msg) ++SYMBOL_DECLARE(void, luaL_checktype, lua_State *L, int arg, int t) ++SYMBOL_DECLARE(void, luaL_checkany, lua_State *L, int arg) ++ ++SYMBOL_DECLARE(int , luaL_newmetatable, lua_State *L, const char *tname) ++SYMBOL_DECLARE(void , luaL_setmetatable, lua_State *L, const char *tname) ++SYMBOL_DECLARE(void *, luaL_testudata, lua_State *L, int ud, const char *tname) ++SYMBOL_DECLARE(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) ++ ++SYMBOL_DECLARE(void, luaL_where, lua_State *L, int lvl) ++SYMBOL_DECLARE_VARARG(int, luaL_error, lua_State *L, const char *fmt) ++ ++SYMBOL_DECLARE(int, luaL_checkoption, lua_State *L, int arg, const char *def, ++ const char *const lst[]) ++ ++SYMBOL_DECLARE(int, luaL_fileresult, lua_State *L, int stat, const char *fname) ++SYMBOL_DECLARE(int, luaL_execresult, lua_State *L, int stat) ++ ++ ++/* predefined references */ ++#define LUA_NOREF (-2) ++#define LUA_REFNIL (-1) ++ ++SYMBOL_DECLARE(int, luaL_ref, lua_State *L, int t) ++SYMBOL_DECLARE(void, luaL_unref, lua_State *L, int t, int ref) ++ ++SYMBOL_DECLARE(int, luaL_loadfilex, lua_State *L, const char *filename, ++ const char *mode) ++ ++#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) ++ ++SYMBOL_DECLARE(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, ++ const char *name, const char *mode) ++SYMBOL_DECLARE(int, luaL_loadstring, lua_State *L, const char *s) ++ ++SYMBOL_DECLARE(lua_State *, luaL_newstate, void) ++ ++SYMBOL_DECLARE(lua_Integer, luaL_len, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(void, luaL_addgsub, luaL_Buffer *b, const char *s, ++ const char *p, const char *r) ++SYMBOL_DECLARE(const char *, luaL_gsub, lua_State *L, const char *s, ++ const char *p, const char *r) ++ ++SYMBOL_DECLARE(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) ++ ++SYMBOL_DECLARE(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) ++ ++SYMBOL_DECLARE(void, luaL_traceback, lua_State *L, lua_State *L1, ++ const char *msg, int level) ++ ++SYMBOL_DECLARE(void, luaL_requiref, lua_State *L, const char *modname, ++ lua_CFunction openf, int glb) ++ ++/* ++** =============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++ ++#define luaL_newlibtable(L,l) \ ++ lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) ++ ++#define luaL_newlib(L,l) \ ++ (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) ++ ++#define luaL_argcheck(L, cond,arg,extramsg) \ ++ ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg)))) ++ ++#define luaL_argexpected(L,cond,arg,tname) \ ++ ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname)))) ++ ++#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) ++#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) ++ ++#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) ++ ++#define luaL_dofile(L, fn) \ ++ (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_dostring(L, s) \ ++ (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) ++ ++#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) ++ ++#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) ++ ++ ++/* ++** Perform arithmetic operations on lua_Integer values with wrap-around ++** semantics, as the Lua core does. ++*/ ++#define luaL_intop(op,v1,v2) \ ++ ((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2))) ++ ++ ++/* push the value used to represent failure/error */ ++#define luaL_pushfail(L) lua_pushnil(L) ++ ++ ++/* ++** Internal assertions for in-house debugging ++*/ ++#if !defined(lua_assert) ++ ++#if defined LUAI_ASSERT ++ #include ++ #define lua_assert(c) assert(c) ++#else ++ #define lua_assert(c) ((void)0) ++#endif ++ ++#endif ++ ++ ++ ++/* ++** {====================================================== ++** Generic Buffer manipulation ++** ======================================================= ++*/ ++ ++struct luaL_Buffer { ++ char *b; /* buffer address */ ++ size_t size; /* buffer size */ ++ size_t n; /* number of characters in buffer */ ++ lua_State *L; ++ union { ++ LUAI_MAXALIGN; /* ensure maximum alignment for buffer */ ++ char b[LUAL_BUFFERSIZE]; /* initial buffer */ ++ } init; ++}; ++ ++ ++#define luaL_bufflen(bf) ((bf)->n) ++#define luaL_buffaddr(bf) ((bf)->b) ++ ++ ++#define luaL_addchar(B,c) \ ++ ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ ++ ((B)->b[(B)->n++] = (c))) ++ ++#define luaL_addsize(B,s) ((B)->n += (s)) ++ ++#define luaL_buffsub(B,s) ((B)->n -= (s)) ++ ++SYMBOL_DECLARE(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) ++SYMBOL_DECLARE(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) ++SYMBOL_DECLARE(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) ++SYMBOL_DECLARE(void, luaL_addstring, luaL_Buffer *B, const char *s) ++SYMBOL_DECLARE(void, luaL_addvalue, luaL_Buffer *B) ++SYMBOL_DECLARE(void, luaL_pushresult, luaL_Buffer *B) ++SYMBOL_DECLARE(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) ++SYMBOL_DECLARE(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) ++ ++#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** File handles for IO library ++** ======================================================= ++*/ ++ ++/* ++** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and ++** initial structure 'luaL_Stream' (it may contain other fields ++** after that initial structure). ++*/ ++ ++#define LUA_FILEHANDLE "FILE*" ++ ++ ++typedef struct luaL_Stream { ++ FILE *f; /* stream (NULL for incompletely created streams) */ ++ lua_CFunction closef; /* to close stream (NULL for closed streams) */ ++} luaL_Stream; ++ ++/* }====================================================== */ ++ ++/* ++** {================================================================== ++** "Abstraction Layer" for basic report of messages and errors ++** =================================================================== ++*/ ++ ++/* print a string */ ++#if !defined(lua_writestring) ++#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) ++#endif ++ ++/* print a newline and flush the output */ ++#if !defined(lua_writeline) ++#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) ++#endif ++ ++/* print an error message */ ++#if !defined(lua_writestringerror) ++#define lua_writestringerror(s,p) \ ++ (fprintf(stderr, (s), (p)), fflush(stderr)) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {============================================================ ++** Compatibility with deprecated conversions ++** ============================================================= ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) ++#define luaL_optunsigned(L,a,d) \ ++ ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) ++ ++#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) ++#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) ++ ++#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) ++#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) ++ ++#endif ++/* }============================================================ */ ++ ++ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lualib.h $ ++** Lua standard libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lualib_h ++#define lualib_h ++ ++ ++/* version suffix for environment variable names */ ++#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR ++ ++ ++SYMBOL_DECLARE(int, luaopen_base, lua_State *L) ++ ++#define LUA_COLIBNAME "coroutine" ++SYMBOL_DECLARE(int, luaopen_coroutine, lua_State *L) ++ ++#define LUA_TABLIBNAME "table" ++SYMBOL_DECLARE(int, luaopen_table, lua_State *L) ++ ++#define LUA_IOLIBNAME "io" ++SYMBOL_DECLARE(int, luaopen_io, lua_State *L) ++ ++#define LUA_OSLIBNAME "os" ++SYMBOL_DECLARE(int, luaopen_os, lua_State *L) ++ ++#define LUA_STRLIBNAME "string" ++SYMBOL_DECLARE(int, luaopen_string, lua_State *L) ++ ++#define LUA_UTF8LIBNAME "utf8" ++SYMBOL_DECLARE(int, luaopen_utf8, lua_State *L) ++ ++#define LUA_MATHLIBNAME "math" ++SYMBOL_DECLARE(int, luaopen_math, lua_State *L) ++ ++#define LUA_DBLIBNAME "debug" ++SYMBOL_DECLARE(int, luaopen_debug, lua_State *L) ++ ++#define LUA_LOADLIBNAME "package" ++SYMBOL_DECLARE(int, luaopen_package, lua_State *L) ++ ++ ++/* open all previous libraries */ ++SYMBOL_DECLARE(void, luaL_openlibs, lua_State *L) ++ ++ ++#endif ++ ++ ++ ++ ++ ++#ifdef LITE_XL_PLUGIN_ENTRYPOINT ++ ++SYMBOL_WRAP_DECL(lua_State *, lua_newstate, lua_Alloc f, void *ud) { ++ return SYMBOL_WRAP_CALL(lua_newstate, f, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_close, lua_State *L) { ++ SYMBOL_WRAP_CALL(lua_close, L); ++} ++SYMBOL_WRAP_DECL(lua_State *, lua_newthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_newthread, L); ++} ++SYMBOL_WRAP_DECL(int, lua_resetthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_resetthread, L); ++} ++ ++SYMBOL_WRAP_DECL(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) { ++ return SYMBOL_WRAP_CALL(lua_atpanic, L, panicf); ++} ++ ++ ++SYMBOL_WRAP_DECL(lua_Number, lua_version, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_version, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_absindex, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_absindex, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_gettop, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gettop, L); ++} ++SYMBOL_WRAP_DECL(void, lua_settop, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_settop, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_pushvalue, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_pushvalue, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_rotate, lua_State *L, int idx, int n) { ++ SYMBOL_WRAP_CALL(lua_rotate, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_copy, lua_State *L, int fromidx, int toidx) { ++ SYMBOL_WRAP_CALL(lua_copy, L, fromidx, toidx); ++} ++SYMBOL_WRAP_DECL(int, lua_checkstack, lua_State *L, int sz) { ++ return SYMBOL_WRAP_CALL(lua_checkstack, L, sz); ++} ++SYMBOL_WRAP_DECL(void, lua_xmove, lua_State *from, lua_State *to, int n) { ++ SYMBOL_WRAP_CALL(lua_xmove, from, to, n); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_isnumber, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isnumber, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isstring, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isstring, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_iscfunction, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_iscfunction, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isinteger, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isinteger, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isuserdata, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isuserdata, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_type, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_type, L, idx); ++} ++SYMBOL_WRAP_DECL(const char *, lua_typename, lua_State *L, int tp) { ++ return SYMBOL_WRAP_CALL(lua_typename, L, tp); ++} ++ ++SYMBOL_WRAP_DECL(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum) { ++ return SYMBOL_WRAP_CALL(lua_tonumberx, L, idx, isnum); ++} ++SYMBOL_WRAP_DECL(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum) { ++ return SYMBOL_WRAP_CALL(lua_tointegerx, L, idx, isnum); ++} ++SYMBOL_WRAP_DECL(int, lua_toboolean, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_toboolean, L, idx); ++} ++SYMBOL_WRAP_DECL(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) { ++ return SYMBOL_WRAP_CALL(lua_tolstring, L, idx, len); ++} ++SYMBOL_WRAP_DECL(lua_Unsigned, lua_rawlen, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_rawlen, L, idx); ++} ++SYMBOL_WRAP_DECL(lua_CFunction, lua_tocfunction, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_tocfunction, L, idx); ++} ++SYMBOL_WRAP_DECL(void *, lua_touserdata, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_touserdata, L, idx); ++} ++SYMBOL_WRAP_DECL(lua_State *, lua_tothread, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_tothread, L, idx); ++} ++SYMBOL_WRAP_DECL(const void *, lua_topointer, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_topointer, L, idx); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_arith, lua_State *L, int op) { ++ SYMBOL_WRAP_CALL(lua_arith, L, op); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_rawequal, lua_State *L, int idx1, int idx2) { ++ return SYMBOL_WRAP_CALL(lua_rawequal, L, idx1, idx2); ++} ++SYMBOL_WRAP_DECL(int, lua_compare, lua_State *L, int idx1, int idx2, int op) { ++ return SYMBOL_WRAP_CALL(lua_compare, L, idx1, idx2, op); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_pushnil, lua_State *L) { ++ SYMBOL_WRAP_CALL(lua_pushnil, L); ++} ++SYMBOL_WRAP_DECL(void, lua_pushnumber, lua_State *L, lua_Number n) { ++ SYMBOL_WRAP_CALL(lua_pushnumber, L, n); ++} ++SYMBOL_WRAP_DECL(void, lua_pushinteger, lua_State *L, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_pushinteger, L, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l) { ++ return SYMBOL_WRAP_CALL(lua_pushlstring, L, s, l); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushstring, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(lua_pushstring, L, s); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp) { ++ return SYMBOL_WRAP_CALL(lua_pushvfstring, L, fmt, argp); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...) { ++ const char *res; ++ va_list argp; ++ va_start(argp, fmt); ++ res = lua_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ return res; ++} ++SYMBOL_WRAP_DECL(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) { ++ SYMBOL_WRAP_CALL(lua_pushcclosure, L, fn, n); ++} ++SYMBOL_WRAP_DECL(void, lua_pushboolean, lua_State *L, int b) { ++ SYMBOL_WRAP_CALL(lua_pushboolean, L, b); ++} ++SYMBOL_WRAP_DECL(void, lua_pushlightuserdata, lua_State *L, void *p) { ++ SYMBOL_WRAP_CALL(lua_pushlightuserdata, L, p); ++} ++SYMBOL_WRAP_DECL(int, lua_pushthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_pushthread, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_getglobal, lua_State *L, const char *var) { ++ return SYMBOL_WRAP_CALL(lua_getglobal, L, var); ++} ++SYMBOL_WRAP_DECL(int, lua_gettable, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_gettable, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_getfield, lua_State *L, int idx, const char *k) { ++ return SYMBOL_WRAP_CALL(lua_getfield, L, idx, k); ++} ++SYMBOL_WRAP_DECL(int , lua_geti, lua_State *L, int idx, lua_Integer n) { ++ return SYMBOL_WRAP_CALL(lua_geti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(int, lua_rawget, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_rawget, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_rawgeti, lua_State *L, int idx, lua_Integer n) { ++ return SYMBOL_WRAP_CALL(lua_rawgeti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(int, lua_rawgetp, lua_State *L, int idx, const void *p) { ++ return SYMBOL_WRAP_CALL(lua_rawgetp, L, idx, p); ++} ++SYMBOL_WRAP_DECL(void, lua_createtable, lua_State *L, int narr, int nrec) { ++ SYMBOL_WRAP_CALL(lua_createtable, L, narr, nrec); ++} ++SYMBOL_WRAP_DECL(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) { ++ return SYMBOL_WRAP_CALL(lua_newuserdatauv, L, sz, nuvalue); ++} ++SYMBOL_WRAP_DECL(int, lua_getmetatable, lua_State *L, int objindex) { ++ return SYMBOL_WRAP_CALL(lua_getmetatable, L, objindex); ++} ++SYMBOL_WRAP_DECL(int, lua_getiuservalue, lua_State *L, int idx, int n) { ++ return SYMBOL_WRAP_CALL(lua_getiuservalue, L, idx, n); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_setglobal, lua_State *L, const char *var) { ++ SYMBOL_WRAP_CALL(lua_setglobal, L, var); ++} ++SYMBOL_WRAP_DECL(void, lua_settable, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_settable, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_setfield, lua_State *L, int idx, const char *k) { ++ SYMBOL_WRAP_CALL(lua_setfield, L, idx, k); ++} ++SYMBOL_WRAP_DECL(void, lua_seti, lua_State *L, int idx, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_seti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_rawset, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_rawset, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_rawseti, lua_State *L, int idx, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_rawseti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_rawsetp, lua_State *L, int idx, const void *p) { ++ SYMBOL_WRAP_CALL(lua_rawsetp, L, idx, p); ++} ++SYMBOL_WRAP_DECL(int, lua_setmetatable, lua_State *L, int objindex) { ++ return SYMBOL_WRAP_CALL(lua_setmetatable, L, objindex); ++} ++SYMBOL_WRAP_DECL(int, lua_setiuservalue, lua_State *L, int idx, int n) { ++ return SYMBOL_WRAP_CALL(lua_setiuservalue, L, idx, n); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { ++ SYMBOL_WRAP_CALL(lua_callk, L, nargs, nresults, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { ++ return SYMBOL_WRAP_CALL(lua_pcallk, L, nargs, nresults, errfunc, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode) { ++ return SYMBOL_WRAP_CALL(lua_load, L, reader, dt, chunkname, mode); ++} ++SYMBOL_WRAP_DECL(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) { ++ return SYMBOL_WRAP_CALL(lua_dump, L, writer, data, strip); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k) { ++ return SYMBOL_WRAP_CALL(lua_yieldk, L, nresults, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_resume, lua_State *L, lua_State *from, int narg, int *nres) { ++ return SYMBOL_WRAP_CALL(lua_resume, L, from, narg, nres); ++} ++SYMBOL_WRAP_DECL(int, lua_status, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_status, L); ++} ++SYMBOL_WRAP_DECL(int, lua_isyieldable, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_isyieldable, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_setwarnf, lua_State *L, lua_WarnFunction f, void *ud) { ++ SYMBOL_WRAP_CALL(lua_setwarnf, L, f, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_warning, lua_State *L, const char *msg, int tocont) { ++ SYMBOL_WRAP_CALL(lua_warning, L, msg, tocont); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_gc, lua_State *L, int what, ...) { ++ /* there are no straightforward ways of passing data. */ ++ int r; ++ va_list ap; ++ va_start(ap, what); ++ if (what == LUA_GCSTEP) { ++ int stepsize = va_arg(ap, int); ++ r = __lua_gc(L, what, stepsize); ++ } else if (what == LUA_GCINC) { ++ int pause = va_arg(ap, int); ++ int stepmul = va_arg(ap, int); ++ int stepsize = va_arg(ap, int); ++ r = __lua_gc(L, what, pause, stepmul, stepsize); ++ } else if (what == LUA_GCGEN) { ++ int minormul = va_arg(ap, int); ++ int majormul = va_arg(ap, int); ++ r = __lua_gc(L, what, minormul, majormul); ++ } else { ++ r = __lua_gc(L, what); ++ } ++ return r; ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_error, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_error, L); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_next, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_next, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_concat, lua_State *L, int n) { ++ SYMBOL_WRAP_CALL(lua_concat, L, n); ++} ++SYMBOL_WRAP_DECL(void, lua_len, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_len, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(size_t, lua_stringtonumber, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(lua_stringtonumber, L, s); ++} ++ ++SYMBOL_WRAP_DECL(lua_Alloc, lua_getallocf, lua_State *L, void **ud) { ++ return SYMBOL_WRAP_CALL(lua_getallocf, L, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud) { ++ SYMBOL_WRAP_CALL(lua_setallocf, L, f, ud); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_toclose, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_toclose, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_closeslot, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_closeslot, L, idx); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) { ++ return SYMBOL_WRAP_CALL(lua_getstack, L, level, ar); ++} ++SYMBOL_WRAP_DECL(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) { ++ return SYMBOL_WRAP_CALL(lua_getinfo, L, what, ar); ++} ++SYMBOL_WRAP_DECL(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) { ++ return SYMBOL_WRAP_CALL(lua_getlocal, L, ar, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) { ++ return SYMBOL_WRAP_CALL(lua_setlocal, L, ar, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) { ++ return SYMBOL_WRAP_CALL(lua_getupvalue, L, funcindex, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) { ++ return SYMBOL_WRAP_CALL(lua_setupvalue, L, funcindex, n); ++} ++ ++SYMBOL_WRAP_DECL(void *, lua_upvalueid, lua_State *L, int fidx, int n) { ++ return SYMBOL_WRAP_CALL(lua_upvalueid, L, fidx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2) { ++ SYMBOL_WRAP_CALL(lua_upvaluejoin, L, fidx1, n1, fidx2, n2); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) { ++ SYMBOL_WRAP_CALL(lua_sethook, L, func, mask, count); ++} ++SYMBOL_WRAP_DECL(lua_Hook, lua_gethook, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethook, L); ++} ++SYMBOL_WRAP_DECL(int, lua_gethookmask, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethookmask, L); ++} ++SYMBOL_WRAP_DECL(int, lua_gethookcount, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethookcount, L); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_setcstacklimit, lua_State *L, unsigned int limit) { ++ return SYMBOL_WRAP_CALL(lua_setcstacklimit, L, limit); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, luaL_checkversion_, lua_State *L, lua_Number ver, size_t sz) { ++ SYMBOL_WRAP_CALL(luaL_checkversion_, L, ver, sz); ++} ++SYMBOL_WRAP_DECL(int, luaL_getmetafield, lua_State *L, int obj, const char *e) { ++ return SYMBOL_WRAP_CALL(luaL_getmetafield, L, obj, e); ++} ++SYMBOL_WRAP_DECL(int, luaL_callmeta, lua_State *L, int obj, const char *e) { ++ return SYMBOL_WRAP_CALL(luaL_callmeta, L, obj, e); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) { ++ return SYMBOL_WRAP_CALL(luaL_tolstring, L, idx, len); ++} ++SYMBOL_WRAP_DECL(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg) { ++ return SYMBOL_WRAP_CALL(luaL_argerror, L, numarg, extramsg); ++} ++SYMBOL_WRAP_DECL(int, luaL_typeerror, lua_State *L, int arg, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_typeerror, L, arg, tname); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l) { ++ return SYMBOL_WRAP_CALL(luaL_checklstring, L, numArg, l); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l) { ++ return SYMBOL_WRAP_CALL(luaL_optlstring, L, numArg, def, l); ++} ++SYMBOL_WRAP_DECL(lua_Number, luaL_checknumber, lua_State *L, int numArg) { ++ return SYMBOL_WRAP_CALL(luaL_checknumber, L, numArg); ++} ++SYMBOL_WRAP_DECL(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def) { ++ return SYMBOL_WRAP_CALL(luaL_optnumber, L, nArg, def); ++} ++ ++SYMBOL_WRAP_DECL(lua_Integer, luaL_checkinteger, lua_State *L, int numArg) { ++ return SYMBOL_WRAP_CALL(luaL_checkinteger, L, numArg); ++} ++SYMBOL_WRAP_DECL(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def) { ++ return SYMBOL_WRAP_CALL(luaL_optinteger, L, nArg, def); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_checkstack, lua_State *L, int sz, const char *msg) { ++ SYMBOL_WRAP_CALL(luaL_checkstack, L, sz, msg); ++} ++SYMBOL_WRAP_DECL(void, luaL_checktype, lua_State *L, int narg, int t) { ++ SYMBOL_WRAP_CALL(luaL_checktype, L, narg, t); ++} ++SYMBOL_WRAP_DECL(void, luaL_checkany, lua_State *L, int narg) { ++ SYMBOL_WRAP_CALL(luaL_checkany, L, narg); ++} ++SYMBOL_WRAP_DECL(int, luaL_newmetatable, lua_State *L, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_newmetatable, L, tname); ++} ++SYMBOL_WRAP_DECL(void, luaL_setmetatable, lua_State *L, const char *tname) { ++ SYMBOL_WRAP_CALL(luaL_setmetatable, L, tname); ++} ++SYMBOL_WRAP_DECL(void *, luaL_testudata, lua_State *L, int ud, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_testudata, L, ud, tname); ++} ++SYMBOL_WRAP_DECL(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_checkudata, L, ud, tname); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_where, lua_State *L, int lvl) { ++ SYMBOL_WRAP_CALL(luaL_where, L, lvl); ++} ++SYMBOL_WRAP_DECL(int, luaL_error, lua_State *L, const char *fmt, ...) { ++ va_list argp; ++ va_start(argp, fmt); ++ luaL_where(L, 1); ++ lua_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ lua_concat(L, 2); ++ return lua_error(L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]) { ++ return SYMBOL_WRAP_CALL(luaL_checkoption, L, narg, def, lst); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_fileresult, lua_State *L, int stat, const char *fname) { ++ return SYMBOL_WRAP_CALL(luaL_fileresult, L, stat, fname); ++} ++SYMBOL_WRAP_DECL(int, luaL_execresult, lua_State *L, int stat) { ++ return SYMBOL_WRAP_CALL(luaL_execresult, L, stat); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, luaL_ref, lua_State *L, int t) { ++ return SYMBOL_WRAP_CALL(luaL_ref, L, t); ++} ++SYMBOL_WRAP_DECL(void, luaL_unref, lua_State *L, int t, int ref) { ++ SYMBOL_WRAP_CALL(luaL_unref, L, t, ref); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode) { ++ return SYMBOL_WRAP_CALL(luaL_loadfilex, L, filename, mode); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode) { ++ return SYMBOL_WRAP_CALL(luaL_loadbufferx, L, buff, sz, name, mode); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadstring, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(luaL_loadstring, L, s); ++} ++ ++SYMBOL_WRAP_DECL(lua_State *, luaL_newstate, void) { ++ return __luaL_newstate(); ++} ++SYMBOL_WRAP_DECL(lua_Integer, luaL_len, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(luaL_len, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_addgsub, luaL_Buffer *b, const char *s, ++ const char *p, const char *r) { ++ SYMBOL_WRAP_CALL(luaL_addgsub, b, s, p, r); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r) { ++ return SYMBOL_WRAP_CALL(luaL_gsub, L, s, p, r); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) { ++ SYMBOL_WRAP_CALL(luaL_setfuncs, L, l, nup); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) { ++ return SYMBOL_WRAP_CALL(luaL_getsubtable, L, idx, fname); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level) { ++ SYMBOL_WRAP_CALL(luaL_traceback, L, L1, msg, level); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb) { ++ SYMBOL_WRAP_CALL(luaL_requiref, L, modname, openf, glb); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_buffinit, L, B); ++} ++SYMBOL_WRAP_DECL(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) { ++ return SYMBOL_WRAP_CALL(luaL_prepbuffsize, B, sz); ++} ++SYMBOL_WRAP_DECL(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) { ++ SYMBOL_WRAP_CALL(luaL_addlstring, B, s, l); ++} ++SYMBOL_WRAP_DECL(void, luaL_addstring, luaL_Buffer *B, const char *s) { ++ SYMBOL_WRAP_CALL(luaL_addstring, B, s); ++} ++SYMBOL_WRAP_DECL(void, luaL_addvalue, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_addvalue, B); ++} ++SYMBOL_WRAP_DECL(void, luaL_pushresult, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_pushresult, B); ++} ++SYMBOL_WRAP_DECL(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) { ++ SYMBOL_WRAP_CALL(luaL_pushresultsize, B, sz); ++} ++SYMBOL_WRAP_DECL(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) { ++ return SYMBOL_WRAP_CALL(luaL_buffinitsize, L, B, sz); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_base, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_base, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_coroutine, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_coroutine, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_table, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_table, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_io, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_io, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_os, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_os, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_string, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_string, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_utf8, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_utf8, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_math, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_math, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_debug, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_debug, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_package, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_package, L); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_openlibs, lua_State *L) { ++ SYMBOL_WRAP_CALL(luaL_openlibs, L); ++} ++ ++ ++ ++ ++ ++ ++#define IMPORT_SYMBOL(name, ret, ...) \ ++ __##name = (\ ++ (*(void **) (&__##name) = symbol(#name)), \ ++ __##name == NULL ? ((ret (*) (__VA_ARGS__)) &__lite_xl_fallback_##name) : __##name\ ++ ) ++ ++void lite_xl_plugin_init(void *XL) { ++ void* (*symbol)(const char *); ++ *(void **) (&symbol) = XL; ++ IMPORT_SYMBOL(lua_newstate, lua_State *, lua_Alloc f, void *ud); ++ IMPORT_SYMBOL(lua_close, void, lua_State *L); ++ IMPORT_SYMBOL(lua_newthread, lua_State *, lua_State *L); ++ IMPORT_SYMBOL(lua_resetthread, int, lua_State *L); ++ IMPORT_SYMBOL(lua_atpanic, lua_CFunction, lua_State *L, lua_CFunction panicf); ++ IMPORT_SYMBOL(lua_version, lua_Number, lua_State *L); ++ IMPORT_SYMBOL(lua_absindex, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_gettop, int, lua_State *L); ++ IMPORT_SYMBOL(lua_settop, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_pushvalue, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rotate, void, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_copy, void, lua_State *L, int fromidx, int toidx); ++ IMPORT_SYMBOL(lua_checkstack, int, lua_State *L, int sz); ++ IMPORT_SYMBOL(lua_xmove, void, lua_State *from, lua_State *to, int n); ++ IMPORT_SYMBOL(lua_isnumber, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isstring, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_iscfunction, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isinteger, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isuserdata, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_type, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_typename, const char *, lua_State *L, int tp); ++ IMPORT_SYMBOL(lua_tonumberx, lua_Number, lua_State *L, int idx, int *isnum); ++ IMPORT_SYMBOL(lua_tointegerx, lua_Integer, lua_State *L, int idx, int *isnum); ++ IMPORT_SYMBOL(lua_toboolean, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tolstring, const char *, lua_State *L, int idx, size_t *len); ++ IMPORT_SYMBOL(lua_rawlen, lua_Unsigned, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tocfunction, lua_CFunction, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_touserdata, void *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tothread, lua_State *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_topointer, const void *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_arith, void, lua_State *L, int op); ++ IMPORT_SYMBOL(lua_rawequal, int, lua_State *L, int idx1, int idx2); ++ IMPORT_SYMBOL(lua_compare, int, lua_State *L, int idx1, int idx2, int op); ++ IMPORT_SYMBOL(lua_pushnil, void, lua_State *L); ++ IMPORT_SYMBOL(lua_pushnumber, void, lua_State *L, lua_Number n); ++ IMPORT_SYMBOL(lua_pushinteger, void, lua_State *L, lua_Integer n); ++ IMPORT_SYMBOL(lua_pushlstring, const char *, lua_State *L, const char *s, size_t l); ++ IMPORT_SYMBOL(lua_pushstring, const char *, lua_State *L, const char *s); ++ IMPORT_SYMBOL(lua_pushvfstring, const char *, lua_State *L, const char *fmt, va_list argp); ++ IMPORT_SYMBOL(lua_pushfstring, const char *, lua_State *L, const char *fmt, ...); ++ IMPORT_SYMBOL(lua_pushcclosure, void, lua_State *L, lua_CFunction fn, int n); ++ IMPORT_SYMBOL(lua_pushboolean, void, lua_State *L, int b); ++ IMPORT_SYMBOL(lua_pushlightuserdata, void, lua_State *L, void *p); ++ IMPORT_SYMBOL(lua_pushthread, int, lua_State *L); ++ IMPORT_SYMBOL(lua_getglobal, int, lua_State *L, const char *var); ++ IMPORT_SYMBOL(lua_gettable, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_getfield, int, lua_State *L, int idx, const char *k); ++ IMPORT_SYMBOL(lua_geti, int, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawget, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rawgeti, int, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawgetp, int, lua_State *L, int idx, const void *p); ++ IMPORT_SYMBOL(lua_createtable, void, lua_State *L, int narr, int nrec); ++ IMPORT_SYMBOL(lua_newuserdatauv, void *, lua_State *L, size_t sz, int nuvalue); ++ IMPORT_SYMBOL(lua_getmetatable, int, lua_State *L, int objindex); ++ IMPORT_SYMBOL(lua_getiuservalue, int, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_setglobal, void, lua_State *L, const char *var); ++ IMPORT_SYMBOL(lua_settable, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_setfield, void, lua_State *L, int idx, const char *k); ++ IMPORT_SYMBOL(lua_seti, void, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawset, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rawseti, void, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawsetp, void, lua_State *L, int idx, const void *p); ++ IMPORT_SYMBOL(lua_setmetatable, int, lua_State *L, int objindex); ++ IMPORT_SYMBOL(lua_setiuservalue, int, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_callk, void, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_pcallk, int, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_load, int, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode); ++ IMPORT_SYMBOL(lua_dump, int, lua_State *L, lua_Writer writer, void *data, int strip); ++ IMPORT_SYMBOL(lua_yieldk, int, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_resume, int, lua_State *L, lua_State *from, int narg, int *nres); ++ IMPORT_SYMBOL(lua_status, int, lua_State *L); ++ IMPORT_SYMBOL(lua_isyieldable, int, lua_State *L); ++ IMPORT_SYMBOL(lua_setwarnf, void, lua_State *L, lua_WarnFunction f, void *ud); ++ IMPORT_SYMBOL(lua_warning, void, lua_State *L, const char *msg, int tocont); ++ IMPORT_SYMBOL(lua_gc, int, lua_State *L, int what, ...); ++ IMPORT_SYMBOL(lua_error, int, lua_State *L); ++ IMPORT_SYMBOL(lua_next, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_concat, void, lua_State *L, int n); ++ IMPORT_SYMBOL(lua_len, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_stringtonumber, size_t, lua_State *L, const char *s); ++ IMPORT_SYMBOL(lua_getallocf, lua_Alloc, lua_State *L, void **ud); ++ IMPORT_SYMBOL(lua_setallocf, void, lua_State *L, lua_Alloc f, void *ud); ++ IMPORT_SYMBOL(lua_toclose, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_closeslot, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_getstack, int, lua_State *L, int level, lua_Debug *ar); ++ IMPORT_SYMBOL(lua_getinfo, int, lua_State *L, const char *what, lua_Debug *ar); ++ IMPORT_SYMBOL(lua_getlocal, const char *, lua_State *L, const lua_Debug *ar, int n); ++ IMPORT_SYMBOL(lua_setlocal, const char *, lua_State *L, const lua_Debug *ar, int n); ++ IMPORT_SYMBOL(lua_getupvalue, const char *, lua_State *L, int funcindex, int n); ++ IMPORT_SYMBOL(lua_setupvalue, const char *, lua_State *L, int funcindex, int n); ++ IMPORT_SYMBOL(lua_upvalueid, void *, lua_State *L, int fidx, int n); ++ IMPORT_SYMBOL(lua_upvaluejoin, void, lua_State *L, int fidx1, int n1, int fidx2, int n2); ++ IMPORT_SYMBOL(lua_sethook, void, lua_State *L, lua_Hook func, int mask, int count); ++ IMPORT_SYMBOL(lua_gethook, lua_Hook, lua_State *L); ++ IMPORT_SYMBOL(lua_gethookmask, int, lua_State *L); ++ IMPORT_SYMBOL(lua_gethookcount, int, lua_State *L); ++ IMPORT_SYMBOL(lua_setcstacklimit, int, lua_State *L, unsigned int limit); ++ IMPORT_SYMBOL(luaL_checkversion_, void, lua_State *L, lua_Number ver, size_t sz); ++ IMPORT_SYMBOL(luaL_getmetafield, int, lua_State *L, int obj, const char *e); ++ IMPORT_SYMBOL(luaL_callmeta, int, lua_State *L, int obj, const char *e); ++ IMPORT_SYMBOL(luaL_tolstring, const char *, lua_State *L, int idx, size_t *len); ++ IMPORT_SYMBOL(luaL_argerror, int, lua_State *L, int numarg, const char *extramsg); ++ IMPORT_SYMBOL(luaL_typeerror, int, lua_State *L, int arg, const char *tname); ++ IMPORT_SYMBOL(luaL_checklstring, const char *, lua_State *L, int numArg, size_t *l); ++ IMPORT_SYMBOL(luaL_optlstring, const char *, lua_State *L, int numArg, const char *def, size_t *l); ++ IMPORT_SYMBOL(luaL_checknumber, lua_Number, lua_State *L, int numArg); ++ IMPORT_SYMBOL(luaL_optnumber, lua_Number, lua_State *L, int nArg, lua_Number def); ++ IMPORT_SYMBOL(luaL_checkinteger, lua_Integer, lua_State *L, int numArg); ++ IMPORT_SYMBOL(luaL_optinteger, lua_Integer, lua_State *L, int nArg, lua_Integer def); ++ IMPORT_SYMBOL(luaL_checkstack, void, lua_State *L, int sz, const char *msg); ++ IMPORT_SYMBOL(luaL_checktype, void, lua_State *L, int narg, int t); ++ IMPORT_SYMBOL(luaL_checkany, void, lua_State *L, int narg); ++ IMPORT_SYMBOL(luaL_newmetatable, int, lua_State *L, const char *tname); ++ IMPORT_SYMBOL(luaL_setmetatable, void, lua_State *L, const char *tname); ++ IMPORT_SYMBOL(luaL_testudata, void *, lua_State *L, int ud, const char *tname); ++ IMPORT_SYMBOL(luaL_checkudata, void *, lua_State *L, int ud, const char *tname); ++ IMPORT_SYMBOL(luaL_where, void, lua_State *L, int lvl); ++ IMPORT_SYMBOL(luaL_error, int, lua_State *L, const char *fmt, ...); ++ IMPORT_SYMBOL(luaL_checkoption, int, lua_State *L, int narg, const char *def, const char *const lst[]); ++ IMPORT_SYMBOL(luaL_fileresult, int, lua_State *L, int stat, const char *fname); ++ IMPORT_SYMBOL(luaL_execresult, int, lua_State *L, int stat); ++ IMPORT_SYMBOL(luaL_ref, int, lua_State *L, int t); ++ IMPORT_SYMBOL(luaL_unref, void, lua_State *L, int t, int ref); ++ IMPORT_SYMBOL(luaL_loadfilex, int, lua_State *L, const char *filename, const char *mode); ++ IMPORT_SYMBOL(luaL_loadbufferx, int, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); ++ IMPORT_SYMBOL(luaL_loadstring, int, lua_State *L, const char *s); ++ IMPORT_SYMBOL(luaL_newstate, lua_State *, void); ++ IMPORT_SYMBOL(luaL_len, lua_Integer, lua_State *L, int idx); ++ IMPORT_SYMBOL(luaL_addgsub, void, luaL_Buffer *b, const char *s, const char *p, const char *r); ++ IMPORT_SYMBOL(luaL_gsub, const char *, lua_State *L, const char *s, const char *p, const char *r); ++ IMPORT_SYMBOL(luaL_setfuncs, void, lua_State *L, const luaL_Reg *l, int nup); ++ IMPORT_SYMBOL(luaL_getsubtable, int, lua_State *L, int idx, const char *fname); ++ IMPORT_SYMBOL(luaL_traceback, void, lua_State *L, lua_State *L1, const char *msg, int level); ++ IMPORT_SYMBOL(luaL_requiref, void, lua_State *L, const char *modname, lua_CFunction openf, int glb); ++ IMPORT_SYMBOL(luaL_buffinit, void, lua_State *L, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_prepbuffsize, char *, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaL_addlstring, void, luaL_Buffer *B, const char *s, size_t l); ++ IMPORT_SYMBOL(luaL_addstring, void, luaL_Buffer *B, const char *s); ++ IMPORT_SYMBOL(luaL_addvalue, void, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_pushresult, void, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_pushresultsize, void, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaL_buffinitsize, char *, lua_State *L, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaopen_base, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_coroutine, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_table, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_io, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_os, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_string, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_utf8, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_math, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_debug, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_package, int, lua_State *L); ++ IMPORT_SYMBOL(luaL_openlibs, void, lua_State* L); ++} ++ ++#undef IMPORT_SYMBOL ++#undef IMPORT_SYMBOL_OPT ++ ++#else /* LITE_XL_PLUGIN_ENTRYPOINT */ ++ ++void lite_xl_plugin_init(void *XL); ++ ++#endif /* LITE_XL_PLUGIN_ENTRYPOINT */ ++ ++#undef LITE_XL_API ++#undef SYMBOL_WRAP_DECL ++#undef SYMBOL_WRAP_CALL ++#undef SYMBOL_WRAP_CALL_FB ++#undef SYMBOL_DECLARE ++#undef SYMBOL_DECLARE_VARARG ++#undef UNUSED ++#undef CONCAT ++#undef CONCAT1 ++#undef CONCAT2 ++#undef FE_1 ++#undef FE_2 ++#undef FE_3 ++#undef FE_4 ++#undef FE_5 ++#undef FE_6 ++#undef FE_7 ++#undef FE_8 ++#undef FOR_EACH_NARG ++#undef FOR_EACH_NARG_ ++#undef FOR_EACH_ARG_N ++#undef FOR_EACH_RSEQ_N ++#undef FOR_EACH_ ++#undef FOR_EACH ++ ++#endif /* LITE_XL_PLUGIN_API */ ++ ++/****************************************************************************** ++* Copyright (C) 1994-2023 Lua.org, PUC-Rio; Lite XL contributors. ++* ++* Permission is hereby granted, free of charge, to any person obtaining ++* a copy of this software and associated documentation files (the ++* "Software"), to deal in the Software without restriction, including ++* without limitation the rights to use, copy, modify, merge, publish, ++* distribute, sublicense, and/or sell copies of the Software, and to ++* permit persons to whom the Software is furnished to do so, subject to ++* the following conditions: ++* ++* The above copyright notice and this permission notice shall be ++* included in all copies or substantial portions of the Software. ++* ++* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ++* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ++* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ++* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ++* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ++* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ++* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++******************************************************************************/ +\ No newline at end of file +diff --git a/resources/lite_xl_plugin_api.h b/resources/lite_xl_plugin_api.h +deleted file mode 100644 +index 8bf74054..00000000 +--- a/resources/lite_xl_plugin_api.h ++++ /dev/null +@@ -1,1124 +0,0 @@ +-#ifndef LITE_XL_PLUGIN_API +-#define LITE_XL_PLUGIN_API +-/** +-The lite_xl plugin API is quite simple. Any shared library can be a plugin file, so long +-as it has an entrypoint that looks like the following, where xxxxx is the plugin name: +- +-#define LITE_XL_PLUGIN_ENTRYPOINT +-#include "lite_xl_plugin_api.h" +-int luaopen_lite_xl_xxxxx(lua_State* L, void* XL) { +- lite_xl_plugin_init(XL); +- ... +- return 1; +-} +- +-NOTE: `#define LITE_XL_PLUGIN_ENTRYPOINT` needs to be defined only on the +-source file where the lite_xl_plugin_init() initialization function is called. +- +-In linux, to compile this file, you'd do: 'gcc -o xxxxx.so -shared xxxxx.c'. Simple! +-Due to the way the API is structured, you *should not* link or include lua libraries. +-This file was automatically generated. DO NOT MODIFY DIRECTLY. +- +-UNLESS you're us, and you had to modify this file manually to get it ready for 2.1. +- +-Go figure. +- +-**/ +- +- +-#include +-#include // for BUFSIZ? this is kinda weird +-#include +- +-#define SYMBOL_WRAP_DECL(ret, name, ...) \ +- ret name(__VA_ARGS__) +- +-#define SYMBOL_WRAP_CALL(name, ...) \ +- return __##name(__VA_ARGS__) +- +-#define SYMBOL_WRAP_CALL_FB(name, ...) \ +- return __lite_xl_fallback_##name(__VA_ARGS__) +- +-#ifdef LITE_XL_PLUGIN_ENTRYPOINT +- #define SYMBOL_DECLARE(ret, name, ...) \ +- static ret (*__##name) (__VA_ARGS__); \ +- SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); \ +- static ret __lite_xl_fallback_##name(__VA_ARGS__) { \ +- fputs("warning: " #name " is a stub", stderr); \ +- exit(1); \ +- } +-#else +- #define SYMBOL_DECLARE(ret, name, ...) \ +- SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); +-#endif +- +-/** luaconf.h **/ +- +-#ifndef lconfig_h +-#define lconfig_h +-#include +-#include +-#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__) +-#define LUA_ANSI +-#endif +-#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) +-#define LUA_WIN +-#endif +-#if defined(LUA_WIN) +-#define LUA_DL_DLL +-#define LUA_USE_AFORMAT +-#endif +-#if defined(LUA_USE_LINUX) +-#define LUA_USE_POSIX +-#define LUA_USE_DLOPEN +-#define LUA_USE_READLINE +-#define LUA_USE_STRTODHEX +-#define LUA_USE_AFORMAT +-#define LUA_USE_LONGLONG +-#endif +-#if defined(LUA_USE_MACOSX) +-#define LUA_USE_POSIX +-#define LUA_USE_DLOPEN +-#define LUA_USE_READLINE +-#define LUA_USE_STRTODHEX +-#define LUA_USE_AFORMAT +-#define LUA_USE_LONGLONG +-#endif +-#if defined(LUA_USE_POSIX) +-#define LUA_USE_MKSTEMP +-#define LUA_USE_ISATTY +-#define LUA_USE_POPEN +-#define LUA_USE_ULONGJMP +-#define LUA_USE_GMTIME_R +-#endif +-#if defined(_WIN32) +-#define LUA_LDIR "!\\lua\\" +-#define LUA_CDIR "!\\" +-#define LUA_PATH_DEFAULT LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua" +-#define LUA_CPATH_DEFAULT LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll" +-#else +-#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" +-#define LUA_ROOT "/usr/local/" +-#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR +-#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR +-#define LUA_PATH_DEFAULT LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua" +-#define LUA_CPATH_DEFAULT LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" +-#endif +-#if defined(_WIN32) +-#define LUA_DIRSEP "\\" +-#else +-#define LUA_DIRSEP "/" +-#endif +-#define LUA_ENV "_ENV" +-#if defined(LUA_BUILD_AS_DLL) +-#if defined(LUA_CORE) || defined(LUA_LIB) +-#define LUA_API __declspec(dllexport) +-#else +-#define LUA_API __declspec(dllimport) +-#endif +-#else +-#define LUA_API extern +-#endif +-#define LUALIB_API LUA_API +-#define LUAMOD_API LUALIB_API +-#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && defined(__ELF__) +-#define LUAI_FUNC __attribute__((visibility("hidden"))) extern +-#define LUAI_DDEC LUAI_FUNC +-#define LUAI_DDEF +-#else +-#define LUAI_FUNC extern +-#define LUAI_DDEC extern +-#define LUAI_DDEF +-#endif +-#define LUA_QL(x) "'" x "'" +-#define LUA_QS LUA_QL("%s") +-#define LUA_IDSIZE 60 +-#if defined(LUA_LIB) || defined(lua_c) +-#include +-#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +-#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) +-#endif +-#define luai_writestringerror(s,p) (fprintf(stderr, (s), (p)), fflush(stderr)) +-#define LUAI_MAXSHORTLEN 40 +-#if defined(LUA_COMPAT_ALL) +-#define LUA_COMPAT_UNPACK +-#define LUA_COMPAT_LOADERS +-#define lua_cpcall(L,f,u) (lua_pushcfunction(L, (f)), lua_pushlightuserdata(L,(u)), lua_pcall(L,1,0,0)) +-#define LUA_COMPAT_LOG10 +-#define LUA_COMPAT_LOADSTRING +-#define LUA_COMPAT_MAXN +-#define lua_strlen(L,i) lua_rawlen(L, (i)) +-#define lua_objlen(L,i) lua_rawlen(L, (i)) +-#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +-#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) +-#define LUA_COMPAT_MODULE +-#endif +-#if INT_MAX-20 < 32760 +-#define LUAI_BITSINT 16 +-#elif INT_MAX > 2147483640L +-#define LUAI_BITSINT 32 +-#else +-#error "you must define LUA_BITSINT with number of bits in an integer" +-#endif +-#if LUAI_BITSINT >= 32 +-#define LUA_INT32 int +-#define LUAI_UMEM size_t +-#define LUAI_MEM ptrdiff_t +-#else +-#define LUA_INT32 long +-#define LUAI_UMEM unsigned long +-#define LUAI_MEM long +-#endif +-#if LUAI_BITSINT >= 32 +-#define LUAI_MAXSTACK 1000000 +-#else +-#define LUAI_MAXSTACK 15000 +-#endif +-#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) +-#define LUAL_BUFFERSIZE BUFSIZ +-#define LUA_NUMBER_DOUBLE +-#define LUA_NUMBER double +-#define LUAI_UACNUMBER double +-#define LUA_NUMBER_SCAN "%lf" +-#define LUA_NUMBER_FMT "%.14g" +-#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) +-#define LUAI_MAXNUMBER2STR 32 +-#define l_mathop(x) (x) +-#define lua_str2number(s,p) strtod((s), (p)) +-#if defined(LUA_USE_STRTODHEX) +-#define lua_strx2number(s,p) strtod((s), (p)) +-#endif +-#if defined(lobject_c) || defined(lvm_c) +-#include +-#define luai_nummod(L,a,b) ((a) - l_mathop(floor)((a)/(b))*(b)) +-#define luai_numpow(L,a,b) (l_mathop(pow)(a,b)) +-#endif +-#if defined(LUA_CORE) +-#define luai_numadd(L,a,b) ((a)+(b)) +-#define luai_numsub(L,a,b) ((a)-(b)) +-#define luai_nummul(L,a,b) ((a)*(b)) +-#define luai_numdiv(L,a,b) ((a)/(b)) +-#define luai_numunm(L,a) (-(a)) +-#define luai_numeq(a,b) ((a)==(b)) +-#define luai_numlt(L,a,b) ((a)<(b)) +-#define luai_numle(L,a,b) ((a)<=(b)) +-#define luai_numisnan(L,a) (!luai_numeq((a), (a))) +-#endif +-#define LUA_INTEGER ptrdiff_t +-#define LUA_KCONTEXT ptrdiff_t +-#define LUA_UNSIGNED unsigned LUA_INT32 +-#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) +-#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) +-#define LUA_MSASMTRICK +-#define LUA_IEEEENDIAN 0 +-#define LUA_NANTRICK +-#elif defined(__i386__) || defined(__i386) || defined(__X86__) +-#define LUA_IEEE754TRICK +-#define LUA_IEEELL +-#define LUA_IEEEENDIAN 0 +-#define LUA_NANTRICK +-#elif defined(__x86_64) +-#define LUA_IEEE754TRICK +-#define LUA_IEEEENDIAN 0 +-#elif defined(__POWERPC__) || defined(__ppc__) +-#define LUA_IEEE754TRICK +-#define LUA_IEEEENDIAN 1 +-#else +-#define LUA_IEEE754TRICK +-#endif +-#endif +-#endif +- +-/** lua.h **/ +- +-typedef struct lua_State lua_State; +-typedef int (*lua_CFunction) (lua_State *L); +-typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); +-typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); +-typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); +-typedef LUA_KCONTEXT lua_KContext; +-typedef LUA_NUMBER lua_Number; +-typedef LUA_INTEGER lua_Integer; +-typedef LUA_UNSIGNED lua_Unsigned; +-typedef struct lua_Debug lua_Debug; +-typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); +-typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); +-struct lua_Debug { +- int event; +- const char *name; +- const char *namewhat; +- const char *what; +- const char *source; +- int currentline; +- int linedefined; +- int lastlinedefined; +- unsigned char nups; +- unsigned char nparams; +- char isvararg; +- char istailcall; +- char short_src[LUA_IDSIZE]; +- struct CallInfo *i_ci; +-}; +- +-SYMBOL_DECLARE(lua_State *, lua_newstate, lua_Alloc f, void *ud) +-SYMBOL_DECLARE(void, lua_close, lua_State *L) +-SYMBOL_DECLARE(lua_State *, lua_newthread, lua_State *L) +-SYMBOL_DECLARE(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) +-SYMBOL_DECLARE(const lua_Number *, lua_version, lua_State *L) +-SYMBOL_DECLARE(int, lua_absindex, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_gettop, lua_State *L) +-SYMBOL_DECLARE(void, lua_settop, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_pushvalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_copy, lua_State *L, int fromidx, int toidx) +-SYMBOL_DECLARE(int, lua_checkstack, lua_State *L, int sz) +-SYMBOL_DECLARE(void, lua_xmove, lua_State *from, lua_State *to, int n) +-SYMBOL_DECLARE(int, lua_isnumber, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_isstring, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_iscfunction, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_isuserdata, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_type, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, lua_typename, lua_State *L, int tp) +-SYMBOL_DECLARE(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(lua_Unsigned, lua_tounsignedx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(int, lua_toboolean, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) +-SYMBOL_DECLARE(size_t, lua_rawlen, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_CFunction, lua_tocfunction, lua_State *L, int idx) +-SYMBOL_DECLARE(void *, lua_touserdata, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_State *, lua_tothread, lua_State *L, int idx) +-SYMBOL_DECLARE(const void *, lua_topointer, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_arith, lua_State *L, int op) +-SYMBOL_DECLARE(int, lua_rawequal, lua_State *L, int idx1, int idx2) +-SYMBOL_DECLARE(int, lua_compare, lua_State *L, int idx1, int idx2, int op) +-SYMBOL_DECLARE(void, lua_pushnil, lua_State *L) +-SYMBOL_DECLARE(void, lua_pushnumber, lua_State *L, lua_Number n) +-SYMBOL_DECLARE(void, lua_pushinteger, lua_State *L, lua_Integer n) +-SYMBOL_DECLARE(void, lua_pushunsigned, lua_State *L, lua_Unsigned n) +-SYMBOL_DECLARE(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l) +-SYMBOL_DECLARE(const char *, lua_pushstring, lua_State *L, const char *s) +-SYMBOL_DECLARE(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp) +-SYMBOL_DECLARE(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...) +-SYMBOL_DECLARE(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) +-SYMBOL_DECLARE(void, lua_pushboolean, lua_State *L, int b) +-SYMBOL_DECLARE(void, lua_pushlightuserdata, lua_State *L, void *p) +-SYMBOL_DECLARE(int, lua_pushthread, lua_State *L) +-SYMBOL_DECLARE(void, lua_getglobal, lua_State *L, const char *var) +-SYMBOL_DECLARE(void, lua_gettable, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_getfield, lua_State *L, int idx, const char *k) +-SYMBOL_DECLARE(void, lua_rawget, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_rawgeti, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_rawgetp, lua_State *L, int idx, const void *p) +-SYMBOL_DECLARE(void, lua_createtable, lua_State *L, int narr, int nrec) +-SYMBOL_DECLARE(void *, lua_newuserdata, lua_State *L, size_t sz) +-SYMBOL_DECLARE(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) +-SYMBOL_DECLARE(int, lua_getmetatable, lua_State *L, int objindex) +-SYMBOL_DECLARE(void, lua_getuservalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_getiuservalue, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_setglobal, lua_State *L, const char *var) +-SYMBOL_DECLARE(void, lua_settable, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_setfield, lua_State *L, int idx, const char *k) +-SYMBOL_DECLARE(void, lua_rawset, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_rawseti, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_rawsetp, lua_State *L, int idx, const void *p) +-SYMBOL_DECLARE(int, lua_setmetatable, lua_State *L, int objindex) +-SYMBOL_DECLARE(void, lua_setuservalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_setiuservalue, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_getctx, lua_State *L, int *ctx) +-SYMBOL_DECLARE(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode) +-SYMBOL_DECLARE(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) +-SYMBOL_DECLARE(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_resume, lua_State *L, lua_State *from, int narg) +-SYMBOL_DECLARE(int, lua_status, lua_State *L) +-SYMBOL_DECLARE(int, lua_gc, lua_State *L, int what, int data) +-SYMBOL_DECLARE(int, lua_error, lua_State *L) +-SYMBOL_DECLARE(int, lua_next, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_concat, lua_State *L, int n) +-SYMBOL_DECLARE(void, lua_len, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_Alloc, lua_getallocf, lua_State *L, void **ud) +-SYMBOL_DECLARE(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud) +-SYMBOL_DECLARE(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) +-SYMBOL_DECLARE(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) +-SYMBOL_DECLARE(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) +-SYMBOL_DECLARE(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) +-SYMBOL_DECLARE(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) +-SYMBOL_DECLARE(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) +-SYMBOL_DECLARE(void *, lua_upvalueid, lua_State *L, int fidx, int n) +-SYMBOL_DECLARE(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2) +-SYMBOL_DECLARE(int, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) +-SYMBOL_DECLARE(lua_Hook, lua_gethook, lua_State *L) +-SYMBOL_DECLARE(int, lua_gethookmask, lua_State *L) +-SYMBOL_DECLARE(int, lua_gethookcount, lua_State *L) +- +-#define lua_h +-#define LUA_VERSION_MAJOR "5" +-#define LUA_VERSION_MINOR "4" +-#define LUA_VERSION_NUM 504 +-#define LUA_VERSION_RELEASE "4" +-#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +-#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE +-#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2015 Lua.org, PUC-Rio" +-#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" +-#define LUA_SIGNATURE "\033Lua" +-#define LUA_MULTRET (-1) +-#define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX +-#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) +-#define LUA_OK 0 +-#define LUA_YIELD 1 +-#define LUA_ERRRUN 2 +-#define LUA_ERRSYNTAX 3 +-#define LUA_ERRMEM 4 +-#define LUA_ERRGCMM 5 +-#define LUA_ERRERR 6 +-#define LUA_TNONE (-1) +-#define LUA_TNIL 0 +-#define LUA_TBOOLEAN 1 +-#define LUA_TLIGHTUSERDATA 2 +-#define LUA_TNUMBER 3 +-#define LUA_TSTRING 4 +-#define LUA_TTABLE 5 +-#define LUA_TFUNCTION 6 +-#define LUA_TUSERDATA 7 +-#define LUA_TTHREAD 8 +-#define LUA_NUMTAGS 9 +-#define LUA_MINSTACK 20 +-#define LUA_RIDX_MAINTHREAD 1 +-#define LUA_RIDX_GLOBALS 2 +-#define LUA_RIDX_LAST LUA_RIDX_GLOBALS +-#define LUA_OPADD 0 +-#define LUA_OPSUB 1 +-#define LUA_OPMUL 2 +-#define LUA_OPDIV 3 +-#define LUA_OPMOD 4 +-#define LUA_OPPOW 5 +-#define LUA_OPUNM 6 +-#define LUA_OPEQ 0 +-#define LUA_OPLT 1 +-#define LUA_OPLE 2 +-#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) +-#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) +-#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) +-#define LUA_GCSTOP 0 +-#define LUA_GCRESTART 1 +-#define LUA_GCCOLLECT 2 +-#define LUA_GCCOUNT 3 +-#define LUA_GCCOUNTB 4 +-#define LUA_GCSTEP 5 +-#define LUA_GCSETPAUSE 6 +-#define LUA_GCSETSTEPMUL 7 +-#define LUA_GCSETMAJORINC 8 +-#define LUA_GCISRUNNING 9 +-#define LUA_GCGEN 10 +-#define LUA_GCINC 11 +-#define lua_tonumber(L,i) lua_tonumberx(L,i,NULL) +-#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL) +-#define lua_tounsigned(L,i) lua_tounsignedx(L,i,NULL) +-#define lua_pop(L,n) lua_settop(L, -(n)-1) +-#define lua_newtable(L) lua_createtable(L, 0, 0) +-#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) +-#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) +-#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) +-#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) +-#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +-#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) +-#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) +-#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) +-#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) +-#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) +-#define lua_pushliteral(L, s) lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) +-#define lua_pushglobaltable(L) lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS) +-#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) +-#define lua_insert(L,idx) lua_rotate(L, (idx), 1) +-#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) +-#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) +-#define LUA_HOOKCALL 0 +-#define LUA_HOOKRET 1 +-#define LUA_HOOKLINE 2 +-#define LUA_HOOKCOUNT 3 +-#define LUA_HOOKTAILCALL 4 +-#define LUA_MASKCALL (1 << LUA_HOOKCALL) +-#define LUA_MASKRET (1 << LUA_HOOKRET) +-#define LUA_MASKLINE (1 << LUA_HOOKLINE) +-#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) +- +-/** lauxlib.h **/ +- +-typedef struct luaL_Reg { +- const char *name; +- lua_CFunction func; +-} luaL_Reg; +-typedef struct luaL_Buffer { +- char *b; +- size_t size; +- size_t n; +- lua_State *L; +- char initb[LUAL_BUFFERSIZE]; +-} luaL_Buffer; +-typedef struct luaL_Stream { +- FILE *f; +- lua_CFunction closef; +-} luaL_Stream; +- +-SYMBOL_DECLARE(void, luaL_checkversion_, lua_State *L, lua_Number ver) +-SYMBOL_DECLARE(int, luaL_getmetafield, lua_State *L, int obj, const char *e) +-SYMBOL_DECLARE(int, luaL_callmeta, lua_State *L, int obj, const char *e) +-SYMBOL_DECLARE(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) +-SYMBOL_DECLARE(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg) +-SYMBOL_DECLARE(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l) +-SYMBOL_DECLARE(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l) +-SYMBOL_DECLARE(lua_Number, luaL_checknumber, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def) +-SYMBOL_DECLARE(lua_Integer, luaL_checkinteger, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def) +-SYMBOL_DECLARE(lua_Unsigned, luaL_checkunsigned, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Unsigned, luaL_optunsigned, lua_State *L, int numArg, lua_Unsigned def) +-SYMBOL_DECLARE(void, luaL_checkstack, lua_State *L, int sz, const char *msg) +-SYMBOL_DECLARE(void, luaL_checktype, lua_State *L, int narg, int t) +-SYMBOL_DECLARE(void, luaL_checkany, lua_State *L, int narg) +-SYMBOL_DECLARE(int, luaL_newmetatable, lua_State *L, const char *tname) +-SYMBOL_DECLARE(void, luaL_setmetatable, lua_State *L, const char *tname) +-SYMBOL_DECLARE(void *, luaL_testudata, lua_State *L, int ud, const char *tname) +-SYMBOL_DECLARE(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) +-SYMBOL_DECLARE(void, luaL_where, lua_State *L, int lvl) +-SYMBOL_DECLARE(int, luaL_error, lua_State *L, const char *fmt, ...) +-SYMBOL_DECLARE(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]) +-SYMBOL_DECLARE(int, luaL_fileresult, lua_State *L, int stat, const char *fname) +-SYMBOL_DECLARE(int, luaL_execresult, lua_State *L, int stat) +-SYMBOL_DECLARE(int, luaL_ref, lua_State *L, int t) +-SYMBOL_DECLARE(void, luaL_unref, lua_State *L, int t, int ref) +-SYMBOL_DECLARE(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode) +-SYMBOL_DECLARE(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode) +-SYMBOL_DECLARE(int, luaL_loadstring, lua_State *L, const char *s) +-SYMBOL_DECLARE(lua_State *, luaL_newstate, void) +-SYMBOL_DECLARE(int, luaL_len, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r) +-SYMBOL_DECLARE(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) +-SYMBOL_DECLARE(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) +-SYMBOL_DECLARE(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level) +-SYMBOL_DECLARE(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb) +-SYMBOL_DECLARE(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) +-SYMBOL_DECLARE(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) +-SYMBOL_DECLARE(void, luaL_addstring, luaL_Buffer *B, const char *s) +-SYMBOL_DECLARE(void, luaL_addvalue, luaL_Buffer *B) +-SYMBOL_DECLARE(void, luaL_pushresult, luaL_Buffer *B) +-SYMBOL_DECLARE(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(void, luaL_openlibs, lua_State *L) +- +-#define lauxlib_h +-#define LUA_ERRFILE (LUA_ERRERR+1) +-#define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM) +-#define LUA_NOREF (-2) +-#define LUA_REFNIL (-1) +-#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) +-#define luaL_newlibtable(L,l) lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) +-#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) +-#define luaL_argcheck(L, cond,numarg,extramsg) ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) +-#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +-#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) +-#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) +-#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) +-#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +-#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) +-#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) +-#define luaL_dofile(L, fn) (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) +-#define luaL_dostring(L, s) (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) +-#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) +-#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) +-#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) +-#define luaL_addchar(B,c) ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), ((B)->b[(B)->n++] = (c))) +-#define luaL_addsize(B,s) ((B)->n += (s)) +-#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) +-#define LUA_FILEHANDLE "FILE*" +- +-#ifdef LITE_XL_PLUGIN_ENTRYPOINT +- +-SYMBOL_WRAP_DECL(lua_State *, lua_newstate, lua_Alloc f, void *ud){ +- SYMBOL_WRAP_CALL(lua_newstate, f, ud); +-} +-SYMBOL_WRAP_DECL(void, lua_close, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_close, L); +-} +-SYMBOL_WRAP_DECL(lua_State *, lua_newthread, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_newthread, L); +-} +-SYMBOL_WRAP_DECL(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf){ +- SYMBOL_WRAP_CALL(lua_atpanic, L, panicf); +-} +-SYMBOL_WRAP_DECL(const lua_Number *, lua_version, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_version, L); +-} +-SYMBOL_WRAP_DECL(int, lua_absindex, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_absindex, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_gettop, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gettop, L); +-} +-SYMBOL_WRAP_DECL(void, lua_settop, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_settop, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_pushvalue, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_pushvalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_copy, lua_State *L, int fromidx, int toidx){ +- SYMBOL_WRAP_CALL(lua_copy, L, fromidx, toidx); +-} +-SYMBOL_WRAP_DECL(int, lua_checkstack, lua_State *L, int sz){ +- SYMBOL_WRAP_CALL(lua_checkstack, L, sz); +-} +-SYMBOL_WRAP_DECL(void, lua_xmove, lua_State *from, lua_State *to, int n){ +- SYMBOL_WRAP_CALL(lua_xmove, from, to, n); +-} +-SYMBOL_WRAP_DECL(int, lua_isnumber, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isnumber, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_isstring, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isstring, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_iscfunction, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_iscfunction, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_isuserdata, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isuserdata, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_type, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_type, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, lua_typename, lua_State *L, int tp){ +- SYMBOL_WRAP_CALL(lua_typename, L, tp); +-} +-SYMBOL_WRAP_DECL(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tonumberx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tointegerx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, lua_tounsignedx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tounsignedx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(int, lua_toboolean, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_toboolean, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, lua_tolstring, lua_State *L, int idx, size_t *len){ +- SYMBOL_WRAP_CALL(lua_tolstring, L, idx, len); +-} +-SYMBOL_WRAP_DECL(size_t, lua_rawlen, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawlen, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_CFunction, lua_tocfunction, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_tocfunction, L, idx); +-} +-SYMBOL_WRAP_DECL(void *, lua_touserdata, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_touserdata, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_State *, lua_tothread, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_tothread, L, idx); +-} +-SYMBOL_WRAP_DECL(const void *, lua_topointer, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_topointer, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_arith, lua_State *L, int op){ +- SYMBOL_WRAP_CALL(lua_arith, L, op); +-} +-SYMBOL_WRAP_DECL(int, lua_rawequal, lua_State *L, int idx1, int idx2){ +- SYMBOL_WRAP_CALL(lua_rawequal, L, idx1, idx2); +-} +-SYMBOL_WRAP_DECL(int, lua_compare, lua_State *L, int idx1, int idx2, int op){ +- SYMBOL_WRAP_CALL(lua_compare, L, idx1, idx2, op); +-} +-SYMBOL_WRAP_DECL(void, lua_pushnil, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_pushnil, L); +-} +-SYMBOL_WRAP_DECL(void, lua_pushnumber, lua_State *L, lua_Number n){ +- SYMBOL_WRAP_CALL(lua_pushnumber, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushinteger, lua_State *L, lua_Integer n){ +- SYMBOL_WRAP_CALL(lua_pushinteger, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushunsigned, lua_State *L, lua_Unsigned n){ +- SYMBOL_WRAP_CALL(lua_pushunsigned, L, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l){ +- SYMBOL_WRAP_CALL(lua_pushlstring, L, s, l); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushstring, lua_State *L, const char *s){ +- SYMBOL_WRAP_CALL(lua_pushstring, L, s); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp){ +- SYMBOL_WRAP_CALL(lua_pushvfstring, L, fmt, argp); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...){ +- SYMBOL_WRAP_CALL(lua_pushfstring, L, fmt); +-} +-SYMBOL_WRAP_DECL(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n){ +- SYMBOL_WRAP_CALL(lua_pushcclosure, L, fn, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushboolean, lua_State *L, int b){ +- SYMBOL_WRAP_CALL(lua_pushboolean, L, b); +-} +-SYMBOL_WRAP_DECL(void, lua_pushlightuserdata, lua_State *L, void *p){ +- SYMBOL_WRAP_CALL(lua_pushlightuserdata, L, p); +-} +-SYMBOL_WRAP_DECL(int, lua_pushthread, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_pushthread, L); +-} +-SYMBOL_WRAP_DECL(void, lua_getglobal, lua_State *L, const char *var){ +- SYMBOL_WRAP_CALL(lua_getglobal, L, var); +-} +-SYMBOL_WRAP_DECL(void, lua_gettable, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_gettable, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_getfield, lua_State *L, int idx, const char *k){ +- SYMBOL_WRAP_CALL(lua_getfield, L, idx, k); +-} +-SYMBOL_WRAP_DECL(void, lua_rawget, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawget, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_rawgeti, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_rawgeti, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_rawgetp, lua_State *L, int idx, const void *p){ +- SYMBOL_WRAP_CALL(lua_rawgetp, L, idx, p); +-} +-SYMBOL_WRAP_DECL(void, lua_createtable, lua_State *L, int narr, int nrec){ +- SYMBOL_WRAP_CALL(lua_createtable, L, narr, nrec); +-} +-SYMBOL_WRAP_DECL(void *, lua_newuserdata, lua_State *L, size_t sz){ +- if (__lua_newuserdatauv != NULL) { +- return lua_newuserdatauv(L, sz, 1); +- } else if (__lua_newuserdata != NULL) { +- SYMBOL_WRAP_CALL(lua_newuserdata, L, sz); +- } +- SYMBOL_WRAP_CALL_FB(lua_newuserdata, L, sz); +-} +-SYMBOL_WRAP_DECL(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue){ +- SYMBOL_WRAP_CALL(lua_newuserdatauv, L, sz, nuvalue); +-} +-SYMBOL_WRAP_DECL(int, lua_getmetatable, lua_State *L, int objindex){ +- SYMBOL_WRAP_CALL(lua_getmetatable, L, objindex); +-} +-SYMBOL_WRAP_DECL(void, lua_getuservalue, lua_State *L, int idx){ +- if (__lua_getiuservalue != NULL) { +- return lua_getiuservalue(L, idx, 1); +- } else if (__lua_getuservalue != NULL) { +- SYMBOL_WRAP_CALL(lua_getuservalue, L, idx); +- } +- SYMBOL_WRAP_CALL_FB(lua_getuservalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_getiuservalue, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_getiuservalue, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_setglobal, lua_State *L, const char *var){ +- SYMBOL_WRAP_CALL(lua_setglobal, L, var); +-} +-SYMBOL_WRAP_DECL(void, lua_settable, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_settable, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_setfield, lua_State *L, int idx, const char *k){ +- SYMBOL_WRAP_CALL(lua_setfield, L, idx, k); +-} +-SYMBOL_WRAP_DECL(void, lua_rawset, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawset, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_rawseti, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_rawseti, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_rawsetp, lua_State *L, int idx, const void *p){ +- SYMBOL_WRAP_CALL(lua_rawsetp, L, idx, p); +-} +-SYMBOL_WRAP_DECL(int, lua_setmetatable, lua_State *L, int objindex){ +- SYMBOL_WRAP_CALL(lua_setmetatable, L, objindex); +-} +-SYMBOL_WRAP_DECL(void, lua_setuservalue, lua_State *L, int idx){ +- if (__lua_setiuservalue != NULL) { +- return lua_setiuservalue(L, idx, 1); +- } else if (__lua_setuservalue != NULL) { +- SYMBOL_WRAP_CALL(lua_setuservalue, L, idx); +- } +- SYMBOL_WRAP_CALL_FB(lua_setuservalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_setiuservalue, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_setiuservalue, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_callk, L, nargs, nresults, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_getctx, lua_State *L, int *ctx){ +- SYMBOL_WRAP_CALL(lua_getctx, L, ctx); +-} +-SYMBOL_WRAP_DECL(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_pcallk, L, nargs, nresults, errfunc, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode){ +- SYMBOL_WRAP_CALL(lua_load, L, reader, dt, chunkname, mode); +-} +-SYMBOL_WRAP_DECL(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip){ +- SYMBOL_WRAP_CALL(lua_dump, L, writer, data, strip); +-} +-SYMBOL_WRAP_DECL(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_yieldk, L, nresults, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_resume, lua_State *L, lua_State *from, int narg){ +- SYMBOL_WRAP_CALL(lua_resume, L, from, narg); +-} +-SYMBOL_WRAP_DECL(int, lua_status, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_status, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gc, lua_State *L, int what, int data){ +- SYMBOL_WRAP_CALL(lua_gc, L, what, data); +-} +-SYMBOL_WRAP_DECL(int, lua_error, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_error, L); +-} +-SYMBOL_WRAP_DECL(int, lua_next, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_next, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_concat, lua_State *L, int n){ +- SYMBOL_WRAP_CALL(lua_concat, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_len, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_len, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_Alloc, lua_getallocf, lua_State *L, void **ud){ +- SYMBOL_WRAP_CALL(lua_getallocf, L, ud); +-} +-SYMBOL_WRAP_DECL(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud){ +- SYMBOL_WRAP_CALL(lua_setallocf, L, f, ud); +-} +-SYMBOL_WRAP_DECL(int, lua_getstack, lua_State *L, int level, lua_Debug *ar){ +- SYMBOL_WRAP_CALL(lua_getstack, L, level, ar); +-} +-SYMBOL_WRAP_DECL(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar){ +- SYMBOL_WRAP_CALL(lua_getinfo, L, what, ar); +-} +-SYMBOL_WRAP_DECL(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n){ +- SYMBOL_WRAP_CALL(lua_getlocal, L, ar, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n){ +- SYMBOL_WRAP_CALL(lua_setlocal, L, ar, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_getupvalue, lua_State *L, int funcindex, int n){ +- SYMBOL_WRAP_CALL(lua_getupvalue, L, funcindex, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_setupvalue, lua_State *L, int funcindex, int n){ +- SYMBOL_WRAP_CALL(lua_setupvalue, L, funcindex, n); +-} +-SYMBOL_WRAP_DECL(void *, lua_upvalueid, lua_State *L, int fidx, int n){ +- SYMBOL_WRAP_CALL(lua_upvalueid, L, fidx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2){ +- SYMBOL_WRAP_CALL(lua_upvaluejoin, L, fidx1, n1, fidx2, n2); +-} +-SYMBOL_WRAP_DECL(int, lua_sethook, lua_State *L, lua_Hook func, int mask, int count){ +- SYMBOL_WRAP_CALL(lua_sethook, L, func, mask, count); +-} +-SYMBOL_WRAP_DECL(lua_Hook, lua_gethook, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethook, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gethookmask, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethookmask, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gethookcount, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethookcount, L); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkversion_, lua_State *L, lua_Number ver){ +- SYMBOL_WRAP_CALL(luaL_checkversion_, L, ver); +-} +-SYMBOL_WRAP_DECL(int, luaL_getmetafield, lua_State *L, int obj, const char *e){ +- SYMBOL_WRAP_CALL(luaL_getmetafield, L, obj, e); +-} +-SYMBOL_WRAP_DECL(int, luaL_callmeta, lua_State *L, int obj, const char *e){ +- SYMBOL_WRAP_CALL(luaL_callmeta, L, obj, e); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len){ +- SYMBOL_WRAP_CALL(luaL_tolstring, L, idx, len); +-} +-SYMBOL_WRAP_DECL(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg){ +- SYMBOL_WRAP_CALL(luaL_argerror, L, numarg, extramsg); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l){ +- SYMBOL_WRAP_CALL(luaL_checklstring, L, numArg, l); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l){ +- SYMBOL_WRAP_CALL(luaL_optlstring, L, numArg, def, l); +-} +-SYMBOL_WRAP_DECL(lua_Number, luaL_checknumber, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checknumber, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def){ +- SYMBOL_WRAP_CALL(luaL_optnumber, L, nArg, def); +-} +-SYMBOL_WRAP_DECL(lua_Integer, luaL_checkinteger, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checkinteger, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def){ +- SYMBOL_WRAP_CALL(luaL_optinteger, L, nArg, def); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, luaL_checkunsigned, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checkunsigned, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, luaL_optunsigned, lua_State *L, int numArg, lua_Unsigned def){ +- SYMBOL_WRAP_CALL(luaL_optunsigned, L, numArg, def); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkstack, lua_State *L, int sz, const char *msg){ +- SYMBOL_WRAP_CALL(luaL_checkstack, L, sz, msg); +-} +-SYMBOL_WRAP_DECL(void, luaL_checktype, lua_State *L, int narg, int t){ +- SYMBOL_WRAP_CALL(luaL_checktype, L, narg, t); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkany, lua_State *L, int narg){ +- SYMBOL_WRAP_CALL(luaL_checkany, L, narg); +-} +-SYMBOL_WRAP_DECL(int, luaL_newmetatable, lua_State *L, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_newmetatable, L, tname); +-} +-SYMBOL_WRAP_DECL(void, luaL_setmetatable, lua_State *L, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_setmetatable, L, tname); +-} +-SYMBOL_WRAP_DECL(void *, luaL_testudata, lua_State *L, int ud, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_testudata, L, ud, tname); +-} +-SYMBOL_WRAP_DECL(void *, luaL_checkudata, lua_State *L, int ud, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_checkudata, L, ud, tname); +-} +-SYMBOL_WRAP_DECL(void, luaL_where, lua_State *L, int lvl){ +- SYMBOL_WRAP_CALL(luaL_where, L, lvl); +-} +-SYMBOL_WRAP_DECL(int, luaL_error, lua_State *L, const char *fmt, ...){ +- va_list argp; +- va_start(argp, fmt); +- luaL_where(L, 1); +- lua_pushvfstring(L, fmt, argp); +- va_end(argp); +- lua_concat(L, 2); +- return lua_error(L); +-} +-SYMBOL_WRAP_DECL(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]){ +- SYMBOL_WRAP_CALL(luaL_checkoption, L, narg, def, lst); +-} +-SYMBOL_WRAP_DECL(int, luaL_fileresult, lua_State *L, int stat, const char *fname){ +- SYMBOL_WRAP_CALL(luaL_fileresult, L, stat, fname); +-} +-SYMBOL_WRAP_DECL(int, luaL_execresult, lua_State *L, int stat){ +- SYMBOL_WRAP_CALL(luaL_execresult, L, stat); +-} +-SYMBOL_WRAP_DECL(int, luaL_ref, lua_State *L, int t){ +- SYMBOL_WRAP_CALL(luaL_ref, L, t); +-} +-SYMBOL_WRAP_DECL(void, luaL_unref, lua_State *L, int t, int ref){ +- SYMBOL_WRAP_CALL(luaL_unref, L, t, ref); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode){ +- SYMBOL_WRAP_CALL(luaL_loadfilex, L, filename, mode); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode){ +- SYMBOL_WRAP_CALL(luaL_loadbufferx, L, buff, sz, name, mode); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadstring, lua_State *L, const char *s){ +- SYMBOL_WRAP_CALL(luaL_loadstring, L, s); +-} +-SYMBOL_WRAP_DECL(lua_State *, luaL_newstate, void){ +- return __luaL_newstate(); +-} +-SYMBOL_WRAP_DECL(int, luaL_len, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(luaL_len, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r){ +- SYMBOL_WRAP_CALL(luaL_gsub, L, s, p, r); +-} +-SYMBOL_WRAP_DECL(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup){ +- SYMBOL_WRAP_CALL(luaL_setfuncs, L, l, nup); +-} +-SYMBOL_WRAP_DECL(int, luaL_getsubtable, lua_State *L, int idx, const char *fname){ +- SYMBOL_WRAP_CALL(luaL_getsubtable, L, idx, fname); +-} +-SYMBOL_WRAP_DECL(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level){ +- SYMBOL_WRAP_CALL(luaL_traceback, L, L1, msg, level); +-} +-SYMBOL_WRAP_DECL(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb){ +- SYMBOL_WRAP_CALL(luaL_requiref, L, modname, openf, glb); +-} +-SYMBOL_WRAP_DECL(void, luaL_buffinit, lua_State *L, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_buffinit, L, B); +-} +-SYMBOL_WRAP_DECL(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_prepbuffsize, B, sz); +-} +-SYMBOL_WRAP_DECL(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l){ +- SYMBOL_WRAP_CALL(luaL_addlstring, B, s, l); +-} +-SYMBOL_WRAP_DECL(void, luaL_addstring, luaL_Buffer *B, const char *s){ +- SYMBOL_WRAP_CALL(luaL_addstring, B, s); +-} +-SYMBOL_WRAP_DECL(void, luaL_addvalue, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_addvalue, B); +-} +-SYMBOL_WRAP_DECL(void, luaL_pushresult, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_pushresult, B); +-} +-SYMBOL_WRAP_DECL(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_pushresultsize, B, sz); +-} +-SYMBOL_WRAP_DECL(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_buffinitsize, L, B, sz); +-} +-SYMBOL_WRAP_DECL(void, luaL_openlibs, lua_State *L){ +- SYMBOL_WRAP_CALL(luaL_openlibs, L); +-} +- +-#define IMPORT_SYMBOL(name, ret, ...) \ +- __##name = (\ +- __##name = (ret (*) (__VA_ARGS__)) symbol(#name), \ +- __##name == NULL ? &__lite_xl_fallback_##name : __##name\ +- ) +- +-#define IMPORT_SYMBOL_OPT(name, ret, ...) \ +- __##name = symbol(#name) +- +-static void lite_xl_plugin_init(void *XL) { +- void* (*symbol)(const char *) = (void* (*) (const char *)) XL; +- IMPORT_SYMBOL(lua_newstate, lua_State *, lua_Alloc f, void *ud); +- IMPORT_SYMBOL(lua_close, void , lua_State *L); +- IMPORT_SYMBOL(lua_newthread, lua_State *, lua_State *L); +- IMPORT_SYMBOL(lua_atpanic, lua_CFunction , lua_State *L, lua_CFunction panicf); +- IMPORT_SYMBOL(lua_version, const lua_Number *, lua_State *L); +- IMPORT_SYMBOL(lua_absindex, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_gettop, int , lua_State *L); +- IMPORT_SYMBOL(lua_settop, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_pushvalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_copy, void , lua_State *L, int fromidx, int toidx); +- IMPORT_SYMBOL(lua_checkstack, int , lua_State *L, int sz); +- IMPORT_SYMBOL(lua_xmove, void , lua_State *from, lua_State *to, int n); +- IMPORT_SYMBOL(lua_isnumber, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_isstring, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_iscfunction, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_isuserdata, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_type, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_typename, const char *, lua_State *L, int tp); +- IMPORT_SYMBOL(lua_tonumberx, lua_Number , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_tointegerx, lua_Integer , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_tounsignedx, lua_Unsigned , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_toboolean, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tolstring, const char *, lua_State *L, int idx, size_t *len); +- IMPORT_SYMBOL(lua_rawlen, size_t , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tocfunction, lua_CFunction , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_touserdata, void *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tothread, lua_State *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_topointer, const void *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_arith, void , lua_State *L, int op); +- IMPORT_SYMBOL(lua_rawequal, int , lua_State *L, int idx1, int idx2); +- IMPORT_SYMBOL(lua_compare, int , lua_State *L, int idx1, int idx2, int op); +- IMPORT_SYMBOL(lua_pushnil, void , lua_State *L); +- IMPORT_SYMBOL(lua_pushnumber, void , lua_State *L, lua_Number n); +- IMPORT_SYMBOL(lua_pushinteger, void , lua_State *L, lua_Integer n); +- IMPORT_SYMBOL(lua_pushunsigned, void , lua_State *L, lua_Unsigned n); +- IMPORT_SYMBOL(lua_pushlstring, const char *, lua_State *L, const char *s, size_t l); +- IMPORT_SYMBOL(lua_pushstring, const char *, lua_State *L, const char *s); +- IMPORT_SYMBOL(lua_pushvfstring, const char *, lua_State *L, const char *fmt, va_list argp); +- IMPORT_SYMBOL(lua_pushfstring, const char *, lua_State *L, const char *fmt, ...); +- IMPORT_SYMBOL(lua_pushcclosure, void , lua_State *L, lua_CFunction fn, int n); +- IMPORT_SYMBOL(lua_pushboolean, void , lua_State *L, int b); +- IMPORT_SYMBOL(lua_pushlightuserdata, void , lua_State *L, void *p); +- IMPORT_SYMBOL(lua_pushthread, int , lua_State *L); +- IMPORT_SYMBOL(lua_getglobal, void , lua_State *L, const char *var); +- IMPORT_SYMBOL(lua_gettable, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getfield, void , lua_State *L, int idx, const char *k); +- IMPORT_SYMBOL(lua_rawget, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_rawgeti, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_rawgetp, void , lua_State *L, int idx, const void *p); +- IMPORT_SYMBOL(lua_createtable, void , lua_State *L, int narr, int nrec); +- IMPORT_SYMBOL_OPT(lua_newuserdata, void *, lua_State *L, size_t sz); +- IMPORT_SYMBOL(lua_newuserdatauv, void *, lua_State *L, size_t sz, int nuvalue); +- IMPORT_SYMBOL(lua_getmetatable, int , lua_State *L, int objindex); +- IMPORT_SYMBOL_OPT(lua_getuservalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getiuservalue, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_setglobal, void , lua_State *L, const char *var); +- IMPORT_SYMBOL(lua_settable, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_setfield, void , lua_State *L, int idx, const char *k); +- IMPORT_SYMBOL(lua_rawset, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_rawseti, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_rawsetp, void , lua_State *L, int idx, const void *p); +- IMPORT_SYMBOL(lua_setmetatable, int , lua_State *L, int objindex); +- IMPORT_SYMBOL_OPT(lua_setuservalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_setiuservalue, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_callk, void , lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_getctx, int , lua_State *L, int *ctx); +- IMPORT_SYMBOL(lua_pcallk, int , lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_load, int , lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode); +- IMPORT_SYMBOL(lua_dump, int , lua_State *L, lua_Writer writer, void *data, int strip); +- IMPORT_SYMBOL(lua_yieldk, int , lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_resume, int , lua_State *L, lua_State *from, int narg); +- IMPORT_SYMBOL(lua_status, int , lua_State *L); +- IMPORT_SYMBOL(lua_gc, int , lua_State *L, int what, int data); +- IMPORT_SYMBOL(lua_error, int , lua_State *L); +- IMPORT_SYMBOL(lua_next, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_concat, void , lua_State *L, int n); +- IMPORT_SYMBOL(lua_len, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getallocf, lua_Alloc , lua_State *L, void **ud); +- IMPORT_SYMBOL(lua_setallocf, void , lua_State *L, lua_Alloc f, void *ud); +- IMPORT_SYMBOL(lua_getstack, int , lua_State *L, int level, lua_Debug *ar); +- IMPORT_SYMBOL(lua_getinfo, int , lua_State *L, const char *what, lua_Debug *ar); +- IMPORT_SYMBOL(lua_getlocal, const char *, lua_State *L, const lua_Debug *ar, int n); +- IMPORT_SYMBOL(lua_setlocal, const char *, lua_State *L, const lua_Debug *ar, int n); +- IMPORT_SYMBOL(lua_getupvalue, const char *, lua_State *L, int funcindex, int n); +- IMPORT_SYMBOL(lua_setupvalue, const char *, lua_State *L, int funcindex, int n); +- IMPORT_SYMBOL(lua_upvalueid, void *, lua_State *L, int fidx, int n); +- IMPORT_SYMBOL(lua_upvaluejoin, void , lua_State *L, int fidx1, int n1, int fidx2, int n2); +- IMPORT_SYMBOL(lua_sethook, int , lua_State *L, lua_Hook func, int mask, int count); +- IMPORT_SYMBOL(lua_gethook, lua_Hook , lua_State *L); +- IMPORT_SYMBOL(lua_gethookmask, int , lua_State *L); +- IMPORT_SYMBOL(lua_gethookcount, int , lua_State *L); +- IMPORT_SYMBOL(luaL_checkversion_, void , lua_State *L, lua_Number ver); +- IMPORT_SYMBOL(luaL_getmetafield, int , lua_State *L, int obj, const char *e); +- IMPORT_SYMBOL(luaL_callmeta, int , lua_State *L, int obj, const char *e); +- IMPORT_SYMBOL(luaL_tolstring, const char *, lua_State *L, int idx, size_t *len); +- IMPORT_SYMBOL(luaL_argerror, int , lua_State *L, int numarg, const char *extramsg); +- IMPORT_SYMBOL(luaL_checklstring, const char *, lua_State *L, int numArg, size_t *l); +- IMPORT_SYMBOL(luaL_optlstring, const char *, lua_State *L, int numArg, const char *def, size_t *l); +- IMPORT_SYMBOL(luaL_checknumber, lua_Number , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optnumber, lua_Number , lua_State *L, int nArg, lua_Number def); +- IMPORT_SYMBOL(luaL_checkinteger, lua_Integer , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optinteger, lua_Integer , lua_State *L, int nArg, lua_Integer def); +- IMPORT_SYMBOL(luaL_checkunsigned, lua_Unsigned , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optunsigned, lua_Unsigned , lua_State *L, int numArg, lua_Unsigned def); +- IMPORT_SYMBOL(luaL_checkstack, void , lua_State *L, int sz, const char *msg); +- IMPORT_SYMBOL(luaL_checktype, void , lua_State *L, int narg, int t); +- IMPORT_SYMBOL(luaL_checkany, void , lua_State *L, int narg); +- IMPORT_SYMBOL(luaL_newmetatable, int , lua_State *L, const char *tname); +- IMPORT_SYMBOL(luaL_setmetatable, void , lua_State *L, const char *tname); +- IMPORT_SYMBOL(luaL_testudata, void *, lua_State *L, int ud, const char *tname); +- IMPORT_SYMBOL(luaL_checkudata, void *, lua_State *L, int ud, const char *tname); +- IMPORT_SYMBOL(luaL_where, void , lua_State *L, int lvl); +- IMPORT_SYMBOL(luaL_error, int , lua_State *L, const char *fmt, ...); +- IMPORT_SYMBOL(luaL_checkoption, int , lua_State *L, int narg, const char *def, const char *const lst[]); +- IMPORT_SYMBOL(luaL_fileresult, int , lua_State *L, int stat, const char *fname); +- IMPORT_SYMBOL(luaL_execresult, int , lua_State *L, int stat); +- IMPORT_SYMBOL(luaL_ref, int , lua_State *L, int t); +- IMPORT_SYMBOL(luaL_unref, void , lua_State *L, int t, int ref); +- IMPORT_SYMBOL(luaL_loadfilex, int , lua_State *L, const char *filename, const char *mode); +- IMPORT_SYMBOL(luaL_loadbufferx, int , lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); +- IMPORT_SYMBOL(luaL_loadstring, int , lua_State *L, const char *s); +- IMPORT_SYMBOL(luaL_newstate, lua_State *, void); +- IMPORT_SYMBOL(luaL_len, int , lua_State *L, int idx); +- IMPORT_SYMBOL(luaL_gsub, const char *, lua_State *L, const char *s, const char *p, const char *r); +- IMPORT_SYMBOL(luaL_setfuncs, void , lua_State *L, const luaL_Reg *l, int nup); +- IMPORT_SYMBOL(luaL_getsubtable, int , lua_State *L, int idx, const char *fname); +- IMPORT_SYMBOL(luaL_traceback, void , lua_State *L, lua_State *L1, const char *msg, int level); +- IMPORT_SYMBOL(luaL_requiref, void , lua_State *L, const char *modname, lua_CFunction openf, int glb); +- IMPORT_SYMBOL(luaL_buffinit, void , lua_State *L, luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_prepbuffsize, char *, luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_addlstring, void , luaL_Buffer *B, const char *s, size_t l); +- IMPORT_SYMBOL(luaL_addstring, void , luaL_Buffer *B, const char *s); +- IMPORT_SYMBOL(luaL_addvalue, void , luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_pushresult, void , luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_pushresultsize, void , luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_buffinitsize, char *, lua_State *L, luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_openlibs, void, lua_State* L); +-} +- +-#endif /* LITE_XL_PLUGIN_ENTRYPOINT */ +- +-#endif /* LITE_XL_PLUGIN_API */ diff --git a/tasks/lite-xl__lite-xl-1436/solution/solve.sh b/tasks/lite-xl__lite-xl-1436/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/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/lite-xl__lite-xl-1436/task.toml b/tasks/lite-xl__lite-xl-1436/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2de5c9aaef9df020c959441aebe1c4373c82efad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1436" +description = "upgrade header files to Lua 5.4" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d15108309c8ce98f9a5412e87a05d39a177e5765" +reference = "https://github.com/lite-xl/lite-xl/pull/1436" +source_access = "auto" +built_at = "2026-11-16T16:09:56.242903+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a1ae787e2c9dcb5191e1eb72ab0ed22163c22099a512c4933a4418ab58929aa8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-11T15:20:28Z" +diff_format = "unified" +context_files = [ + "resources/include/lite_xl_plugin_api.h", + "resources/lite_xl_plugin_api.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3687 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.283804+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b6c61ddfbb69aef1d91f6ffaa60bbb9dc01ad5e4648f032c7c292080515a96f0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1436/tests/capture.py b/tasks/lite-xl__lite-xl-1436/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/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/lite-xl__lite-xl-1436/tests/instruction.md b/tasks/lite-xl__lite-xl-1436/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a536a743400194426a399879a78e9516be2a34c9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** upgrade header files to Lua 5.4 + +## Description + +Old header. New Lua. Me compile no work. + +Updated the function prototypes, macros and structures to Lua 5.4. +Polyfills for backward compatibility with other Lua versions are removed. +lite_xl_plugin_init is now extern so that dlls with multiple entrypoints (eventually) can use it. + +I've tested this new header with [cffi-lua][1] and [ltreesitter][2]. +No warnings. + +Requires #1440. + + +[1]: https://github.com/q66/cffi-lua +[2]: https://github.com/euclidianAce/ltreesitter + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d15108309c8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1436/tests/oracle.patch b/tasks/lite-xl__lite-xl-1436/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f23d49172a8f8d6761b5706179d2a32e7c6f78e8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/tests/oracle.patch @@ -0,0 +1,3700 @@ +diff --git a/resources/include/lite_xl_plugin_api.h b/resources/include/lite_xl_plugin_api.h +new file mode 100644 +index 00000000..2947039e +--- /dev/null ++++ b/resources/include/lite_xl_plugin_api.h +@@ -0,0 +1,2563 @@ ++/** ++ * lite_xl_plugin_api.h ++ * API for writing C extension modules loaded by Lite XL. ++ * This file is licensed under MIT. ++ * ++ * The Lite XL plugin API is quite simple. ++ * You would write a lua C extension and replace any references to lua.h, lauxlib.h ++ * and lualib.h with lite_xl_plugin_api.h. ++ * In your main file (where your entrypoint resides), define LITE_XL_PLUGIN_ENTRYPOINT. ++ * If you have multiple entrypoints, define LITE_XL_PLUGIN_ENTRYPOINT in one of them. ++ * ++ * After that, you need to create a Lite XL entrypoint, which is formatted as ++ * luaopen_lite_xl_xxxxx instead of luaopen_xxxxx. ++ * This entrypoint accepts a lua_State and an extra parameter of type void *. ++ * In this entrypoint, call lite_xl_plugin_init() with the extra parameter. ++ * If you have multiple entrypoints, you must call lite_xl_plugin_init() in ++ * each of them. ++ * This function is not thread safe, so don't try to do anything stupid. ++ * ++ * An example: ++ * ++ * #define LITE_XL_PLUGIN_ENTRYPOINT ++ * #include "lite_xl_plugin_api.h" ++ * int luaopen_lite_xl_xxxxx(lua_State* L, void* XL) { ++ * lite_xl_plugin_init(XL); ++ * ... ++ * return 1; ++ * } ++ * ++ * You can compile the library just like any Lua library without linking to Lua. ++ * An example command would be: gcc -shared -o xxxxx.so xxxxx.c ++ * You must not link to ANY lua library to avoid symbol collision. ++ * ++ * This file contains stock configuration for a typical installation of Lua 5.4. ++ * DO NOT MODIFY ANYTHING. MODIFYING STUFFS IN HERE WILL BREAK ++ * COMPATIBILITY WITH LITE XL AND CAUSE UNDEBUGGABLE BUGS. ++**/ ++#ifndef LITE_XL_PLUGIN_API ++#define LITE_XL_PLUGIN_API ++ ++#include ++#include ++ ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ ++/* FOR_EACH macro */ ++#define CONCAT(arg1, arg2) CONCAT1(arg1, arg2) ++#define CONCAT1(arg1, arg2) CONCAT2(arg1, arg2) ++#define CONCAT2(arg1, arg2) arg1##arg2 ++#define FE_1(what, x) what x ++#define FE_2(what, x, ...) what x,FE_1(what, __VA_ARGS__) ++#define FE_3(what, x, ...) what x,FE_2(what, __VA_ARGS__) ++#define FE_4(what, x, ...) what x,FE_3(what, __VA_ARGS__) ++#define FE_5(what, x, ...) what x,FE_4(what, __VA_ARGS__) ++#define FE_6(what, x, ...) what x,FE_5(what, __VA_ARGS__) ++#define FE_7(what, x, ...) what x,FE_6(what, __VA_ARGS__) ++#define FE_8(what, x, ...) what x,FE_7(what, __VA_ARGS__) ++#define FOR_EACH_NARG(...) FOR_EACH_NARG_(__VA_ARGS__, FOR_EACH_RSEQ_N()) ++#define FOR_EACH_NARG_(...) FOR_EACH_ARG_N(__VA_ARGS__) ++#define FOR_EACH_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N ++#define FOR_EACH_RSEQ_N() 8, 7, 6, 5, 4, 3, 2, 1, 0 ++#define FOR_EACH_(N, what, ...) CONCAT(FE_, N)(what, __VA_ARGS__) ++#define FOR_EACH(what, ...) FOR_EACH_(FOR_EACH_NARG(__VA_ARGS__), what, __VA_ARGS__) ++ ++#define SYMBOL_WRAP_DECL(ret, name, ...) \ ++ ret name(__VA_ARGS__) ++ ++#define SYMBOL_WRAP_CALL(name, ...) \ ++ __##name(__VA_ARGS__) ++ ++#define SYMBOL_WRAP_CALL_FB(name, ...) \ ++ return __lite_xl_fallback_##name(__VA_ARGS__) ++ ++#ifdef LITE_XL_PLUGIN_ENTRYPOINT ++ #define SYMBOL_DECLARE(ret, name, ...) \ ++ static ret (*__##name) (__VA_ARGS__); \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); \ ++ static ret __lite_xl_fallback_##name(FOR_EACH(UNUSED, __VA_ARGS__)) { \ ++ fputs("warning: " #name " is a stub", stderr); \ ++ exit(1); \ ++ } ++ #define SYMBOL_DECLARE_VARARG(ret, name, ...) \ ++ static ret (*__##name) (__VA_ARGS__, ...); \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__, ...); \ ++ static ret __lite_xl_fallback_##name(FOR_EACH(UNUSED, __VA_ARGS__), ...) { \ ++ fputs("warning: " #name " is a stub", stderr); \ ++ exit(1); \ ++ } ++#else ++ #define SYMBOL_DECLARE(ret, name, ...) \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); ++ #define SYMBOL_DECLARE_VARARG(ret, name, ...) \ ++ SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__, ...); ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: luaconf.h $ ++** Configuration file for Lua ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef luaconf_h ++#define luaconf_h ++ ++#include ++#include ++ ++ ++/* ++** =================================================================== ++** General Configuration File for Lua ++** ++** Some definitions here can be changed externally, through the compiler ++** (e.g., with '-D' options): They are commented out or protected ++** by '#if !defined' guards. However, several other definitions ++** should be changed directly here, either because they affect the ++** Lua ABI (by making the changes here, you ensure that all software ++** connected to Lua, such as C libraries, will be compiled with the same ++** configuration); or because they are seldom changed. ++** ++** Search for "@@" to find all configurable definitions. ++** =================================================================== ++*/ ++ ++ ++/* ++** {==================================================================== ++** System Configuration: macros to adapt (if needed) Lua to some ++** particular platform, for instance restricting it to C89. ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_USE_C89 controls the use of non-ISO-C89 features. ++** Define it if you want Lua to avoid the use of a few C99 features ++** or Windows-specific features on Windows. ++*/ ++/* #define LUA_USE_C89 */ ++ ++ ++/* ++** By default, Lua on Windows use (some) specific Windows features ++*/ ++#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) ++#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ ++#endif ++ ++ ++#if defined(LUA_USE_WINDOWS) ++#define LUA_DL_DLL /* enable support for DLL */ ++#define LUA_USE_C89 /* broadly, Windows is C89 */ ++#endif ++ ++ ++#if defined(LUA_USE_LINUX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ ++#endif ++ ++ ++#if defined(LUA_USE_MACOSX) ++#define LUA_USE_POSIX ++#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ ++#endif ++ ++ ++/* ++@@ LUAI_IS32INT is true iff 'int' has (at least) 32 bits. ++*/ ++#define LUAI_IS32INT ((UINT_MAX >> 30) >= 3) ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Number types. These options should not be ++** set externally, because any other code connected to Lua must ++** use the same configuration. ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_INT_TYPE defines the type for Lua integers. ++@@ LUA_FLOAT_TYPE defines the type for Lua floats. ++** Lua should work fine with any mix of these options supported ++** by your C compiler. The usual configurations are 64-bit integers ++** and 'double' (the default), 32-bit integers and 'float' (for ++** restricted platforms), and 'long'/'double' (for C compilers not ++** compliant with C99, which may not have support for 'long long'). ++*/ ++ ++/* predefined options for LUA_INT_TYPE */ ++#define LUA_INT_INT 1 ++#define LUA_INT_LONG 2 ++#define LUA_INT_LONGLONG 3 ++ ++/* predefined options for LUA_FLOAT_TYPE */ ++#define LUA_FLOAT_FLOAT 1 ++#define LUA_FLOAT_DOUBLE 2 ++#define LUA_FLOAT_LONGDOUBLE 3 ++ ++ ++/* Default configuration ('long long' and 'double', for 64-bit Lua) */ ++#define LUA_INT_DEFAULT LUA_INT_LONGLONG ++#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE ++ ++ ++/* ++@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. ++*/ ++#define LUA_32BITS 0 ++ ++ ++/* ++@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for ++** C89 ('long' and 'double'); Windows always has '__int64', so it does ++** not need to use this case. ++*/ ++#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) ++#define LUA_C89_NUMBERS 1 ++#else ++#define LUA_C89_NUMBERS 0 ++#endif ++ ++ ++#if LUA_32BITS /* { */ ++/* ++** 32-bit integers and 'float' ++*/ ++#if LUAI_IS32INT /* use 'int' if big enough */ ++#define LUA_INT_TYPE LUA_INT_INT ++#else /* otherwise use 'long' */ ++#define LUA_INT_TYPE LUA_INT_LONG ++#endif ++#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT ++ ++#elif LUA_C89_NUMBERS /* }{ */ ++/* ++** largest types available for C89 ('long' and 'double') ++*/ ++#define LUA_INT_TYPE LUA_INT_LONG ++#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE ++ ++#else /* }{ */ ++/* use defaults */ ++ ++#define LUA_INT_TYPE LUA_INT_DEFAULT ++#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT ++ ++#endif /* } */ ++ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Paths. ++** =================================================================== ++*/ ++ ++/* ++** LUA_PATH_SEP is the character that separates templates in a path. ++** LUA_PATH_MARK is the string that marks the substitution points in a ++** template. ++** LUA_EXEC_DIR in a Windows path is replaced by the executable's ++** directory. ++*/ ++#define LUA_PATH_SEP ";" ++#define LUA_PATH_MARK "?" ++#define LUA_EXEC_DIR "!" ++ ++ ++/* ++@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for ++** Lua libraries. ++@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for ++** C libraries. ++** CHANGE them if your machine has a non-conventional directory ++** hierarchy or if you want to install your libraries in ++** non-conventional directories. ++*/ ++ ++#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#if defined(_WIN32) /* { */ ++/* ++** In Windows, any exclamation mark ('!') in the path is replaced by the ++** path of the directory of the executable file of the current process. ++*/ ++#define LUA_LDIR "!\\lua\\" ++#define LUA_CDIR "!\\" ++#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ ++ LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ ++ ".\\?.lua;" ".\\?\\init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.dll;" \ ++ LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \ ++ LUA_CDIR"loadall.dll;" ".\\?.dll" ++#endif ++ ++#else /* }{ */ ++ ++#define LUA_ROOT "/usr/local/" ++#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/" ++#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/" ++ ++#if !defined(LUA_PATH_DEFAULT) ++#define LUA_PATH_DEFAULT \ ++ LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ ++ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \ ++ "./?.lua;" "./?/init.lua" ++#endif ++ ++#if !defined(LUA_CPATH_DEFAULT) ++#define LUA_CPATH_DEFAULT \ ++ LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" ++#endif ++ ++#endif /* } */ ++ ++ ++/* ++@@ LUA_DIRSEP is the directory separator (for submodules). ++** CHANGE it if your machine does not use "/" as the directory separator ++** and is not Windows. (On Windows Lua automatically uses "\".) ++*/ ++#if !defined(LUA_DIRSEP) ++ ++#if defined(_WIN32) ++#define LUA_DIRSEP "\\" ++#else ++#define LUA_DIRSEP "/" ++#endif ++ ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Marks for exported symbols in the C code ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_API is a mark for all core API functions. ++@@ LUALIB_API is a mark for all auxiliary library functions. ++@@ LUAMOD_API is a mark for all standard library opening functions. ++** CHANGE them if you need to define those functions in some special way. ++** For instance, if you want to create one Windows DLL with the core and ++** the libraries, you may want to use the following definition (define ++** LUA_BUILD_AS_DLL to get it). ++*/ ++#if defined(LUA_BUILD_AS_DLL) /* { */ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) /* { */ ++#define LUA_API __declspec(dllexport) ++#else /* }{ */ ++#define LUA_API __declspec(dllimport) ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#define LUA_API extern ++ ++#endif /* } */ ++ ++ ++/* ++** More often than not the libs go together with the core. ++*/ ++#define LUALIB_API LUA_API ++#define LUAMOD_API LUA_API ++ ++ ++/* ++@@ LUAI_FUNC is a mark for all extern functions that are not to be ++** exported to outside modules. ++@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables, ++** none of which to be exported to outside modules (LUAI_DDEF for ++** definitions and LUAI_DDEC for declarations). ++** CHANGE them if you need to mark them in some special way. Elf/gcc ++** (versions 3.2 and later) mark them as "hidden" to optimize access ++** when Lua is compiled as a shared library. Not all elf targets support ++** this attribute. Unfortunately, gcc does not offer a way to check ++** whether the target offers that support, and those without support ++** give a warning about it. To avoid these warnings, change to the ++** default definition. ++*/ ++#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ ++ defined(__ELF__) /* { */ ++#define LUAI_FUNC __attribute__((visibility("internal"))) extern ++#else /* }{ */ ++#define LUAI_FUNC extern ++#endif /* } */ ++ ++#define LUAI_DDEC(dec) LUAI_FUNC dec ++#define LUAI_DDEF /* empty */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Compatibility with previous versions ++** =================================================================== ++*/ ++ ++/* ++@@ LUA_COMPAT_5_3 controls other macros for compatibility with Lua 5.3. ++** You can define it to get all options, or change specific options ++** to fit your specific needs. ++*/ ++#if defined(LUA_COMPAT_5_3) /* { */ ++ ++/* ++@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated ++** functions in the mathematical library. ++** (These functions were already officially removed in 5.3; ++** nevertheless they are still available here.) ++*/ ++#define LUA_COMPAT_MATHLIB ++ ++/* ++@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for ++** manipulating other integer types (lua_pushunsigned, lua_tounsigned, ++** luaL_checkint, luaL_checklong, etc.) ++** (These macros were also officially removed in 5.3, but they are still ++** available here.) ++*/ ++#define LUA_COMPAT_APIINTCASTS ++ ++ ++/* ++@@ LUA_COMPAT_LT_LE controls the emulation of the '__le' metamethod ++** using '__lt'. ++*/ ++#define LUA_COMPAT_LT_LE ++ ++ ++/* ++@@ The following macros supply trivial compatibility for some ++** changes in the API. The macros themselves document how to ++** change your code to avoid using them. ++** (Once more, these macros were officially removed in 5.3, but they are ++** still available here.) ++*/ ++#define lua_strlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_objlen(L,i) lua_rawlen(L, (i)) ++ ++#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) ++#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++ ++/* ++** {================================================================== ++** Configuration for Numbers (low-level part). ++** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_* ++** satisfy your needs. ++** =================================================================== ++*/ ++ ++/* ++@@ LUAI_UACNUMBER is the result of a 'default argument promotion' ++@@ over a floating number. ++@@ l_floatatt(x) corrects float attribute 'x' to the proper float type ++** by prefixing it with one of FLT/DBL/LDBL. ++@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats. ++@@ LUA_NUMBER_FMT is the format for writing floats. ++@@ lua_number2str converts a float to a string. ++@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. ++@@ l_floor takes the floor of a float. ++@@ lua_str2number converts a decimal numeral to a number. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define l_floor(x) (l_mathop(floor)(x)) ++ ++#define lua_number2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n)) ++ ++/* ++@@ lua_numbertointeger converts a float number with an integral value ++** to an integer, or returns 0 if float is not within the range of ++** a lua_Integer. (The range comparisons are tricky because of ++** rounding. The tests here assume a two-complement representation, ++** where MININTEGER always has an exact representation as a float; ++** MAXINTEGER may not have one, and therefore its conversion to float ++** may have an ill-defined value.) ++*/ ++#define lua_numbertointeger(n,p) \ ++ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ ++ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ ++ (*(p) = (LUA_INTEGER)(n), 1)) ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */ ++ ++#define LUA_NUMBER float ++ ++#define l_floatatt(n) (FLT_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.7g" ++ ++#define l_mathop(op) op##f ++ ++#define lua_str2number(s,p) strtof((s), (p)) ++ ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */ ++ ++#define LUA_NUMBER long double ++ ++#define l_floatatt(n) (LDBL_##n) ++ ++#define LUAI_UACNUMBER long double ++ ++#define LUA_NUMBER_FRMLEN "L" ++#define LUA_NUMBER_FMT "%.19Lg" ++ ++#define l_mathop(op) op##l ++ ++#define lua_str2number(s,p) strtold((s), (p)) ++ ++#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */ ++ ++#define LUA_NUMBER double ++ ++#define l_floatatt(n) (DBL_##n) ++ ++#define LUAI_UACNUMBER double ++ ++#define LUA_NUMBER_FRMLEN "" ++#define LUA_NUMBER_FMT "%.14g" ++ ++#define l_mathop(op) op ++ ++#define lua_str2number(s,p) strtod((s), (p)) ++ ++#else /* }{ */ ++ ++#error "numeric float type not defined" ++ ++#endif /* } */ ++ ++ ++ ++/* ++@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER. ++@@ LUAI_UACINT is the result of a 'default argument promotion' ++@@ over a LUA_INTEGER. ++@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers. ++@@ LUA_INTEGER_FMT is the format for writing integers. ++@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER. ++@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER. ++@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED. ++@@ lua_integer2str converts an integer to a string. ++*/ ++ ++ ++/* The following definitions are good for most cases here */ ++ ++#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d" ++ ++#define LUAI_UACINT LUA_INTEGER ++ ++#define lua_integer2str(s,sz,n) \ ++ l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n)) ++ ++/* ++** use LUAI_UACINT here to avoid problems with promotions (which ++** can turn a comparison between unsigneds into a signed comparison) ++*/ ++#define LUA_UNSIGNED unsigned LUAI_UACINT ++ ++ ++/* now the variable definitions */ ++ ++#if LUA_INT_TYPE == LUA_INT_INT /* { int */ ++ ++#define LUA_INTEGER int ++#define LUA_INTEGER_FRMLEN "" ++ ++#define LUA_MAXINTEGER INT_MAX ++#define LUA_MININTEGER INT_MIN ++ ++#define LUA_MAXUNSIGNED UINT_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */ ++ ++#define LUA_INTEGER long ++#define LUA_INTEGER_FRMLEN "l" ++ ++#define LUA_MAXINTEGER LONG_MAX ++#define LUA_MININTEGER LONG_MIN ++ ++#define LUA_MAXUNSIGNED ULONG_MAX ++ ++#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */ ++ ++/* use presence of macro LLONG_MAX as proxy for C99 compliance */ ++#if defined(LLONG_MAX) /* { */ ++/* use ISO C99 stuff */ ++ ++#define LUA_INTEGER long long ++#define LUA_INTEGER_FRMLEN "ll" ++ ++#define LUA_MAXINTEGER LLONG_MAX ++#define LUA_MININTEGER LLONG_MIN ++ ++#define LUA_MAXUNSIGNED ULLONG_MAX ++ ++#elif defined(LUA_USE_WINDOWS) /* }{ */ ++/* in Windows, can use specific Windows types */ ++ ++#define LUA_INTEGER __int64 ++#define LUA_INTEGER_FRMLEN "I64" ++ ++#define LUA_MAXINTEGER _I64_MAX ++#define LUA_MININTEGER _I64_MIN ++ ++#define LUA_MAXUNSIGNED _UI64_MAX ++ ++#else /* }{ */ ++ ++#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ ++ or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" ++ ++#endif /* } */ ++ ++#else /* }{ */ ++ ++#error "numeric integer type not defined" ++ ++#endif /* } */ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Dependencies with C99 and other C details ++** =================================================================== ++*/ ++ ++/* ++@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89. ++** (All uses in Lua have only one format item.) ++*/ ++#if !defined(LUA_USE_C89) ++#define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i) ++#else ++#define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i)) ++#endif ++ ++ ++/* ++@@ lua_strx2number converts a hexadecimal numeral to a number. ++** In C99, 'strtod' does that conversion. Otherwise, you can ++** leave 'lua_strx2number' undefined and Lua will provide its own ++** implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_strx2number(s,p) lua_str2number(s,p) ++#endif ++ ++ ++/* ++@@ lua_pointer2str converts a pointer to a readable string in a ++** non-specified way. ++*/ ++#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p) ++ ++ ++/* ++@@ lua_number2strx converts a float to a hexadecimal numeral. ++** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that. ++** Otherwise, you can leave 'lua_number2strx' undefined and Lua will ++** provide its own implementation. ++*/ ++#if !defined(LUA_USE_C89) ++#define lua_number2strx(L,b,sz,f,n) \ ++ ((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n))) ++#endif ++ ++ ++/* ++** 'strtof' and 'opf' variants for math functions are not valid in ++** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the ++** availability of these variants. ('math.h' is already included in ++** all files that use these macros.) ++*/ ++#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) ++#undef l_mathop /* variants not available */ ++#undef lua_str2number ++#define l_mathop(op) (lua_Number)op /* no variant */ ++#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) ++#endif ++ ++ ++/* ++@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation ++** functions. It must be a numerical type; Lua will use 'intptr_t' if ++** available, otherwise it will use 'ptrdiff_t' (the nearest thing to ++** 'intptr_t' in C89) ++*/ ++#define LUA_KCONTEXT ptrdiff_t ++ ++#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ ++ __STDC_VERSION__ >= 199901L ++#include ++#if defined(INTPTR_MAX) /* even in C99 this type is optional */ ++#undef LUA_KCONTEXT ++#define LUA_KCONTEXT intptr_t ++#endif ++#endif ++ ++ ++/* ++@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point). ++** Change that if you do not want to use C locales. (Code using this ++** macro must include the header 'locale.h'.) ++*/ ++#if !defined(lua_getlocaledecpoint) ++#define lua_getlocaledecpoint() (localeconv()->decimal_point[0]) ++#endif ++ ++ ++/* ++** macros to improve jump prediction, used mostly for error handling ++** and debug facilities. (Some macros in the Lua API use these macros. ++** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your ++** code.) ++*/ ++#if !defined(luai_likely) ++ ++#if defined(__GNUC__) && !defined(LUA_NOBUILTIN) ++#define luai_likely(x) (__builtin_expect(((x) != 0), 1)) ++#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0)) ++#else ++#define luai_likely(x) (x) ++#define luai_unlikely(x) (x) ++#endif ++ ++#endif ++ ++ ++#if defined(LUA_CORE) || defined(LUA_LIB) ++/* shorter names for Lua's own use */ ++#define l_likely(x) luai_likely(x) ++#define l_unlikely(x) luai_unlikely(x) ++#endif ++ ++ ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Language Variations ++** ===================================================================== ++*/ ++ ++/* ++@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some ++** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from ++** numbers to strings. Define LUA_NOCVTS2N to turn off automatic ++** coercion from strings to numbers. ++*/ ++/* #define LUA_NOCVTN2S */ ++/* #define LUA_NOCVTS2N */ ++ ++ ++/* ++@@ LUA_USE_APICHECK turns on several consistency checks on the C API. ++** Define it as a help when debugging C code. ++*/ ++#if defined(LUA_USE_APICHECK) ++#include ++#define luai_apicheck(l,e) assert(e) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {================================================================== ++** Macros that affect the API and must be stable (that is, must be the ++** same when you compile Lua and when you compile code that links to ++** Lua). ++** ===================================================================== ++*/ ++ ++/* ++@@ LUAI_MAXSTACK limits the size of the Lua stack. ++** CHANGE it if you need a different limit. This limit is arbitrary; ++** its only purpose is to stop Lua from consuming unlimited stack ++** space (and to reserve some numbers for pseudo-indices). ++** (It must fit into max(size_t)/32.) ++*/ ++#if LUAI_IS32INT ++#define LUAI_MAXSTACK 1000000 ++#else ++#define LUAI_MAXSTACK 15000 ++#endif ++ ++ ++/* ++@@ LUA_EXTRASPACE defines the size of a raw memory area associated with ++** a Lua state with very fast access. ++** CHANGE it if you need a different size. ++*/ ++#define LUA_EXTRASPACE (sizeof(void *)) ++ ++ ++/* ++@@ LUA_IDSIZE gives the maximum size for the description of the source ++@@ of a function in debug information. ++** CHANGE it if you want a different size. ++*/ ++#define LUA_IDSIZE 60 ++ ++ ++/* ++@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. ++*/ ++#define LUAL_BUFFERSIZE ((int)(16 * sizeof(void*) * sizeof(lua_Number))) ++ ++ ++/* ++@@ LUAI_MAXALIGN defines fields that, when used in a union, ensure ++** maximum alignment for the other items in that union. ++*/ ++#define LUAI_MAXALIGN lua_Number n; double u; void *s; lua_Integer i; long l ++ ++/* }================================================================== */ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lua.h $ ++** Lua - A Scripting Language ++** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ++** See Copyright Notice at the end of this file ++*/ ++ ++ ++#ifndef lua_h ++#define lua_h ++ ++#include ++#include ++ ++ ++#define LUA_VERSION_MAJOR "5" ++#define LUA_VERSION_MINOR "4" ++#define LUA_VERSION_RELEASE "4" ++ ++#define LUA_VERSION_NUM 504 ++#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 4) ++ ++#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR ++#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE ++#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2022 Lua.org, PUC-Rio" ++#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" ++ ++ ++/* mark for precompiled code ('Lua') */ ++#define LUA_SIGNATURE "\x1bLua" ++ ++/* option for multiple returns in 'lua_pcall' and 'lua_call' */ ++#define LUA_MULTRET (-1) ++ ++ ++/* ++** Pseudo-indices ++** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty ++** space after that to help overflow detection) ++*/ ++#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000) ++#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) ++ ++ ++/* thread status */ ++#define LUA_OK 0 ++#define LUA_YIELD 1 ++#define LUA_ERRRUN 2 ++#define LUA_ERRSYNTAX 3 ++#define LUA_ERRMEM 4 ++#define LUA_ERRERR 5 ++ ++ ++typedef struct lua_State lua_State; ++ ++ ++/* ++** basic types ++*/ ++#define LUA_TNONE (-1) ++ ++#define LUA_TNIL 0 ++#define LUA_TBOOLEAN 1 ++#define LUA_TLIGHTUSERDATA 2 ++#define LUA_TNUMBER 3 ++#define LUA_TSTRING 4 ++#define LUA_TTABLE 5 ++#define LUA_TFUNCTION 6 ++#define LUA_TUSERDATA 7 ++#define LUA_TTHREAD 8 ++ ++#define LUA_NUMTYPES 9 ++ ++ ++ ++/* minimum Lua stack available to a C function */ ++#define LUA_MINSTACK 20 ++ ++ ++/* predefined values in the registry */ ++#define LUA_RIDX_MAINTHREAD 1 ++#define LUA_RIDX_GLOBALS 2 ++#define LUA_RIDX_LAST LUA_RIDX_GLOBALS ++ ++ ++/* type of numbers in Lua */ ++typedef LUA_NUMBER lua_Number; ++ ++ ++/* type for integer functions */ ++typedef LUA_INTEGER lua_Integer; ++ ++/* unsigned integer type */ ++typedef LUA_UNSIGNED lua_Unsigned; ++ ++/* type for continuation-function contexts */ ++typedef LUA_KCONTEXT lua_KContext; ++ ++ ++/* ++** Type for C functions registered with Lua ++*/ ++typedef int (*lua_CFunction) (lua_State *L); ++ ++/* ++** Type for continuation functions ++*/ ++typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); ++ ++ ++/* ++** Type for functions that read/write blocks when loading/dumping Lua chunks ++*/ ++typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); ++ ++typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud); ++ ++ ++/* ++** Type for memory-allocation functions ++*/ ++typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); ++ ++ ++/* ++** Type for warning functions ++*/ ++typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont); ++ ++ ++ ++ ++/* ++** generic extra include file ++*/ ++#if defined(LUA_USER_H) ++#include LUA_USER_H ++#endif ++ ++ ++/* ++** RCS ident string ++*/ ++extern const char lua_ident[]; ++ ++ ++/* ++** state manipulation ++*/ ++SYMBOL_DECLARE(lua_State *, lua_newstate, lua_Alloc f, void *ud) ++SYMBOL_DECLARE(void, lua_close, lua_State *L) ++SYMBOL_DECLARE(lua_State *, lua_newthread, lua_State *L) ++SYMBOL_DECLARE(int, lua_resetthread, lua_State *L) ++ ++SYMBOL_DECLARE(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) ++ ++ ++SYMBOL_DECLARE(lua_Number, lua_version, lua_State *L) ++ ++ ++/* ++** basic stack manipulation ++*/ ++SYMBOL_DECLARE(int , lua_absindex, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_gettop, lua_State *L) ++SYMBOL_DECLARE(void, lua_settop, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_pushvalue, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_rotate, lua_State *L, int idx, int n) ++SYMBOL_DECLARE(void, lua_copy, lua_State *L, int fromidx, int toidx) ++SYMBOL_DECLARE(int , lua_checkstack, lua_State *L, int n) ++ ++SYMBOL_DECLARE(void, lua_xmove, lua_State *from, lua_State *to, int n) ++ ++ ++/* ++** access functions (stack -> C) ++*/ ++ ++SYMBOL_DECLARE(int , lua_isnumber, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isstring, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_iscfunction, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isinteger, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_isuserdata, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_type, lua_State *L, int idx) ++SYMBOL_DECLARE(const char *, lua_typename, lua_State *L, int tp) ++ ++SYMBOL_DECLARE(lua_Number , lua_tonumberx, lua_State *L, int idx, int *isnum) ++SYMBOL_DECLARE(lua_Integer , lua_tointegerx, lua_State *L, int idx, int *isnum) ++SYMBOL_DECLARE(int , lua_toboolean, lua_State *L, int idx) ++SYMBOL_DECLARE(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) ++SYMBOL_DECLARE(lua_Unsigned , lua_rawlen, lua_State *L, int idx) ++SYMBOL_DECLARE(lua_CFunction , lua_tocfunction, lua_State *L, int idx) ++SYMBOL_DECLARE(void *, lua_touserdata, lua_State *L, int idx) ++SYMBOL_DECLARE(lua_State *, lua_tothread, lua_State *L, int idx) ++SYMBOL_DECLARE(const void *, lua_topointer, lua_State *L, int idx) ++ ++ ++/* ++** Comparison and arithmetic functions ++*/ ++ ++#define LUA_OPADD 0 /* ORDER TM, ORDER OP */ ++#define LUA_OPSUB 1 ++#define LUA_OPMUL 2 ++#define LUA_OPMOD 3 ++#define LUA_OPPOW 4 ++#define LUA_OPDIV 5 ++#define LUA_OPIDIV 6 ++#define LUA_OPBAND 7 ++#define LUA_OPBOR 8 ++#define LUA_OPBXOR 9 ++#define LUA_OPSHL 10 ++#define LUA_OPSHR 11 ++#define LUA_OPUNM 12 ++#define LUA_OPBNOT 13 ++ ++SYMBOL_DECLARE(void , lua_arith, lua_State *L, int op) ++ ++#define LUA_OPEQ 0 ++#define LUA_OPLT 1 ++#define LUA_OPLE 2 ++ ++SYMBOL_DECLARE(int , lua_rawequal, lua_State *L, int idx1, int idx2) ++SYMBOL_DECLARE(int , lua_compare, lua_State *L, int idx1, int idx2, int op) ++ ++ ++/* ++** push functions (C -> stack) ++*/ ++SYMBOL_DECLARE(void , lua_pushnil, lua_State *L) ++SYMBOL_DECLARE(void , lua_pushnumber, lua_State *L, lua_Number n) ++SYMBOL_DECLARE(void , lua_pushinteger, lua_State *L, lua_Integer n) ++SYMBOL_DECLARE(const char *, lua_pushlstring, lua_State *L, const char *s, size_t len) ++SYMBOL_DECLARE(const char *, lua_pushstring, lua_State *L, const char *s) ++SYMBOL_DECLARE(const char *, lua_pushvfstring, lua_State *L, const char *fmt, ++ va_list argp) ++SYMBOL_DECLARE_VARARG(const char *, lua_pushfstring, lua_State *L, const char *fmt) ++SYMBOL_DECLARE(void , lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) ++SYMBOL_DECLARE(void , lua_pushboolean, lua_State *L, int b) ++SYMBOL_DECLARE(void , lua_pushlightuserdata, lua_State *L, void *p) ++SYMBOL_DECLARE(int , lua_pushthread, lua_State *L) ++ ++ ++/* ++** get functions (Lua -> stack) ++*/ ++SYMBOL_DECLARE(int , lua_getglobal, lua_State *L, const char *name) ++SYMBOL_DECLARE(int , lua_gettable, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_getfield, lua_State *L, int idx, const char *k) ++SYMBOL_DECLARE(int , lua_geti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(int , lua_rawget, lua_State *L, int idx) ++SYMBOL_DECLARE(int , lua_rawgeti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(int , lua_rawgetp, lua_State *L, int idx, const void *p) ++ ++SYMBOL_DECLARE(void , lua_createtable, lua_State *L, int narr, int nrec) ++SYMBOL_DECLARE(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) ++SYMBOL_DECLARE(int , lua_getmetatable, lua_State *L, int objindex) ++SYMBOL_DECLARE(int , lua_getiuservalue, lua_State *L, int idx, int n) ++ ++ ++/* ++** set functions (stack -> Lua) ++*/ ++SYMBOL_DECLARE(void , lua_setglobal, lua_State *L, const char *name) ++SYMBOL_DECLARE(void , lua_settable, lua_State *L, int idx) ++SYMBOL_DECLARE(void , lua_setfield, lua_State *L, int idx, const char *k) ++SYMBOL_DECLARE(void , lua_seti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(void , lua_rawset, lua_State *L, int idx) ++SYMBOL_DECLARE(void , lua_rawseti, lua_State *L, int idx, lua_Integer n) ++SYMBOL_DECLARE(void , lua_rawsetp, lua_State *L, int idx, const void *p) ++SYMBOL_DECLARE(int , lua_setmetatable, lua_State *L, int objindex) ++SYMBOL_DECLARE(int , lua_setiuservalue, lua_State *L, int idx, int n) ++ ++ ++/* ++** 'load' and 'call' functions (load and run Lua code) ++*/ ++SYMBOL_DECLARE(void, lua_callk, lua_State *L, int nargs, int nresults, ++ lua_KContext ctx, lua_KFunction k) ++#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) ++ ++SYMBOL_DECLARE(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, ++ lua_KContext ctx, lua_KFunction k) ++#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) ++ ++SYMBOL_DECLARE(int, lua_load, lua_State *L, lua_Reader reader, void *dt, ++ const char *chunkname, const char *mode) ++ ++SYMBOL_DECLARE(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) ++ ++ ++/* ++** coroutine functions ++*/ ++SYMBOL_DECLARE(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, ++ lua_KFunction k) ++SYMBOL_DECLARE(int, lua_resume, lua_State *L, lua_State *from, int narg, ++ int *nres) ++SYMBOL_DECLARE(int, lua_status, lua_State *L) ++SYMBOL_DECLARE(int, lua_isyieldable, lua_State *L) ++ ++#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) ++ ++ ++/* ++** Warning-related functions ++*/ ++SYMBOL_DECLARE(void, lua_setwarnf, lua_State *L, lua_WarnFunction f, void *ud) ++SYMBOL_DECLARE(void, lua_warning, lua_State *L, const char *msg, int tocont) ++ ++ ++/* ++** garbage-collection function and options ++*/ ++ ++#define LUA_GCSTOP 0 ++#define LUA_GCRESTART 1 ++#define LUA_GCCOLLECT 2 ++#define LUA_GCCOUNT 3 ++#define LUA_GCCOUNTB 4 ++#define LUA_GCSTEP 5 ++#define LUA_GCSETPAUSE 6 ++#define LUA_GCSETSTEPMUL 7 ++#define LUA_GCISRUNNING 9 ++#define LUA_GCGEN 10 ++#define LUA_GCINC 11 ++ ++SYMBOL_DECLARE_VARARG(int, lua_gc, lua_State *L, int what) ++ ++ ++/* ++** miscellaneous functions ++*/ ++ ++SYMBOL_DECLARE(int , lua_error, lua_State *L) ++ ++SYMBOL_DECLARE(int , lua_next, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(void, lua_concat, lua_State *L, int n) ++SYMBOL_DECLARE(void, lua_len, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(size_t, lua_stringtonumber, lua_State *L, const char *s) ++ ++SYMBOL_DECLARE(lua_Alloc, lua_getallocf, lua_State *L, void **ud) ++SYMBOL_DECLARE(void , lua_setallocf, lua_State *L, lua_Alloc f, void *ud) ++ ++SYMBOL_DECLARE(void, lua_toclose, lua_State *L, int idx) ++SYMBOL_DECLARE(void, lua_closeslot, lua_State *L, int idx) ++ ++ ++/* ++** {============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE)) ++ ++#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL) ++#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL) ++ ++#define lua_pop(L,n) lua_settop(L, -(n)-1) ++ ++#define lua_newtable(L) lua_createtable(L, 0, 0) ++ ++#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) ++ ++#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) ++ ++#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) ++#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) ++#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) ++#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) ++#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) ++#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) ++#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) ++#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) ++ ++#define lua_pushliteral(L, s) lua_pushstring(L, "" s) ++ ++#define lua_pushglobaltable(L) \ ++ ((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)) ++ ++#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) ++ ++ ++#define lua_insert(L,idx) lua_rotate(L, (idx), 1) ++ ++#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) ++ ++#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) ++ ++/* }============================================================== */ ++ ++ ++/* ++** {============================================================== ++** compatibility macros ++** =============================================================== ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) ++#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) ++#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) ++ ++#endif ++ ++#define lua_newuserdata(L,s) lua_newuserdatauv(L,s,1) ++#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1) ++#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1) ++ ++#define LUA_NUMTAGS LUA_NUMTYPES ++ ++/* }============================================================== */ ++ ++/* ++** {====================================================================== ++** Debug API ++** ======================================================================= ++*/ ++ ++ ++/* ++** Event codes ++*/ ++#define LUA_HOOKCALL 0 ++#define LUA_HOOKRET 1 ++#define LUA_HOOKLINE 2 ++#define LUA_HOOKCOUNT 3 ++#define LUA_HOOKTAILCALL 4 ++ ++ ++/* ++** Event masks ++*/ ++#define LUA_MASKCALL (1 << LUA_HOOKCALL) ++#define LUA_MASKRET (1 << LUA_HOOKRET) ++#define LUA_MASKLINE (1 << LUA_HOOKLINE) ++#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) ++ ++typedef struct lua_Debug lua_Debug; /* activation record */ ++ ++ ++/* Functions to be called by the debugger in specific events */ ++typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); ++ ++ ++SYMBOL_DECLARE(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) ++SYMBOL_DECLARE(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) ++SYMBOL_DECLARE(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) ++SYMBOL_DECLARE(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) ++SYMBOL_DECLARE(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) ++SYMBOL_DECLARE(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) ++ ++SYMBOL_DECLARE(void *, lua_upvalueid, lua_State *L, int fidx, int n) ++SYMBOL_DECLARE(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, ++ int fidx2, int n2) ++ ++SYMBOL_DECLARE(void, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) ++SYMBOL_DECLARE(lua_Hook, lua_gethook, lua_State *L) ++SYMBOL_DECLARE(int, lua_gethookmask, lua_State *L) ++SYMBOL_DECLARE(int, lua_gethookcount, lua_State *L) ++ ++SYMBOL_DECLARE(int, lua_setcstacklimit, lua_State *L, unsigned int limit) ++ ++struct lua_Debug { ++ int event; ++ const char *name; /* (n) */ ++ const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */ ++ const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */ ++ const char *source; /* (S) */ ++ size_t srclen; /* (S) */ ++ int currentline; /* (l) */ ++ int linedefined; /* (S) */ ++ int lastlinedefined; /* (S) */ ++ unsigned char nups; /* (u) number of upvalues */ ++ unsigned char nparams;/* (u) number of parameters */ ++ char isvararg; /* (u) */ ++ char istailcall; /* (t) */ ++ unsigned short ftransfer; /* (r) index of first value transferred */ ++ unsigned short ntransfer; /* (r) number of transferred values */ ++ char short_src[LUA_IDSIZE]; /* (S) */ ++ /* private part */ ++ struct CallInfo *i_ci; /* active function */ ++}; ++ ++/* }====================================================================== */ ++ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lauxlib.h $ ++** Auxiliary functions for building Lua libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lauxlib_h ++#define lauxlib_h ++ ++ ++#include ++#include ++ ++ ++/* global table */ ++#define LUA_GNAME "_G" ++ ++ ++typedef struct luaL_Buffer luaL_Buffer; ++ ++ ++/* extra error code for 'luaL_loadfilex' */ ++#define LUA_ERRFILE (LUA_ERRERR+1) ++ ++ ++/* key, in the registry, for table of loaded modules */ ++#define LUA_LOADED_TABLE "_LOADED" ++ ++ ++/* key, in the registry, for table of preloaded loaders */ ++#define LUA_PRELOAD_TABLE "_PRELOAD" ++ ++ ++typedef struct luaL_Reg { ++ const char *name; ++ lua_CFunction func; ++} luaL_Reg; ++ ++ ++#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number)) ++ ++SYMBOL_DECLARE(void, luaL_checkversion_, lua_State *L, lua_Number ver, size_t sz) ++#define luaL_checkversion(L) \ ++ luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES) ++ ++SYMBOL_DECLARE(int, luaL_getmetafield, lua_State *L, int obj, const char *e) ++SYMBOL_DECLARE(int, luaL_callmeta, lua_State *L, int obj, const char *e) ++SYMBOL_DECLARE(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) ++SYMBOL_DECLARE(int, luaL_argerror, lua_State *L, int arg, const char *extramsg) ++SYMBOL_DECLARE(int, luaL_typeerror, lua_State *L, int arg, const char *tname) ++SYMBOL_DECLARE(const char *, luaL_checklstring, lua_State *L, int arg, ++ size_t *l) ++SYMBOL_DECLARE(const char *, luaL_optlstring, lua_State *L, int arg, ++ const char *def, size_t *l) ++SYMBOL_DECLARE(lua_Number, luaL_checknumber, lua_State *L, int arg) ++SYMBOL_DECLARE(lua_Number, luaL_optnumber, lua_State *L, int arg, lua_Number def) ++ ++SYMBOL_DECLARE(lua_Integer, luaL_checkinteger, lua_State *L, int arg) ++SYMBOL_DECLARE(lua_Integer, luaL_optinteger, lua_State *L, int arg, ++ lua_Integer def) ++ ++SYMBOL_DECLARE(void, luaL_checkstack, lua_State *L, int sz, const char *msg) ++SYMBOL_DECLARE(void, luaL_checktype, lua_State *L, int arg, int t) ++SYMBOL_DECLARE(void, luaL_checkany, lua_State *L, int arg) ++ ++SYMBOL_DECLARE(int , luaL_newmetatable, lua_State *L, const char *tname) ++SYMBOL_DECLARE(void , luaL_setmetatable, lua_State *L, const char *tname) ++SYMBOL_DECLARE(void *, luaL_testudata, lua_State *L, int ud, const char *tname) ++SYMBOL_DECLARE(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) ++ ++SYMBOL_DECLARE(void, luaL_where, lua_State *L, int lvl) ++SYMBOL_DECLARE_VARARG(int, luaL_error, lua_State *L, const char *fmt) ++ ++SYMBOL_DECLARE(int, luaL_checkoption, lua_State *L, int arg, const char *def, ++ const char *const lst[]) ++ ++SYMBOL_DECLARE(int, luaL_fileresult, lua_State *L, int stat, const char *fname) ++SYMBOL_DECLARE(int, luaL_execresult, lua_State *L, int stat) ++ ++ ++/* predefined references */ ++#define LUA_NOREF (-2) ++#define LUA_REFNIL (-1) ++ ++SYMBOL_DECLARE(int, luaL_ref, lua_State *L, int t) ++SYMBOL_DECLARE(void, luaL_unref, lua_State *L, int t, int ref) ++ ++SYMBOL_DECLARE(int, luaL_loadfilex, lua_State *L, const char *filename, ++ const char *mode) ++ ++#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) ++ ++SYMBOL_DECLARE(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, ++ const char *name, const char *mode) ++SYMBOL_DECLARE(int, luaL_loadstring, lua_State *L, const char *s) ++ ++SYMBOL_DECLARE(lua_State *, luaL_newstate, void) ++ ++SYMBOL_DECLARE(lua_Integer, luaL_len, lua_State *L, int idx) ++ ++SYMBOL_DECLARE(void, luaL_addgsub, luaL_Buffer *b, const char *s, ++ const char *p, const char *r) ++SYMBOL_DECLARE(const char *, luaL_gsub, lua_State *L, const char *s, ++ const char *p, const char *r) ++ ++SYMBOL_DECLARE(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) ++ ++SYMBOL_DECLARE(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) ++ ++SYMBOL_DECLARE(void, luaL_traceback, lua_State *L, lua_State *L1, ++ const char *msg, int level) ++ ++SYMBOL_DECLARE(void, luaL_requiref, lua_State *L, const char *modname, ++ lua_CFunction openf, int glb) ++ ++/* ++** =============================================================== ++** some useful macros ++** =============================================================== ++*/ ++ ++ ++#define luaL_newlibtable(L,l) \ ++ lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) ++ ++#define luaL_newlib(L,l) \ ++ (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) ++ ++#define luaL_argcheck(L, cond,arg,extramsg) \ ++ ((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg)))) ++ ++#define luaL_argexpected(L,cond,arg,tname) \ ++ ((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname)))) ++ ++#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) ++#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) ++ ++#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) ++ ++#define luaL_dofile(L, fn) \ ++ (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_dostring(L, s) \ ++ (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) ++ ++#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) ++ ++#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) ++ ++#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) ++ ++ ++/* ++** Perform arithmetic operations on lua_Integer values with wrap-around ++** semantics, as the Lua core does. ++*/ ++#define luaL_intop(op,v1,v2) \ ++ ((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2))) ++ ++ ++/* push the value used to represent failure/error */ ++#define luaL_pushfail(L) lua_pushnil(L) ++ ++ ++/* ++** Internal assertions for in-house debugging ++*/ ++#if !defined(lua_assert) ++ ++#if defined LUAI_ASSERT ++ #include ++ #define lua_assert(c) assert(c) ++#else ++ #define lua_assert(c) ((void)0) ++#endif ++ ++#endif ++ ++ ++ ++/* ++** {====================================================== ++** Generic Buffer manipulation ++** ======================================================= ++*/ ++ ++struct luaL_Buffer { ++ char *b; /* buffer address */ ++ size_t size; /* buffer size */ ++ size_t n; /* number of characters in buffer */ ++ lua_State *L; ++ union { ++ LUAI_MAXALIGN; /* ensure maximum alignment for buffer */ ++ char b[LUAL_BUFFERSIZE]; /* initial buffer */ ++ } init; ++}; ++ ++ ++#define luaL_bufflen(bf) ((bf)->n) ++#define luaL_buffaddr(bf) ((bf)->b) ++ ++ ++#define luaL_addchar(B,c) \ ++ ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \ ++ ((B)->b[(B)->n++] = (c))) ++ ++#define luaL_addsize(B,s) ((B)->n += (s)) ++ ++#define luaL_buffsub(B,s) ((B)->n -= (s)) ++ ++SYMBOL_DECLARE(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) ++SYMBOL_DECLARE(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) ++SYMBOL_DECLARE(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) ++SYMBOL_DECLARE(void, luaL_addstring, luaL_Buffer *B, const char *s) ++SYMBOL_DECLARE(void, luaL_addvalue, luaL_Buffer *B) ++SYMBOL_DECLARE(void, luaL_pushresult, luaL_Buffer *B) ++SYMBOL_DECLARE(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) ++SYMBOL_DECLARE(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) ++ ++#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) ++ ++/* }====================================================== */ ++ ++ ++ ++/* ++** {====================================================== ++** File handles for IO library ++** ======================================================= ++*/ ++ ++/* ++** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and ++** initial structure 'luaL_Stream' (it may contain other fields ++** after that initial structure). ++*/ ++ ++#define LUA_FILEHANDLE "FILE*" ++ ++ ++typedef struct luaL_Stream { ++ FILE *f; /* stream (NULL for incompletely created streams) */ ++ lua_CFunction closef; /* to close stream (NULL for closed streams) */ ++} luaL_Stream; ++ ++/* }====================================================== */ ++ ++/* ++** {================================================================== ++** "Abstraction Layer" for basic report of messages and errors ++** =================================================================== ++*/ ++ ++/* print a string */ ++#if !defined(lua_writestring) ++#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) ++#endif ++ ++/* print a newline and flush the output */ ++#if !defined(lua_writeline) ++#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) ++#endif ++ ++/* print an error message */ ++#if !defined(lua_writestringerror) ++#define lua_writestringerror(s,p) \ ++ (fprintf(stderr, (s), (p)), fflush(stderr)) ++#endif ++ ++/* }================================================================== */ ++ ++ ++/* ++** {============================================================ ++** Compatibility with deprecated conversions ++** ============================================================= ++*/ ++#if defined(LUA_COMPAT_APIINTCASTS) ++ ++#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a)) ++#define luaL_optunsigned(L,a,d) \ ++ ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d))) ++ ++#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) ++#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) ++ ++#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) ++#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) ++ ++#endif ++/* }============================================================ */ ++ ++ ++ ++#endif ++ ++ ++ ++ ++ ++/* ++** $Id: lualib.h $ ++** Lua standard libraries ++** See Copyright Notice in lua.h ++*/ ++ ++ ++#ifndef lualib_h ++#define lualib_h ++ ++ ++/* version suffix for environment variable names */ ++#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR ++ ++ ++SYMBOL_DECLARE(int, luaopen_base, lua_State *L) ++ ++#define LUA_COLIBNAME "coroutine" ++SYMBOL_DECLARE(int, luaopen_coroutine, lua_State *L) ++ ++#define LUA_TABLIBNAME "table" ++SYMBOL_DECLARE(int, luaopen_table, lua_State *L) ++ ++#define LUA_IOLIBNAME "io" ++SYMBOL_DECLARE(int, luaopen_io, lua_State *L) ++ ++#define LUA_OSLIBNAME "os" ++SYMBOL_DECLARE(int, luaopen_os, lua_State *L) ++ ++#define LUA_STRLIBNAME "string" ++SYMBOL_DECLARE(int, luaopen_string, lua_State *L) ++ ++#define LUA_UTF8LIBNAME "utf8" ++SYMBOL_DECLARE(int, luaopen_utf8, lua_State *L) ++ ++#define LUA_MATHLIBNAME "math" ++SYMBOL_DECLARE(int, luaopen_math, lua_State *L) ++ ++#define LUA_DBLIBNAME "debug" ++SYMBOL_DECLARE(int, luaopen_debug, lua_State *L) ++ ++#define LUA_LOADLIBNAME "package" ++SYMBOL_DECLARE(int, luaopen_package, lua_State *L) ++ ++ ++/* open all previous libraries */ ++SYMBOL_DECLARE(void, luaL_openlibs, lua_State *L) ++ ++ ++#endif ++ ++ ++ ++ ++ ++#ifdef LITE_XL_PLUGIN_ENTRYPOINT ++ ++SYMBOL_WRAP_DECL(lua_State *, lua_newstate, lua_Alloc f, void *ud) { ++ return SYMBOL_WRAP_CALL(lua_newstate, f, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_close, lua_State *L) { ++ SYMBOL_WRAP_CALL(lua_close, L); ++} ++SYMBOL_WRAP_DECL(lua_State *, lua_newthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_newthread, L); ++} ++SYMBOL_WRAP_DECL(int, lua_resetthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_resetthread, L); ++} ++ ++SYMBOL_WRAP_DECL(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) { ++ return SYMBOL_WRAP_CALL(lua_atpanic, L, panicf); ++} ++ ++ ++SYMBOL_WRAP_DECL(lua_Number, lua_version, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_version, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_absindex, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_absindex, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_gettop, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gettop, L); ++} ++SYMBOL_WRAP_DECL(void, lua_settop, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_settop, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_pushvalue, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_pushvalue, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_rotate, lua_State *L, int idx, int n) { ++ SYMBOL_WRAP_CALL(lua_rotate, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_copy, lua_State *L, int fromidx, int toidx) { ++ SYMBOL_WRAP_CALL(lua_copy, L, fromidx, toidx); ++} ++SYMBOL_WRAP_DECL(int, lua_checkstack, lua_State *L, int sz) { ++ return SYMBOL_WRAP_CALL(lua_checkstack, L, sz); ++} ++SYMBOL_WRAP_DECL(void, lua_xmove, lua_State *from, lua_State *to, int n) { ++ SYMBOL_WRAP_CALL(lua_xmove, from, to, n); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_isnumber, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isnumber, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isstring, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isstring, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_iscfunction, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_iscfunction, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isinteger, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isinteger, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_isuserdata, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_isuserdata, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_type, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_type, L, idx); ++} ++SYMBOL_WRAP_DECL(const char *, lua_typename, lua_State *L, int tp) { ++ return SYMBOL_WRAP_CALL(lua_typename, L, tp); ++} ++ ++SYMBOL_WRAP_DECL(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum) { ++ return SYMBOL_WRAP_CALL(lua_tonumberx, L, idx, isnum); ++} ++SYMBOL_WRAP_DECL(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum) { ++ return SYMBOL_WRAP_CALL(lua_tointegerx, L, idx, isnum); ++} ++SYMBOL_WRAP_DECL(int, lua_toboolean, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_toboolean, L, idx); ++} ++SYMBOL_WRAP_DECL(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) { ++ return SYMBOL_WRAP_CALL(lua_tolstring, L, idx, len); ++} ++SYMBOL_WRAP_DECL(lua_Unsigned, lua_rawlen, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_rawlen, L, idx); ++} ++SYMBOL_WRAP_DECL(lua_CFunction, lua_tocfunction, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_tocfunction, L, idx); ++} ++SYMBOL_WRAP_DECL(void *, lua_touserdata, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_touserdata, L, idx); ++} ++SYMBOL_WRAP_DECL(lua_State *, lua_tothread, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_tothread, L, idx); ++} ++SYMBOL_WRAP_DECL(const void *, lua_topointer, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_topointer, L, idx); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_arith, lua_State *L, int op) { ++ SYMBOL_WRAP_CALL(lua_arith, L, op); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_rawequal, lua_State *L, int idx1, int idx2) { ++ return SYMBOL_WRAP_CALL(lua_rawequal, L, idx1, idx2); ++} ++SYMBOL_WRAP_DECL(int, lua_compare, lua_State *L, int idx1, int idx2, int op) { ++ return SYMBOL_WRAP_CALL(lua_compare, L, idx1, idx2, op); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_pushnil, lua_State *L) { ++ SYMBOL_WRAP_CALL(lua_pushnil, L); ++} ++SYMBOL_WRAP_DECL(void, lua_pushnumber, lua_State *L, lua_Number n) { ++ SYMBOL_WRAP_CALL(lua_pushnumber, L, n); ++} ++SYMBOL_WRAP_DECL(void, lua_pushinteger, lua_State *L, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_pushinteger, L, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l) { ++ return SYMBOL_WRAP_CALL(lua_pushlstring, L, s, l); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushstring, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(lua_pushstring, L, s); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp) { ++ return SYMBOL_WRAP_CALL(lua_pushvfstring, L, fmt, argp); ++} ++SYMBOL_WRAP_DECL(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...) { ++ const char *res; ++ va_list argp; ++ va_start(argp, fmt); ++ res = lua_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ return res; ++} ++SYMBOL_WRAP_DECL(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) { ++ SYMBOL_WRAP_CALL(lua_pushcclosure, L, fn, n); ++} ++SYMBOL_WRAP_DECL(void, lua_pushboolean, lua_State *L, int b) { ++ SYMBOL_WRAP_CALL(lua_pushboolean, L, b); ++} ++SYMBOL_WRAP_DECL(void, lua_pushlightuserdata, lua_State *L, void *p) { ++ SYMBOL_WRAP_CALL(lua_pushlightuserdata, L, p); ++} ++SYMBOL_WRAP_DECL(int, lua_pushthread, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_pushthread, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_getglobal, lua_State *L, const char *var) { ++ return SYMBOL_WRAP_CALL(lua_getglobal, L, var); ++} ++SYMBOL_WRAP_DECL(int, lua_gettable, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_gettable, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_getfield, lua_State *L, int idx, const char *k) { ++ return SYMBOL_WRAP_CALL(lua_getfield, L, idx, k); ++} ++SYMBOL_WRAP_DECL(int , lua_geti, lua_State *L, int idx, lua_Integer n) { ++ return SYMBOL_WRAP_CALL(lua_geti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(int, lua_rawget, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_rawget, L, idx); ++} ++SYMBOL_WRAP_DECL(int, lua_rawgeti, lua_State *L, int idx, lua_Integer n) { ++ return SYMBOL_WRAP_CALL(lua_rawgeti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(int, lua_rawgetp, lua_State *L, int idx, const void *p) { ++ return SYMBOL_WRAP_CALL(lua_rawgetp, L, idx, p); ++} ++SYMBOL_WRAP_DECL(void, lua_createtable, lua_State *L, int narr, int nrec) { ++ SYMBOL_WRAP_CALL(lua_createtable, L, narr, nrec); ++} ++SYMBOL_WRAP_DECL(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) { ++ return SYMBOL_WRAP_CALL(lua_newuserdatauv, L, sz, nuvalue); ++} ++SYMBOL_WRAP_DECL(int, lua_getmetatable, lua_State *L, int objindex) { ++ return SYMBOL_WRAP_CALL(lua_getmetatable, L, objindex); ++} ++SYMBOL_WRAP_DECL(int, lua_getiuservalue, lua_State *L, int idx, int n) { ++ return SYMBOL_WRAP_CALL(lua_getiuservalue, L, idx, n); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_setglobal, lua_State *L, const char *var) { ++ SYMBOL_WRAP_CALL(lua_setglobal, L, var); ++} ++SYMBOL_WRAP_DECL(void, lua_settable, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_settable, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_setfield, lua_State *L, int idx, const char *k) { ++ SYMBOL_WRAP_CALL(lua_setfield, L, idx, k); ++} ++SYMBOL_WRAP_DECL(void, lua_seti, lua_State *L, int idx, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_seti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_rawset, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_rawset, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_rawseti, lua_State *L, int idx, lua_Integer n) { ++ SYMBOL_WRAP_CALL(lua_rawseti, L, idx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_rawsetp, lua_State *L, int idx, const void *p) { ++ SYMBOL_WRAP_CALL(lua_rawsetp, L, idx, p); ++} ++SYMBOL_WRAP_DECL(int, lua_setmetatable, lua_State *L, int objindex) { ++ return SYMBOL_WRAP_CALL(lua_setmetatable, L, objindex); ++} ++SYMBOL_WRAP_DECL(int, lua_setiuservalue, lua_State *L, int idx, int n) { ++ return SYMBOL_WRAP_CALL(lua_setiuservalue, L, idx, n); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { ++ SYMBOL_WRAP_CALL(lua_callk, L, nargs, nresults, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { ++ return SYMBOL_WRAP_CALL(lua_pcallk, L, nargs, nresults, errfunc, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode) { ++ return SYMBOL_WRAP_CALL(lua_load, L, reader, dt, chunkname, mode); ++} ++SYMBOL_WRAP_DECL(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) { ++ return SYMBOL_WRAP_CALL(lua_dump, L, writer, data, strip); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k) { ++ return SYMBOL_WRAP_CALL(lua_yieldk, L, nresults, ctx, k); ++} ++SYMBOL_WRAP_DECL(int, lua_resume, lua_State *L, lua_State *from, int narg, int *nres) { ++ return SYMBOL_WRAP_CALL(lua_resume, L, from, narg, nres); ++} ++SYMBOL_WRAP_DECL(int, lua_status, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_status, L); ++} ++SYMBOL_WRAP_DECL(int, lua_isyieldable, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_isyieldable, L); ++} ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, lua_setwarnf, lua_State *L, lua_WarnFunction f, void *ud) { ++ SYMBOL_WRAP_CALL(lua_setwarnf, L, f, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_warning, lua_State *L, const char *msg, int tocont) { ++ SYMBOL_WRAP_CALL(lua_warning, L, msg, tocont); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_gc, lua_State *L, int what, ...) { ++ /* there are no straightforward ways of passing data. */ ++ int r; ++ va_list ap; ++ va_start(ap, what); ++ if (what == LUA_GCSTEP) { ++ int stepsize = va_arg(ap, int); ++ r = __lua_gc(L, what, stepsize); ++ } else if (what == LUA_GCINC) { ++ int pause = va_arg(ap, int); ++ int stepmul = va_arg(ap, int); ++ int stepsize = va_arg(ap, int); ++ r = __lua_gc(L, what, pause, stepmul, stepsize); ++ } else if (what == LUA_GCGEN) { ++ int minormul = va_arg(ap, int); ++ int majormul = va_arg(ap, int); ++ r = __lua_gc(L, what, minormul, majormul); ++ } else { ++ r = __lua_gc(L, what); ++ } ++ return r; ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_error, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_error, L); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_next, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(lua_next, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_concat, lua_State *L, int n) { ++ SYMBOL_WRAP_CALL(lua_concat, L, n); ++} ++SYMBOL_WRAP_DECL(void, lua_len, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_len, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(size_t, lua_stringtonumber, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(lua_stringtonumber, L, s); ++} ++ ++SYMBOL_WRAP_DECL(lua_Alloc, lua_getallocf, lua_State *L, void **ud) { ++ return SYMBOL_WRAP_CALL(lua_getallocf, L, ud); ++} ++SYMBOL_WRAP_DECL(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud) { ++ SYMBOL_WRAP_CALL(lua_setallocf, L, f, ud); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_toclose, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_toclose, L, idx); ++} ++SYMBOL_WRAP_DECL(void, lua_closeslot, lua_State *L, int idx) { ++ SYMBOL_WRAP_CALL(lua_closeslot, L, idx); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) { ++ return SYMBOL_WRAP_CALL(lua_getstack, L, level, ar); ++} ++SYMBOL_WRAP_DECL(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) { ++ return SYMBOL_WRAP_CALL(lua_getinfo, L, what, ar); ++} ++SYMBOL_WRAP_DECL(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) { ++ return SYMBOL_WRAP_CALL(lua_getlocal, L, ar, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) { ++ return SYMBOL_WRAP_CALL(lua_setlocal, L, ar, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) { ++ return SYMBOL_WRAP_CALL(lua_getupvalue, L, funcindex, n); ++} ++SYMBOL_WRAP_DECL(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) { ++ return SYMBOL_WRAP_CALL(lua_setupvalue, L, funcindex, n); ++} ++ ++SYMBOL_WRAP_DECL(void *, lua_upvalueid, lua_State *L, int fidx, int n) { ++ return SYMBOL_WRAP_CALL(lua_upvalueid, L, fidx, n); ++} ++SYMBOL_WRAP_DECL(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2) { ++ SYMBOL_WRAP_CALL(lua_upvaluejoin, L, fidx1, n1, fidx2, n2); ++} ++ ++SYMBOL_WRAP_DECL(void, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) { ++ SYMBOL_WRAP_CALL(lua_sethook, L, func, mask, count); ++} ++SYMBOL_WRAP_DECL(lua_Hook, lua_gethook, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethook, L); ++} ++SYMBOL_WRAP_DECL(int, lua_gethookmask, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethookmask, L); ++} ++SYMBOL_WRAP_DECL(int, lua_gethookcount, lua_State *L) { ++ return SYMBOL_WRAP_CALL(lua_gethookcount, L); ++} ++ ++SYMBOL_WRAP_DECL(int, lua_setcstacklimit, lua_State *L, unsigned int limit) { ++ return SYMBOL_WRAP_CALL(lua_setcstacklimit, L, limit); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, luaL_checkversion_, lua_State *L, lua_Number ver, size_t sz) { ++ SYMBOL_WRAP_CALL(luaL_checkversion_, L, ver, sz); ++} ++SYMBOL_WRAP_DECL(int, luaL_getmetafield, lua_State *L, int obj, const char *e) { ++ return SYMBOL_WRAP_CALL(luaL_getmetafield, L, obj, e); ++} ++SYMBOL_WRAP_DECL(int, luaL_callmeta, lua_State *L, int obj, const char *e) { ++ return SYMBOL_WRAP_CALL(luaL_callmeta, L, obj, e); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) { ++ return SYMBOL_WRAP_CALL(luaL_tolstring, L, idx, len); ++} ++SYMBOL_WRAP_DECL(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg) { ++ return SYMBOL_WRAP_CALL(luaL_argerror, L, numarg, extramsg); ++} ++SYMBOL_WRAP_DECL(int, luaL_typeerror, lua_State *L, int arg, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_typeerror, L, arg, tname); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l) { ++ return SYMBOL_WRAP_CALL(luaL_checklstring, L, numArg, l); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l) { ++ return SYMBOL_WRAP_CALL(luaL_optlstring, L, numArg, def, l); ++} ++SYMBOL_WRAP_DECL(lua_Number, luaL_checknumber, lua_State *L, int numArg) { ++ return SYMBOL_WRAP_CALL(luaL_checknumber, L, numArg); ++} ++SYMBOL_WRAP_DECL(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def) { ++ return SYMBOL_WRAP_CALL(luaL_optnumber, L, nArg, def); ++} ++ ++SYMBOL_WRAP_DECL(lua_Integer, luaL_checkinteger, lua_State *L, int numArg) { ++ return SYMBOL_WRAP_CALL(luaL_checkinteger, L, numArg); ++} ++SYMBOL_WRAP_DECL(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def) { ++ return SYMBOL_WRAP_CALL(luaL_optinteger, L, nArg, def); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_checkstack, lua_State *L, int sz, const char *msg) { ++ SYMBOL_WRAP_CALL(luaL_checkstack, L, sz, msg); ++} ++SYMBOL_WRAP_DECL(void, luaL_checktype, lua_State *L, int narg, int t) { ++ SYMBOL_WRAP_CALL(luaL_checktype, L, narg, t); ++} ++SYMBOL_WRAP_DECL(void, luaL_checkany, lua_State *L, int narg) { ++ SYMBOL_WRAP_CALL(luaL_checkany, L, narg); ++} ++SYMBOL_WRAP_DECL(int, luaL_newmetatable, lua_State *L, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_newmetatable, L, tname); ++} ++SYMBOL_WRAP_DECL(void, luaL_setmetatable, lua_State *L, const char *tname) { ++ SYMBOL_WRAP_CALL(luaL_setmetatable, L, tname); ++} ++SYMBOL_WRAP_DECL(void *, luaL_testudata, lua_State *L, int ud, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_testudata, L, ud, tname); ++} ++SYMBOL_WRAP_DECL(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) { ++ return SYMBOL_WRAP_CALL(luaL_checkudata, L, ud, tname); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_where, lua_State *L, int lvl) { ++ SYMBOL_WRAP_CALL(luaL_where, L, lvl); ++} ++SYMBOL_WRAP_DECL(int, luaL_error, lua_State *L, const char *fmt, ...) { ++ va_list argp; ++ va_start(argp, fmt); ++ luaL_where(L, 1); ++ lua_pushvfstring(L, fmt, argp); ++ va_end(argp); ++ lua_concat(L, 2); ++ return lua_error(L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]) { ++ return SYMBOL_WRAP_CALL(luaL_checkoption, L, narg, def, lst); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_fileresult, lua_State *L, int stat, const char *fname) { ++ return SYMBOL_WRAP_CALL(luaL_fileresult, L, stat, fname); ++} ++SYMBOL_WRAP_DECL(int, luaL_execresult, lua_State *L, int stat) { ++ return SYMBOL_WRAP_CALL(luaL_execresult, L, stat); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(int, luaL_ref, lua_State *L, int t) { ++ return SYMBOL_WRAP_CALL(luaL_ref, L, t); ++} ++SYMBOL_WRAP_DECL(void, luaL_unref, lua_State *L, int t, int ref) { ++ SYMBOL_WRAP_CALL(luaL_unref, L, t, ref); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode) { ++ return SYMBOL_WRAP_CALL(luaL_loadfilex, L, filename, mode); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode) { ++ return SYMBOL_WRAP_CALL(luaL_loadbufferx, L, buff, sz, name, mode); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_loadstring, lua_State *L, const char *s) { ++ return SYMBOL_WRAP_CALL(luaL_loadstring, L, s); ++} ++ ++SYMBOL_WRAP_DECL(lua_State *, luaL_newstate, void) { ++ return __luaL_newstate(); ++} ++SYMBOL_WRAP_DECL(lua_Integer, luaL_len, lua_State *L, int idx) { ++ return SYMBOL_WRAP_CALL(luaL_len, L, idx); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_addgsub, luaL_Buffer *b, const char *s, ++ const char *p, const char *r) { ++ SYMBOL_WRAP_CALL(luaL_addgsub, b, s, p, r); ++} ++SYMBOL_WRAP_DECL(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r) { ++ return SYMBOL_WRAP_CALL(luaL_gsub, L, s, p, r); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) { ++ SYMBOL_WRAP_CALL(luaL_setfuncs, L, l, nup); ++} ++ ++SYMBOL_WRAP_DECL(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) { ++ return SYMBOL_WRAP_CALL(luaL_getsubtable, L, idx, fname); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level) { ++ SYMBOL_WRAP_CALL(luaL_traceback, L, L1, msg, level); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb) { ++ SYMBOL_WRAP_CALL(luaL_requiref, L, modname, openf, glb); ++} ++ ++ ++ ++ ++ ++ ++SYMBOL_WRAP_DECL(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_buffinit, L, B); ++} ++SYMBOL_WRAP_DECL(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) { ++ return SYMBOL_WRAP_CALL(luaL_prepbuffsize, B, sz); ++} ++SYMBOL_WRAP_DECL(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) { ++ SYMBOL_WRAP_CALL(luaL_addlstring, B, s, l); ++} ++SYMBOL_WRAP_DECL(void, luaL_addstring, luaL_Buffer *B, const char *s) { ++ SYMBOL_WRAP_CALL(luaL_addstring, B, s); ++} ++SYMBOL_WRAP_DECL(void, luaL_addvalue, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_addvalue, B); ++} ++SYMBOL_WRAP_DECL(void, luaL_pushresult, luaL_Buffer *B) { ++ SYMBOL_WRAP_CALL(luaL_pushresult, B); ++} ++SYMBOL_WRAP_DECL(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) { ++ SYMBOL_WRAP_CALL(luaL_pushresultsize, B, sz); ++} ++SYMBOL_WRAP_DECL(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) { ++ return SYMBOL_WRAP_CALL(luaL_buffinitsize, L, B, sz); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_base, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_base, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_coroutine, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_coroutine, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_table, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_table, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_io, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_io, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_os, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_os, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_string, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_string, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_utf8, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_utf8, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_math, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_math, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_debug, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_debug, L); ++} ++ ++SYMBOL_WRAP_DECL(int, luaopen_package, lua_State *L) { ++ return SYMBOL_WRAP_CALL(luaopen_package, L); ++} ++ ++SYMBOL_WRAP_DECL(void, luaL_openlibs, lua_State *L) { ++ SYMBOL_WRAP_CALL(luaL_openlibs, L); ++} ++ ++ ++ ++ ++ ++ ++#define IMPORT_SYMBOL(name, ret, ...) \ ++ __##name = (\ ++ (*(void **) (&__##name) = symbol(#name)), \ ++ __##name == NULL ? ((ret (*) (__VA_ARGS__)) &__lite_xl_fallback_##name) : __##name\ ++ ) ++ ++void lite_xl_plugin_init(void *XL) { ++ void* (*symbol)(const char *); ++ *(void **) (&symbol) = XL; ++ IMPORT_SYMBOL(lua_newstate, lua_State *, lua_Alloc f, void *ud); ++ IMPORT_SYMBOL(lua_close, void, lua_State *L); ++ IMPORT_SYMBOL(lua_newthread, lua_State *, lua_State *L); ++ IMPORT_SYMBOL(lua_resetthread, int, lua_State *L); ++ IMPORT_SYMBOL(lua_atpanic, lua_CFunction, lua_State *L, lua_CFunction panicf); ++ IMPORT_SYMBOL(lua_version, lua_Number, lua_State *L); ++ IMPORT_SYMBOL(lua_absindex, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_gettop, int, lua_State *L); ++ IMPORT_SYMBOL(lua_settop, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_pushvalue, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rotate, void, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_copy, void, lua_State *L, int fromidx, int toidx); ++ IMPORT_SYMBOL(lua_checkstack, int, lua_State *L, int sz); ++ IMPORT_SYMBOL(lua_xmove, void, lua_State *from, lua_State *to, int n); ++ IMPORT_SYMBOL(lua_isnumber, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isstring, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_iscfunction, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isinteger, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_isuserdata, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_type, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_typename, const char *, lua_State *L, int tp); ++ IMPORT_SYMBOL(lua_tonumberx, lua_Number, lua_State *L, int idx, int *isnum); ++ IMPORT_SYMBOL(lua_tointegerx, lua_Integer, lua_State *L, int idx, int *isnum); ++ IMPORT_SYMBOL(lua_toboolean, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tolstring, const char *, lua_State *L, int idx, size_t *len); ++ IMPORT_SYMBOL(lua_rawlen, lua_Unsigned, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tocfunction, lua_CFunction, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_touserdata, void *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_tothread, lua_State *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_topointer, const void *, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_arith, void, lua_State *L, int op); ++ IMPORT_SYMBOL(lua_rawequal, int, lua_State *L, int idx1, int idx2); ++ IMPORT_SYMBOL(lua_compare, int, lua_State *L, int idx1, int idx2, int op); ++ IMPORT_SYMBOL(lua_pushnil, void, lua_State *L); ++ IMPORT_SYMBOL(lua_pushnumber, void, lua_State *L, lua_Number n); ++ IMPORT_SYMBOL(lua_pushinteger, void, lua_State *L, lua_Integer n); ++ IMPORT_SYMBOL(lua_pushlstring, const char *, lua_State *L, const char *s, size_t l); ++ IMPORT_SYMBOL(lua_pushstring, const char *, lua_State *L, const char *s); ++ IMPORT_SYMBOL(lua_pushvfstring, const char *, lua_State *L, const char *fmt, va_list argp); ++ IMPORT_SYMBOL(lua_pushfstring, const char *, lua_State *L, const char *fmt, ...); ++ IMPORT_SYMBOL(lua_pushcclosure, void, lua_State *L, lua_CFunction fn, int n); ++ IMPORT_SYMBOL(lua_pushboolean, void, lua_State *L, int b); ++ IMPORT_SYMBOL(lua_pushlightuserdata, void, lua_State *L, void *p); ++ IMPORT_SYMBOL(lua_pushthread, int, lua_State *L); ++ IMPORT_SYMBOL(lua_getglobal, int, lua_State *L, const char *var); ++ IMPORT_SYMBOL(lua_gettable, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_getfield, int, lua_State *L, int idx, const char *k); ++ IMPORT_SYMBOL(lua_geti, int, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawget, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rawgeti, int, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawgetp, int, lua_State *L, int idx, const void *p); ++ IMPORT_SYMBOL(lua_createtable, void, lua_State *L, int narr, int nrec); ++ IMPORT_SYMBOL(lua_newuserdatauv, void *, lua_State *L, size_t sz, int nuvalue); ++ IMPORT_SYMBOL(lua_getmetatable, int, lua_State *L, int objindex); ++ IMPORT_SYMBOL(lua_getiuservalue, int, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_setglobal, void, lua_State *L, const char *var); ++ IMPORT_SYMBOL(lua_settable, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_setfield, void, lua_State *L, int idx, const char *k); ++ IMPORT_SYMBOL(lua_seti, void, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawset, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_rawseti, void, lua_State *L, int idx, lua_Integer n); ++ IMPORT_SYMBOL(lua_rawsetp, void, lua_State *L, int idx, const void *p); ++ IMPORT_SYMBOL(lua_setmetatable, int, lua_State *L, int objindex); ++ IMPORT_SYMBOL(lua_setiuservalue, int, lua_State *L, int idx, int n); ++ IMPORT_SYMBOL(lua_callk, void, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_pcallk, int, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_load, int, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode); ++ IMPORT_SYMBOL(lua_dump, int, lua_State *L, lua_Writer writer, void *data, int strip); ++ IMPORT_SYMBOL(lua_yieldk, int, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k); ++ IMPORT_SYMBOL(lua_resume, int, lua_State *L, lua_State *from, int narg, int *nres); ++ IMPORT_SYMBOL(lua_status, int, lua_State *L); ++ IMPORT_SYMBOL(lua_isyieldable, int, lua_State *L); ++ IMPORT_SYMBOL(lua_setwarnf, void, lua_State *L, lua_WarnFunction f, void *ud); ++ IMPORT_SYMBOL(lua_warning, void, lua_State *L, const char *msg, int tocont); ++ IMPORT_SYMBOL(lua_gc, int, lua_State *L, int what, ...); ++ IMPORT_SYMBOL(lua_error, int, lua_State *L); ++ IMPORT_SYMBOL(lua_next, int, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_concat, void, lua_State *L, int n); ++ IMPORT_SYMBOL(lua_len, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_stringtonumber, size_t, lua_State *L, const char *s); ++ IMPORT_SYMBOL(lua_getallocf, lua_Alloc, lua_State *L, void **ud); ++ IMPORT_SYMBOL(lua_setallocf, void, lua_State *L, lua_Alloc f, void *ud); ++ IMPORT_SYMBOL(lua_toclose, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_closeslot, void, lua_State *L, int idx); ++ IMPORT_SYMBOL(lua_getstack, int, lua_State *L, int level, lua_Debug *ar); ++ IMPORT_SYMBOL(lua_getinfo, int, lua_State *L, const char *what, lua_Debug *ar); ++ IMPORT_SYMBOL(lua_getlocal, const char *, lua_State *L, const lua_Debug *ar, int n); ++ IMPORT_SYMBOL(lua_setlocal, const char *, lua_State *L, const lua_Debug *ar, int n); ++ IMPORT_SYMBOL(lua_getupvalue, const char *, lua_State *L, int funcindex, int n); ++ IMPORT_SYMBOL(lua_setupvalue, const char *, lua_State *L, int funcindex, int n); ++ IMPORT_SYMBOL(lua_upvalueid, void *, lua_State *L, int fidx, int n); ++ IMPORT_SYMBOL(lua_upvaluejoin, void, lua_State *L, int fidx1, int n1, int fidx2, int n2); ++ IMPORT_SYMBOL(lua_sethook, void, lua_State *L, lua_Hook func, int mask, int count); ++ IMPORT_SYMBOL(lua_gethook, lua_Hook, lua_State *L); ++ IMPORT_SYMBOL(lua_gethookmask, int, lua_State *L); ++ IMPORT_SYMBOL(lua_gethookcount, int, lua_State *L); ++ IMPORT_SYMBOL(lua_setcstacklimit, int, lua_State *L, unsigned int limit); ++ IMPORT_SYMBOL(luaL_checkversion_, void, lua_State *L, lua_Number ver, size_t sz); ++ IMPORT_SYMBOL(luaL_getmetafield, int, lua_State *L, int obj, const char *e); ++ IMPORT_SYMBOL(luaL_callmeta, int, lua_State *L, int obj, const char *e); ++ IMPORT_SYMBOL(luaL_tolstring, const char *, lua_State *L, int idx, size_t *len); ++ IMPORT_SYMBOL(luaL_argerror, int, lua_State *L, int numarg, const char *extramsg); ++ IMPORT_SYMBOL(luaL_typeerror, int, lua_State *L, int arg, const char *tname); ++ IMPORT_SYMBOL(luaL_checklstring, const char *, lua_State *L, int numArg, size_t *l); ++ IMPORT_SYMBOL(luaL_optlstring, const char *, lua_State *L, int numArg, const char *def, size_t *l); ++ IMPORT_SYMBOL(luaL_checknumber, lua_Number, lua_State *L, int numArg); ++ IMPORT_SYMBOL(luaL_optnumber, lua_Number, lua_State *L, int nArg, lua_Number def); ++ IMPORT_SYMBOL(luaL_checkinteger, lua_Integer, lua_State *L, int numArg); ++ IMPORT_SYMBOL(luaL_optinteger, lua_Integer, lua_State *L, int nArg, lua_Integer def); ++ IMPORT_SYMBOL(luaL_checkstack, void, lua_State *L, int sz, const char *msg); ++ IMPORT_SYMBOL(luaL_checktype, void, lua_State *L, int narg, int t); ++ IMPORT_SYMBOL(luaL_checkany, void, lua_State *L, int narg); ++ IMPORT_SYMBOL(luaL_newmetatable, int, lua_State *L, const char *tname); ++ IMPORT_SYMBOL(luaL_setmetatable, void, lua_State *L, const char *tname); ++ IMPORT_SYMBOL(luaL_testudata, void *, lua_State *L, int ud, const char *tname); ++ IMPORT_SYMBOL(luaL_checkudata, void *, lua_State *L, int ud, const char *tname); ++ IMPORT_SYMBOL(luaL_where, void, lua_State *L, int lvl); ++ IMPORT_SYMBOL(luaL_error, int, lua_State *L, const char *fmt, ...); ++ IMPORT_SYMBOL(luaL_checkoption, int, lua_State *L, int narg, const char *def, const char *const lst[]); ++ IMPORT_SYMBOL(luaL_fileresult, int, lua_State *L, int stat, const char *fname); ++ IMPORT_SYMBOL(luaL_execresult, int, lua_State *L, int stat); ++ IMPORT_SYMBOL(luaL_ref, int, lua_State *L, int t); ++ IMPORT_SYMBOL(luaL_unref, void, lua_State *L, int t, int ref); ++ IMPORT_SYMBOL(luaL_loadfilex, int, lua_State *L, const char *filename, const char *mode); ++ IMPORT_SYMBOL(luaL_loadbufferx, int, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); ++ IMPORT_SYMBOL(luaL_loadstring, int, lua_State *L, const char *s); ++ IMPORT_SYMBOL(luaL_newstate, lua_State *, void); ++ IMPORT_SYMBOL(luaL_len, lua_Integer, lua_State *L, int idx); ++ IMPORT_SYMBOL(luaL_addgsub, void, luaL_Buffer *b, const char *s, const char *p, const char *r); ++ IMPORT_SYMBOL(luaL_gsub, const char *, lua_State *L, const char *s, const char *p, const char *r); ++ IMPORT_SYMBOL(luaL_setfuncs, void, lua_State *L, const luaL_Reg *l, int nup); ++ IMPORT_SYMBOL(luaL_getsubtable, int, lua_State *L, int idx, const char *fname); ++ IMPORT_SYMBOL(luaL_traceback, void, lua_State *L, lua_State *L1, const char *msg, int level); ++ IMPORT_SYMBOL(luaL_requiref, void, lua_State *L, const char *modname, lua_CFunction openf, int glb); ++ IMPORT_SYMBOL(luaL_buffinit, void, lua_State *L, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_prepbuffsize, char *, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaL_addlstring, void, luaL_Buffer *B, const char *s, size_t l); ++ IMPORT_SYMBOL(luaL_addstring, void, luaL_Buffer *B, const char *s); ++ IMPORT_SYMBOL(luaL_addvalue, void, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_pushresult, void, luaL_Buffer *B); ++ IMPORT_SYMBOL(luaL_pushresultsize, void, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaL_buffinitsize, char *, lua_State *L, luaL_Buffer *B, size_t sz); ++ IMPORT_SYMBOL(luaopen_base, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_coroutine, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_table, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_io, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_os, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_string, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_utf8, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_math, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_debug, int, lua_State *L); ++ IMPORT_SYMBOL(luaopen_package, int, lua_State *L); ++ IMPORT_SYMBOL(luaL_openlibs, void, lua_State* L); ++} ++ ++#undef IMPORT_SYMBOL ++#undef IMPORT_SYMBOL_OPT ++ ++#else /* LITE_XL_PLUGIN_ENTRYPOINT */ ++ ++void lite_xl_plugin_init(void *XL); ++ ++#endif /* LITE_XL_PLUGIN_ENTRYPOINT */ ++ ++#undef LITE_XL_API ++#undef SYMBOL_WRAP_DECL ++#undef SYMBOL_WRAP_CALL ++#undef SYMBOL_WRAP_CALL_FB ++#undef SYMBOL_DECLARE ++#undef SYMBOL_DECLARE_VARARG ++#undef UNUSED ++#undef CONCAT ++#undef CONCAT1 ++#undef CONCAT2 ++#undef FE_1 ++#undef FE_2 ++#undef FE_3 ++#undef FE_4 ++#undef FE_5 ++#undef FE_6 ++#undef FE_7 ++#undef FE_8 ++#undef FOR_EACH_NARG ++#undef FOR_EACH_NARG_ ++#undef FOR_EACH_ARG_N ++#undef FOR_EACH_RSEQ_N ++#undef FOR_EACH_ ++#undef FOR_EACH ++ ++#endif /* LITE_XL_PLUGIN_API */ ++ ++/****************************************************************************** ++* Copyright (C) 1994-2023 Lua.org, PUC-Rio; Lite XL contributors. ++* ++* Permission is hereby granted, free of charge, to any person obtaining ++* a copy of this software and associated documentation files (the ++* "Software"), to deal in the Software without restriction, including ++* without limitation the rights to use, copy, modify, merge, publish, ++* distribute, sublicense, and/or sell copies of the Software, and to ++* permit persons to whom the Software is furnished to do so, subject to ++* the following conditions: ++* ++* The above copyright notice and this permission notice shall be ++* included in all copies or substantial portions of the Software. ++* ++* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ++* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ++* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ++* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ++* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ++* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ++* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++******************************************************************************/ +\ No newline at end of file +diff --git a/resources/lite_xl_plugin_api.h b/resources/lite_xl_plugin_api.h +deleted file mode 100644 +index 8bf74054..00000000 +--- a/resources/lite_xl_plugin_api.h ++++ /dev/null +@@ -1,1124 +0,0 @@ +-#ifndef LITE_XL_PLUGIN_API +-#define LITE_XL_PLUGIN_API +-/** +-The lite_xl plugin API is quite simple. Any shared library can be a plugin file, so long +-as it has an entrypoint that looks like the following, where xxxxx is the plugin name: +- +-#define LITE_XL_PLUGIN_ENTRYPOINT +-#include "lite_xl_plugin_api.h" +-int luaopen_lite_xl_xxxxx(lua_State* L, void* XL) { +- lite_xl_plugin_init(XL); +- ... +- return 1; +-} +- +-NOTE: `#define LITE_XL_PLUGIN_ENTRYPOINT` needs to be defined only on the +-source file where the lite_xl_plugin_init() initialization function is called. +- +-In linux, to compile this file, you'd do: 'gcc -o xxxxx.so -shared xxxxx.c'. Simple! +-Due to the way the API is structured, you *should not* link or include lua libraries. +-This file was automatically generated. DO NOT MODIFY DIRECTLY. +- +-UNLESS you're us, and you had to modify this file manually to get it ready for 2.1. +- +-Go figure. +- +-**/ +- +- +-#include +-#include // for BUFSIZ? this is kinda weird +-#include +- +-#define SYMBOL_WRAP_DECL(ret, name, ...) \ +- ret name(__VA_ARGS__) +- +-#define SYMBOL_WRAP_CALL(name, ...) \ +- return __##name(__VA_ARGS__) +- +-#define SYMBOL_WRAP_CALL_FB(name, ...) \ +- return __lite_xl_fallback_##name(__VA_ARGS__) +- +-#ifdef LITE_XL_PLUGIN_ENTRYPOINT +- #define SYMBOL_DECLARE(ret, name, ...) \ +- static ret (*__##name) (__VA_ARGS__); \ +- SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); \ +- static ret __lite_xl_fallback_##name(__VA_ARGS__) { \ +- fputs("warning: " #name " is a stub", stderr); \ +- exit(1); \ +- } +-#else +- #define SYMBOL_DECLARE(ret, name, ...) \ +- SYMBOL_WRAP_DECL(ret, name, __VA_ARGS__); +-#endif +- +-/** luaconf.h **/ +- +-#ifndef lconfig_h +-#define lconfig_h +-#include +-#include +-#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__) +-#define LUA_ANSI +-#endif +-#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) +-#define LUA_WIN +-#endif +-#if defined(LUA_WIN) +-#define LUA_DL_DLL +-#define LUA_USE_AFORMAT +-#endif +-#if defined(LUA_USE_LINUX) +-#define LUA_USE_POSIX +-#define LUA_USE_DLOPEN +-#define LUA_USE_READLINE +-#define LUA_USE_STRTODHEX +-#define LUA_USE_AFORMAT +-#define LUA_USE_LONGLONG +-#endif +-#if defined(LUA_USE_MACOSX) +-#define LUA_USE_POSIX +-#define LUA_USE_DLOPEN +-#define LUA_USE_READLINE +-#define LUA_USE_STRTODHEX +-#define LUA_USE_AFORMAT +-#define LUA_USE_LONGLONG +-#endif +-#if defined(LUA_USE_POSIX) +-#define LUA_USE_MKSTEMP +-#define LUA_USE_ISATTY +-#define LUA_USE_POPEN +-#define LUA_USE_ULONGJMP +-#define LUA_USE_GMTIME_R +-#endif +-#if defined(_WIN32) +-#define LUA_LDIR "!\\lua\\" +-#define LUA_CDIR "!\\" +-#define LUA_PATH_DEFAULT LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua" +-#define LUA_CPATH_DEFAULT LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll" +-#else +-#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/" +-#define LUA_ROOT "/usr/local/" +-#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR +-#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR +-#define LUA_PATH_DEFAULT LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua" +-#define LUA_CPATH_DEFAULT LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so" +-#endif +-#if defined(_WIN32) +-#define LUA_DIRSEP "\\" +-#else +-#define LUA_DIRSEP "/" +-#endif +-#define LUA_ENV "_ENV" +-#if defined(LUA_BUILD_AS_DLL) +-#if defined(LUA_CORE) || defined(LUA_LIB) +-#define LUA_API __declspec(dllexport) +-#else +-#define LUA_API __declspec(dllimport) +-#endif +-#else +-#define LUA_API extern +-#endif +-#define LUALIB_API LUA_API +-#define LUAMOD_API LUALIB_API +-#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && defined(__ELF__) +-#define LUAI_FUNC __attribute__((visibility("hidden"))) extern +-#define LUAI_DDEC LUAI_FUNC +-#define LUAI_DDEF +-#else +-#define LUAI_FUNC extern +-#define LUAI_DDEC extern +-#define LUAI_DDEF +-#endif +-#define LUA_QL(x) "'" x "'" +-#define LUA_QS LUA_QL("%s") +-#define LUA_IDSIZE 60 +-#if defined(LUA_LIB) || defined(lua_c) +-#include +-#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +-#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) +-#endif +-#define luai_writestringerror(s,p) (fprintf(stderr, (s), (p)), fflush(stderr)) +-#define LUAI_MAXSHORTLEN 40 +-#if defined(LUA_COMPAT_ALL) +-#define LUA_COMPAT_UNPACK +-#define LUA_COMPAT_LOADERS +-#define lua_cpcall(L,f,u) (lua_pushcfunction(L, (f)), lua_pushlightuserdata(L,(u)), lua_pcall(L,1,0,0)) +-#define LUA_COMPAT_LOG10 +-#define LUA_COMPAT_LOADSTRING +-#define LUA_COMPAT_MAXN +-#define lua_strlen(L,i) lua_rawlen(L, (i)) +-#define lua_objlen(L,i) lua_rawlen(L, (i)) +-#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ) +-#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT) +-#define LUA_COMPAT_MODULE +-#endif +-#if INT_MAX-20 < 32760 +-#define LUAI_BITSINT 16 +-#elif INT_MAX > 2147483640L +-#define LUAI_BITSINT 32 +-#else +-#error "you must define LUA_BITSINT with number of bits in an integer" +-#endif +-#if LUAI_BITSINT >= 32 +-#define LUA_INT32 int +-#define LUAI_UMEM size_t +-#define LUAI_MEM ptrdiff_t +-#else +-#define LUA_INT32 long +-#define LUAI_UMEM unsigned long +-#define LUAI_MEM long +-#endif +-#if LUAI_BITSINT >= 32 +-#define LUAI_MAXSTACK 1000000 +-#else +-#define LUAI_MAXSTACK 15000 +-#endif +-#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) +-#define LUAL_BUFFERSIZE BUFSIZ +-#define LUA_NUMBER_DOUBLE +-#define LUA_NUMBER double +-#define LUAI_UACNUMBER double +-#define LUA_NUMBER_SCAN "%lf" +-#define LUA_NUMBER_FMT "%.14g" +-#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) +-#define LUAI_MAXNUMBER2STR 32 +-#define l_mathop(x) (x) +-#define lua_str2number(s,p) strtod((s), (p)) +-#if defined(LUA_USE_STRTODHEX) +-#define lua_strx2number(s,p) strtod((s), (p)) +-#endif +-#if defined(lobject_c) || defined(lvm_c) +-#include +-#define luai_nummod(L,a,b) ((a) - l_mathop(floor)((a)/(b))*(b)) +-#define luai_numpow(L,a,b) (l_mathop(pow)(a,b)) +-#endif +-#if defined(LUA_CORE) +-#define luai_numadd(L,a,b) ((a)+(b)) +-#define luai_numsub(L,a,b) ((a)-(b)) +-#define luai_nummul(L,a,b) ((a)*(b)) +-#define luai_numdiv(L,a,b) ((a)/(b)) +-#define luai_numunm(L,a) (-(a)) +-#define luai_numeq(a,b) ((a)==(b)) +-#define luai_numlt(L,a,b) ((a)<(b)) +-#define luai_numle(L,a,b) ((a)<=(b)) +-#define luai_numisnan(L,a) (!luai_numeq((a), (a))) +-#endif +-#define LUA_INTEGER ptrdiff_t +-#define LUA_KCONTEXT ptrdiff_t +-#define LUA_UNSIGNED unsigned LUA_INT32 +-#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) +-#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86) +-#define LUA_MSASMTRICK +-#define LUA_IEEEENDIAN 0 +-#define LUA_NANTRICK +-#elif defined(__i386__) || defined(__i386) || defined(__X86__) +-#define LUA_IEEE754TRICK +-#define LUA_IEEELL +-#define LUA_IEEEENDIAN 0 +-#define LUA_NANTRICK +-#elif defined(__x86_64) +-#define LUA_IEEE754TRICK +-#define LUA_IEEEENDIAN 0 +-#elif defined(__POWERPC__) || defined(__ppc__) +-#define LUA_IEEE754TRICK +-#define LUA_IEEEENDIAN 1 +-#else +-#define LUA_IEEE754TRICK +-#endif +-#endif +-#endif +- +-/** lua.h **/ +- +-typedef struct lua_State lua_State; +-typedef int (*lua_CFunction) (lua_State *L); +-typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); +-typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); +-typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); +-typedef LUA_KCONTEXT lua_KContext; +-typedef LUA_NUMBER lua_Number; +-typedef LUA_INTEGER lua_Integer; +-typedef LUA_UNSIGNED lua_Unsigned; +-typedef struct lua_Debug lua_Debug; +-typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); +-typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); +-struct lua_Debug { +- int event; +- const char *name; +- const char *namewhat; +- const char *what; +- const char *source; +- int currentline; +- int linedefined; +- int lastlinedefined; +- unsigned char nups; +- unsigned char nparams; +- char isvararg; +- char istailcall; +- char short_src[LUA_IDSIZE]; +- struct CallInfo *i_ci; +-}; +- +-SYMBOL_DECLARE(lua_State *, lua_newstate, lua_Alloc f, void *ud) +-SYMBOL_DECLARE(void, lua_close, lua_State *L) +-SYMBOL_DECLARE(lua_State *, lua_newthread, lua_State *L) +-SYMBOL_DECLARE(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf) +-SYMBOL_DECLARE(const lua_Number *, lua_version, lua_State *L) +-SYMBOL_DECLARE(int, lua_absindex, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_gettop, lua_State *L) +-SYMBOL_DECLARE(void, lua_settop, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_pushvalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_copy, lua_State *L, int fromidx, int toidx) +-SYMBOL_DECLARE(int, lua_checkstack, lua_State *L, int sz) +-SYMBOL_DECLARE(void, lua_xmove, lua_State *from, lua_State *to, int n) +-SYMBOL_DECLARE(int, lua_isnumber, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_isstring, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_iscfunction, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_isuserdata, lua_State *L, int idx) +-SYMBOL_DECLARE(int, lua_type, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, lua_typename, lua_State *L, int tp) +-SYMBOL_DECLARE(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(lua_Unsigned, lua_tounsignedx, lua_State *L, int idx, int *isnum) +-SYMBOL_DECLARE(int, lua_toboolean, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, lua_tolstring, lua_State *L, int idx, size_t *len) +-SYMBOL_DECLARE(size_t, lua_rawlen, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_CFunction, lua_tocfunction, lua_State *L, int idx) +-SYMBOL_DECLARE(void *, lua_touserdata, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_State *, lua_tothread, lua_State *L, int idx) +-SYMBOL_DECLARE(const void *, lua_topointer, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_arith, lua_State *L, int op) +-SYMBOL_DECLARE(int, lua_rawequal, lua_State *L, int idx1, int idx2) +-SYMBOL_DECLARE(int, lua_compare, lua_State *L, int idx1, int idx2, int op) +-SYMBOL_DECLARE(void, lua_pushnil, lua_State *L) +-SYMBOL_DECLARE(void, lua_pushnumber, lua_State *L, lua_Number n) +-SYMBOL_DECLARE(void, lua_pushinteger, lua_State *L, lua_Integer n) +-SYMBOL_DECLARE(void, lua_pushunsigned, lua_State *L, lua_Unsigned n) +-SYMBOL_DECLARE(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l) +-SYMBOL_DECLARE(const char *, lua_pushstring, lua_State *L, const char *s) +-SYMBOL_DECLARE(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp) +-SYMBOL_DECLARE(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...) +-SYMBOL_DECLARE(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n) +-SYMBOL_DECLARE(void, lua_pushboolean, lua_State *L, int b) +-SYMBOL_DECLARE(void, lua_pushlightuserdata, lua_State *L, void *p) +-SYMBOL_DECLARE(int, lua_pushthread, lua_State *L) +-SYMBOL_DECLARE(void, lua_getglobal, lua_State *L, const char *var) +-SYMBOL_DECLARE(void, lua_gettable, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_getfield, lua_State *L, int idx, const char *k) +-SYMBOL_DECLARE(void, lua_rawget, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_rawgeti, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_rawgetp, lua_State *L, int idx, const void *p) +-SYMBOL_DECLARE(void, lua_createtable, lua_State *L, int narr, int nrec) +-SYMBOL_DECLARE(void *, lua_newuserdata, lua_State *L, size_t sz) +-SYMBOL_DECLARE(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue) +-SYMBOL_DECLARE(int, lua_getmetatable, lua_State *L, int objindex) +-SYMBOL_DECLARE(void, lua_getuservalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_getiuservalue, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_setglobal, lua_State *L, const char *var) +-SYMBOL_DECLARE(void, lua_settable, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_setfield, lua_State *L, int idx, const char *k) +-SYMBOL_DECLARE(void, lua_rawset, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_rawseti, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_rawsetp, lua_State *L, int idx, const void *p) +-SYMBOL_DECLARE(int, lua_setmetatable, lua_State *L, int objindex) +-SYMBOL_DECLARE(void, lua_setuservalue, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_setiuservalue, lua_State *L, int idx, int n) +-SYMBOL_DECLARE(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_getctx, lua_State *L, int *ctx) +-SYMBOL_DECLARE(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode) +-SYMBOL_DECLARE(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip) +-SYMBOL_DECLARE(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k) +-SYMBOL_DECLARE(int, lua_resume, lua_State *L, lua_State *from, int narg) +-SYMBOL_DECLARE(int, lua_status, lua_State *L) +-SYMBOL_DECLARE(int, lua_gc, lua_State *L, int what, int data) +-SYMBOL_DECLARE(int, lua_error, lua_State *L) +-SYMBOL_DECLARE(int, lua_next, lua_State *L, int idx) +-SYMBOL_DECLARE(void, lua_concat, lua_State *L, int n) +-SYMBOL_DECLARE(void, lua_len, lua_State *L, int idx) +-SYMBOL_DECLARE(lua_Alloc, lua_getallocf, lua_State *L, void **ud) +-SYMBOL_DECLARE(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud) +-SYMBOL_DECLARE(int, lua_getstack, lua_State *L, int level, lua_Debug *ar) +-SYMBOL_DECLARE(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar) +-SYMBOL_DECLARE(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n) +-SYMBOL_DECLARE(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n) +-SYMBOL_DECLARE(const char *, lua_getupvalue, lua_State *L, int funcindex, int n) +-SYMBOL_DECLARE(const char *, lua_setupvalue, lua_State *L, int funcindex, int n) +-SYMBOL_DECLARE(void *, lua_upvalueid, lua_State *L, int fidx, int n) +-SYMBOL_DECLARE(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2) +-SYMBOL_DECLARE(int, lua_sethook, lua_State *L, lua_Hook func, int mask, int count) +-SYMBOL_DECLARE(lua_Hook, lua_gethook, lua_State *L) +-SYMBOL_DECLARE(int, lua_gethookmask, lua_State *L) +-SYMBOL_DECLARE(int, lua_gethookcount, lua_State *L) +- +-#define lua_h +-#define LUA_VERSION_MAJOR "5" +-#define LUA_VERSION_MINOR "4" +-#define LUA_VERSION_NUM 504 +-#define LUA_VERSION_RELEASE "4" +-#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR +-#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE +-#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2015 Lua.org, PUC-Rio" +-#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes" +-#define LUA_SIGNATURE "\033Lua" +-#define LUA_MULTRET (-1) +-#define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX +-#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i)) +-#define LUA_OK 0 +-#define LUA_YIELD 1 +-#define LUA_ERRRUN 2 +-#define LUA_ERRSYNTAX 3 +-#define LUA_ERRMEM 4 +-#define LUA_ERRGCMM 5 +-#define LUA_ERRERR 6 +-#define LUA_TNONE (-1) +-#define LUA_TNIL 0 +-#define LUA_TBOOLEAN 1 +-#define LUA_TLIGHTUSERDATA 2 +-#define LUA_TNUMBER 3 +-#define LUA_TSTRING 4 +-#define LUA_TTABLE 5 +-#define LUA_TFUNCTION 6 +-#define LUA_TUSERDATA 7 +-#define LUA_TTHREAD 8 +-#define LUA_NUMTAGS 9 +-#define LUA_MINSTACK 20 +-#define LUA_RIDX_MAINTHREAD 1 +-#define LUA_RIDX_GLOBALS 2 +-#define LUA_RIDX_LAST LUA_RIDX_GLOBALS +-#define LUA_OPADD 0 +-#define LUA_OPSUB 1 +-#define LUA_OPMUL 2 +-#define LUA_OPDIV 3 +-#define LUA_OPMOD 4 +-#define LUA_OPPOW 5 +-#define LUA_OPUNM 6 +-#define LUA_OPEQ 0 +-#define LUA_OPLT 1 +-#define LUA_OPLE 2 +-#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL) +-#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) +-#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) +-#define LUA_GCSTOP 0 +-#define LUA_GCRESTART 1 +-#define LUA_GCCOLLECT 2 +-#define LUA_GCCOUNT 3 +-#define LUA_GCCOUNTB 4 +-#define LUA_GCSTEP 5 +-#define LUA_GCSETPAUSE 6 +-#define LUA_GCSETSTEPMUL 7 +-#define LUA_GCSETMAJORINC 8 +-#define LUA_GCISRUNNING 9 +-#define LUA_GCGEN 10 +-#define LUA_GCINC 11 +-#define lua_tonumber(L,i) lua_tonumberx(L,i,NULL) +-#define lua_tointeger(L,i) lua_tointegerx(L,i,NULL) +-#define lua_tounsigned(L,i) lua_tounsignedx(L,i,NULL) +-#define lua_pop(L,n) lua_settop(L, -(n)-1) +-#define lua_newtable(L) lua_createtable(L, 0, 0) +-#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) +-#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) +-#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) +-#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) +-#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) +-#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) +-#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) +-#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) +-#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) +-#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) +-#define lua_pushliteral(L, s) lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) +-#define lua_pushglobaltable(L) lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS) +-#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) +-#define lua_insert(L,idx) lua_rotate(L, (idx), 1) +-#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1)) +-#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1)) +-#define LUA_HOOKCALL 0 +-#define LUA_HOOKRET 1 +-#define LUA_HOOKLINE 2 +-#define LUA_HOOKCOUNT 3 +-#define LUA_HOOKTAILCALL 4 +-#define LUA_MASKCALL (1 << LUA_HOOKCALL) +-#define LUA_MASKRET (1 << LUA_HOOKRET) +-#define LUA_MASKLINE (1 << LUA_HOOKLINE) +-#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) +- +-/** lauxlib.h **/ +- +-typedef struct luaL_Reg { +- const char *name; +- lua_CFunction func; +-} luaL_Reg; +-typedef struct luaL_Buffer { +- char *b; +- size_t size; +- size_t n; +- lua_State *L; +- char initb[LUAL_BUFFERSIZE]; +-} luaL_Buffer; +-typedef struct luaL_Stream { +- FILE *f; +- lua_CFunction closef; +-} luaL_Stream; +- +-SYMBOL_DECLARE(void, luaL_checkversion_, lua_State *L, lua_Number ver) +-SYMBOL_DECLARE(int, luaL_getmetafield, lua_State *L, int obj, const char *e) +-SYMBOL_DECLARE(int, luaL_callmeta, lua_State *L, int obj, const char *e) +-SYMBOL_DECLARE(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len) +-SYMBOL_DECLARE(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg) +-SYMBOL_DECLARE(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l) +-SYMBOL_DECLARE(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l) +-SYMBOL_DECLARE(lua_Number, luaL_checknumber, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def) +-SYMBOL_DECLARE(lua_Integer, luaL_checkinteger, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def) +-SYMBOL_DECLARE(lua_Unsigned, luaL_checkunsigned, lua_State *L, int numArg) +-SYMBOL_DECLARE(lua_Unsigned, luaL_optunsigned, lua_State *L, int numArg, lua_Unsigned def) +-SYMBOL_DECLARE(void, luaL_checkstack, lua_State *L, int sz, const char *msg) +-SYMBOL_DECLARE(void, luaL_checktype, lua_State *L, int narg, int t) +-SYMBOL_DECLARE(void, luaL_checkany, lua_State *L, int narg) +-SYMBOL_DECLARE(int, luaL_newmetatable, lua_State *L, const char *tname) +-SYMBOL_DECLARE(void, luaL_setmetatable, lua_State *L, const char *tname) +-SYMBOL_DECLARE(void *, luaL_testudata, lua_State *L, int ud, const char *tname) +-SYMBOL_DECLARE(void *, luaL_checkudata, lua_State *L, int ud, const char *tname) +-SYMBOL_DECLARE(void, luaL_where, lua_State *L, int lvl) +-SYMBOL_DECLARE(int, luaL_error, lua_State *L, const char *fmt, ...) +-SYMBOL_DECLARE(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]) +-SYMBOL_DECLARE(int, luaL_fileresult, lua_State *L, int stat, const char *fname) +-SYMBOL_DECLARE(int, luaL_execresult, lua_State *L, int stat) +-SYMBOL_DECLARE(int, luaL_ref, lua_State *L, int t) +-SYMBOL_DECLARE(void, luaL_unref, lua_State *L, int t, int ref) +-SYMBOL_DECLARE(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode) +-SYMBOL_DECLARE(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode) +-SYMBOL_DECLARE(int, luaL_loadstring, lua_State *L, const char *s) +-SYMBOL_DECLARE(lua_State *, luaL_newstate, void) +-SYMBOL_DECLARE(int, luaL_len, lua_State *L, int idx) +-SYMBOL_DECLARE(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r) +-SYMBOL_DECLARE(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup) +-SYMBOL_DECLARE(int, luaL_getsubtable, lua_State *L, int idx, const char *fname) +-SYMBOL_DECLARE(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level) +-SYMBOL_DECLARE(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb) +-SYMBOL_DECLARE(void, luaL_buffinit, lua_State *L, luaL_Buffer *B) +-SYMBOL_DECLARE(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l) +-SYMBOL_DECLARE(void, luaL_addstring, luaL_Buffer *B, const char *s) +-SYMBOL_DECLARE(void, luaL_addvalue, luaL_Buffer *B) +-SYMBOL_DECLARE(void, luaL_pushresult, luaL_Buffer *B) +-SYMBOL_DECLARE(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz) +-SYMBOL_DECLARE(void, luaL_openlibs, lua_State *L) +- +-#define lauxlib_h +-#define LUA_ERRFILE (LUA_ERRERR+1) +-#define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM) +-#define LUA_NOREF (-2) +-#define LUA_REFNIL (-1) +-#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL) +-#define luaL_newlibtable(L,l) lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) +-#define luaL_newlib(L,l) (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) +-#define luaL_argcheck(L, cond,numarg,extramsg) ((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) +-#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) +-#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) +-#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) +-#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) +-#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) +-#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) +-#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) +-#define luaL_dofile(L, fn) (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) +-#define luaL_dostring(L, s) (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) +-#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) +-#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) +-#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL) +-#define luaL_addchar(B,c) ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), ((B)->b[(B)->n++] = (c))) +-#define luaL_addsize(B,s) ((B)->n += (s)) +-#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE) +-#define LUA_FILEHANDLE "FILE*" +- +-#ifdef LITE_XL_PLUGIN_ENTRYPOINT +- +-SYMBOL_WRAP_DECL(lua_State *, lua_newstate, lua_Alloc f, void *ud){ +- SYMBOL_WRAP_CALL(lua_newstate, f, ud); +-} +-SYMBOL_WRAP_DECL(void, lua_close, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_close, L); +-} +-SYMBOL_WRAP_DECL(lua_State *, lua_newthread, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_newthread, L); +-} +-SYMBOL_WRAP_DECL(lua_CFunction, lua_atpanic, lua_State *L, lua_CFunction panicf){ +- SYMBOL_WRAP_CALL(lua_atpanic, L, panicf); +-} +-SYMBOL_WRAP_DECL(const lua_Number *, lua_version, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_version, L); +-} +-SYMBOL_WRAP_DECL(int, lua_absindex, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_absindex, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_gettop, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gettop, L); +-} +-SYMBOL_WRAP_DECL(void, lua_settop, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_settop, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_pushvalue, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_pushvalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_copy, lua_State *L, int fromidx, int toidx){ +- SYMBOL_WRAP_CALL(lua_copy, L, fromidx, toidx); +-} +-SYMBOL_WRAP_DECL(int, lua_checkstack, lua_State *L, int sz){ +- SYMBOL_WRAP_CALL(lua_checkstack, L, sz); +-} +-SYMBOL_WRAP_DECL(void, lua_xmove, lua_State *from, lua_State *to, int n){ +- SYMBOL_WRAP_CALL(lua_xmove, from, to, n); +-} +-SYMBOL_WRAP_DECL(int, lua_isnumber, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isnumber, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_isstring, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isstring, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_iscfunction, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_iscfunction, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_isuserdata, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_isuserdata, L, idx); +-} +-SYMBOL_WRAP_DECL(int, lua_type, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_type, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, lua_typename, lua_State *L, int tp){ +- SYMBOL_WRAP_CALL(lua_typename, L, tp); +-} +-SYMBOL_WRAP_DECL(lua_Number, lua_tonumberx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tonumberx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(lua_Integer, lua_tointegerx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tointegerx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, lua_tounsignedx, lua_State *L, int idx, int *isnum){ +- SYMBOL_WRAP_CALL(lua_tounsignedx, L, idx, isnum); +-} +-SYMBOL_WRAP_DECL(int, lua_toboolean, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_toboolean, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, lua_tolstring, lua_State *L, int idx, size_t *len){ +- SYMBOL_WRAP_CALL(lua_tolstring, L, idx, len); +-} +-SYMBOL_WRAP_DECL(size_t, lua_rawlen, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawlen, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_CFunction, lua_tocfunction, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_tocfunction, L, idx); +-} +-SYMBOL_WRAP_DECL(void *, lua_touserdata, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_touserdata, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_State *, lua_tothread, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_tothread, L, idx); +-} +-SYMBOL_WRAP_DECL(const void *, lua_topointer, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_topointer, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_arith, lua_State *L, int op){ +- SYMBOL_WRAP_CALL(lua_arith, L, op); +-} +-SYMBOL_WRAP_DECL(int, lua_rawequal, lua_State *L, int idx1, int idx2){ +- SYMBOL_WRAP_CALL(lua_rawequal, L, idx1, idx2); +-} +-SYMBOL_WRAP_DECL(int, lua_compare, lua_State *L, int idx1, int idx2, int op){ +- SYMBOL_WRAP_CALL(lua_compare, L, idx1, idx2, op); +-} +-SYMBOL_WRAP_DECL(void, lua_pushnil, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_pushnil, L); +-} +-SYMBOL_WRAP_DECL(void, lua_pushnumber, lua_State *L, lua_Number n){ +- SYMBOL_WRAP_CALL(lua_pushnumber, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushinteger, lua_State *L, lua_Integer n){ +- SYMBOL_WRAP_CALL(lua_pushinteger, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushunsigned, lua_State *L, lua_Unsigned n){ +- SYMBOL_WRAP_CALL(lua_pushunsigned, L, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushlstring, lua_State *L, const char *s, size_t l){ +- SYMBOL_WRAP_CALL(lua_pushlstring, L, s, l); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushstring, lua_State *L, const char *s){ +- SYMBOL_WRAP_CALL(lua_pushstring, L, s); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushvfstring, lua_State *L, const char *fmt, va_list argp){ +- SYMBOL_WRAP_CALL(lua_pushvfstring, L, fmt, argp); +-} +-SYMBOL_WRAP_DECL(const char *, lua_pushfstring, lua_State *L, const char *fmt, ...){ +- SYMBOL_WRAP_CALL(lua_pushfstring, L, fmt); +-} +-SYMBOL_WRAP_DECL(void, lua_pushcclosure, lua_State *L, lua_CFunction fn, int n){ +- SYMBOL_WRAP_CALL(lua_pushcclosure, L, fn, n); +-} +-SYMBOL_WRAP_DECL(void, lua_pushboolean, lua_State *L, int b){ +- SYMBOL_WRAP_CALL(lua_pushboolean, L, b); +-} +-SYMBOL_WRAP_DECL(void, lua_pushlightuserdata, lua_State *L, void *p){ +- SYMBOL_WRAP_CALL(lua_pushlightuserdata, L, p); +-} +-SYMBOL_WRAP_DECL(int, lua_pushthread, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_pushthread, L); +-} +-SYMBOL_WRAP_DECL(void, lua_getglobal, lua_State *L, const char *var){ +- SYMBOL_WRAP_CALL(lua_getglobal, L, var); +-} +-SYMBOL_WRAP_DECL(void, lua_gettable, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_gettable, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_getfield, lua_State *L, int idx, const char *k){ +- SYMBOL_WRAP_CALL(lua_getfield, L, idx, k); +-} +-SYMBOL_WRAP_DECL(void, lua_rawget, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawget, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_rawgeti, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_rawgeti, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_rawgetp, lua_State *L, int idx, const void *p){ +- SYMBOL_WRAP_CALL(lua_rawgetp, L, idx, p); +-} +-SYMBOL_WRAP_DECL(void, lua_createtable, lua_State *L, int narr, int nrec){ +- SYMBOL_WRAP_CALL(lua_createtable, L, narr, nrec); +-} +-SYMBOL_WRAP_DECL(void *, lua_newuserdata, lua_State *L, size_t sz){ +- if (__lua_newuserdatauv != NULL) { +- return lua_newuserdatauv(L, sz, 1); +- } else if (__lua_newuserdata != NULL) { +- SYMBOL_WRAP_CALL(lua_newuserdata, L, sz); +- } +- SYMBOL_WRAP_CALL_FB(lua_newuserdata, L, sz); +-} +-SYMBOL_WRAP_DECL(void *, lua_newuserdatauv, lua_State *L, size_t sz, int nuvalue){ +- SYMBOL_WRAP_CALL(lua_newuserdatauv, L, sz, nuvalue); +-} +-SYMBOL_WRAP_DECL(int, lua_getmetatable, lua_State *L, int objindex){ +- SYMBOL_WRAP_CALL(lua_getmetatable, L, objindex); +-} +-SYMBOL_WRAP_DECL(void, lua_getuservalue, lua_State *L, int idx){ +- if (__lua_getiuservalue != NULL) { +- return lua_getiuservalue(L, idx, 1); +- } else if (__lua_getuservalue != NULL) { +- SYMBOL_WRAP_CALL(lua_getuservalue, L, idx); +- } +- SYMBOL_WRAP_CALL_FB(lua_getuservalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_getiuservalue, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_getiuservalue, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_setglobal, lua_State *L, const char *var){ +- SYMBOL_WRAP_CALL(lua_setglobal, L, var); +-} +-SYMBOL_WRAP_DECL(void, lua_settable, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_settable, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_setfield, lua_State *L, int idx, const char *k){ +- SYMBOL_WRAP_CALL(lua_setfield, L, idx, k); +-} +-SYMBOL_WRAP_DECL(void, lua_rawset, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_rawset, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_rawseti, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_rawseti, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_rawsetp, lua_State *L, int idx, const void *p){ +- SYMBOL_WRAP_CALL(lua_rawsetp, L, idx, p); +-} +-SYMBOL_WRAP_DECL(int, lua_setmetatable, lua_State *L, int objindex){ +- SYMBOL_WRAP_CALL(lua_setmetatable, L, objindex); +-} +-SYMBOL_WRAP_DECL(void, lua_setuservalue, lua_State *L, int idx){ +- if (__lua_setiuservalue != NULL) { +- return lua_setiuservalue(L, idx, 1); +- } else if (__lua_setuservalue != NULL) { +- SYMBOL_WRAP_CALL(lua_setuservalue, L, idx); +- } +- SYMBOL_WRAP_CALL_FB(lua_setuservalue, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_setiuservalue, lua_State *L, int idx, int n){ +- SYMBOL_WRAP_CALL(lua_setiuservalue, L, idx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_callk, lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_callk, L, nargs, nresults, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_getctx, lua_State *L, int *ctx){ +- SYMBOL_WRAP_CALL(lua_getctx, L, ctx); +-} +-SYMBOL_WRAP_DECL(int, lua_pcallk, lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_pcallk, L, nargs, nresults, errfunc, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_load, lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode){ +- SYMBOL_WRAP_CALL(lua_load, L, reader, dt, chunkname, mode); +-} +-SYMBOL_WRAP_DECL(int, lua_dump, lua_State *L, lua_Writer writer, void *data, int strip){ +- SYMBOL_WRAP_CALL(lua_dump, L, writer, data, strip); +-} +-SYMBOL_WRAP_DECL(int, lua_yieldk, lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k){ +- SYMBOL_WRAP_CALL(lua_yieldk, L, nresults, ctx, k); +-} +-SYMBOL_WRAP_DECL(int, lua_resume, lua_State *L, lua_State *from, int narg){ +- SYMBOL_WRAP_CALL(lua_resume, L, from, narg); +-} +-SYMBOL_WRAP_DECL(int, lua_status, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_status, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gc, lua_State *L, int what, int data){ +- SYMBOL_WRAP_CALL(lua_gc, L, what, data); +-} +-SYMBOL_WRAP_DECL(int, lua_error, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_error, L); +-} +-SYMBOL_WRAP_DECL(int, lua_next, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_next, L, idx); +-} +-SYMBOL_WRAP_DECL(void, lua_concat, lua_State *L, int n){ +- SYMBOL_WRAP_CALL(lua_concat, L, n); +-} +-SYMBOL_WRAP_DECL(void, lua_len, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(lua_len, L, idx); +-} +-SYMBOL_WRAP_DECL(lua_Alloc, lua_getallocf, lua_State *L, void **ud){ +- SYMBOL_WRAP_CALL(lua_getallocf, L, ud); +-} +-SYMBOL_WRAP_DECL(void, lua_setallocf, lua_State *L, lua_Alloc f, void *ud){ +- SYMBOL_WRAP_CALL(lua_setallocf, L, f, ud); +-} +-SYMBOL_WRAP_DECL(int, lua_getstack, lua_State *L, int level, lua_Debug *ar){ +- SYMBOL_WRAP_CALL(lua_getstack, L, level, ar); +-} +-SYMBOL_WRAP_DECL(int, lua_getinfo, lua_State *L, const char *what, lua_Debug *ar){ +- SYMBOL_WRAP_CALL(lua_getinfo, L, what, ar); +-} +-SYMBOL_WRAP_DECL(const char *, lua_getlocal, lua_State *L, const lua_Debug *ar, int n){ +- SYMBOL_WRAP_CALL(lua_getlocal, L, ar, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_setlocal, lua_State *L, const lua_Debug *ar, int n){ +- SYMBOL_WRAP_CALL(lua_setlocal, L, ar, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_getupvalue, lua_State *L, int funcindex, int n){ +- SYMBOL_WRAP_CALL(lua_getupvalue, L, funcindex, n); +-} +-SYMBOL_WRAP_DECL(const char *, lua_setupvalue, lua_State *L, int funcindex, int n){ +- SYMBOL_WRAP_CALL(lua_setupvalue, L, funcindex, n); +-} +-SYMBOL_WRAP_DECL(void *, lua_upvalueid, lua_State *L, int fidx, int n){ +- SYMBOL_WRAP_CALL(lua_upvalueid, L, fidx, n); +-} +-SYMBOL_WRAP_DECL(void, lua_upvaluejoin, lua_State *L, int fidx1, int n1, int fidx2, int n2){ +- SYMBOL_WRAP_CALL(lua_upvaluejoin, L, fidx1, n1, fidx2, n2); +-} +-SYMBOL_WRAP_DECL(int, lua_sethook, lua_State *L, lua_Hook func, int mask, int count){ +- SYMBOL_WRAP_CALL(lua_sethook, L, func, mask, count); +-} +-SYMBOL_WRAP_DECL(lua_Hook, lua_gethook, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethook, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gethookmask, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethookmask, L); +-} +-SYMBOL_WRAP_DECL(int, lua_gethookcount, lua_State *L){ +- SYMBOL_WRAP_CALL(lua_gethookcount, L); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkversion_, lua_State *L, lua_Number ver){ +- SYMBOL_WRAP_CALL(luaL_checkversion_, L, ver); +-} +-SYMBOL_WRAP_DECL(int, luaL_getmetafield, lua_State *L, int obj, const char *e){ +- SYMBOL_WRAP_CALL(luaL_getmetafield, L, obj, e); +-} +-SYMBOL_WRAP_DECL(int, luaL_callmeta, lua_State *L, int obj, const char *e){ +- SYMBOL_WRAP_CALL(luaL_callmeta, L, obj, e); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_tolstring, lua_State *L, int idx, size_t *len){ +- SYMBOL_WRAP_CALL(luaL_tolstring, L, idx, len); +-} +-SYMBOL_WRAP_DECL(int, luaL_argerror, lua_State *L, int numarg, const char *extramsg){ +- SYMBOL_WRAP_CALL(luaL_argerror, L, numarg, extramsg); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_checklstring, lua_State *L, int numArg, size_t *l){ +- SYMBOL_WRAP_CALL(luaL_checklstring, L, numArg, l); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_optlstring, lua_State *L, int numArg, const char *def, size_t *l){ +- SYMBOL_WRAP_CALL(luaL_optlstring, L, numArg, def, l); +-} +-SYMBOL_WRAP_DECL(lua_Number, luaL_checknumber, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checknumber, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Number, luaL_optnumber, lua_State *L, int nArg, lua_Number def){ +- SYMBOL_WRAP_CALL(luaL_optnumber, L, nArg, def); +-} +-SYMBOL_WRAP_DECL(lua_Integer, luaL_checkinteger, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checkinteger, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Integer, luaL_optinteger, lua_State *L, int nArg, lua_Integer def){ +- SYMBOL_WRAP_CALL(luaL_optinteger, L, nArg, def); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, luaL_checkunsigned, lua_State *L, int numArg){ +- SYMBOL_WRAP_CALL(luaL_checkunsigned, L, numArg); +-} +-SYMBOL_WRAP_DECL(lua_Unsigned, luaL_optunsigned, lua_State *L, int numArg, lua_Unsigned def){ +- SYMBOL_WRAP_CALL(luaL_optunsigned, L, numArg, def); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkstack, lua_State *L, int sz, const char *msg){ +- SYMBOL_WRAP_CALL(luaL_checkstack, L, sz, msg); +-} +-SYMBOL_WRAP_DECL(void, luaL_checktype, lua_State *L, int narg, int t){ +- SYMBOL_WRAP_CALL(luaL_checktype, L, narg, t); +-} +-SYMBOL_WRAP_DECL(void, luaL_checkany, lua_State *L, int narg){ +- SYMBOL_WRAP_CALL(luaL_checkany, L, narg); +-} +-SYMBOL_WRAP_DECL(int, luaL_newmetatable, lua_State *L, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_newmetatable, L, tname); +-} +-SYMBOL_WRAP_DECL(void, luaL_setmetatable, lua_State *L, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_setmetatable, L, tname); +-} +-SYMBOL_WRAP_DECL(void *, luaL_testudata, lua_State *L, int ud, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_testudata, L, ud, tname); +-} +-SYMBOL_WRAP_DECL(void *, luaL_checkudata, lua_State *L, int ud, const char *tname){ +- SYMBOL_WRAP_CALL(luaL_checkudata, L, ud, tname); +-} +-SYMBOL_WRAP_DECL(void, luaL_where, lua_State *L, int lvl){ +- SYMBOL_WRAP_CALL(luaL_where, L, lvl); +-} +-SYMBOL_WRAP_DECL(int, luaL_error, lua_State *L, const char *fmt, ...){ +- va_list argp; +- va_start(argp, fmt); +- luaL_where(L, 1); +- lua_pushvfstring(L, fmt, argp); +- va_end(argp); +- lua_concat(L, 2); +- return lua_error(L); +-} +-SYMBOL_WRAP_DECL(int, luaL_checkoption, lua_State *L, int narg, const char *def, const char *const lst[]){ +- SYMBOL_WRAP_CALL(luaL_checkoption, L, narg, def, lst); +-} +-SYMBOL_WRAP_DECL(int, luaL_fileresult, lua_State *L, int stat, const char *fname){ +- SYMBOL_WRAP_CALL(luaL_fileresult, L, stat, fname); +-} +-SYMBOL_WRAP_DECL(int, luaL_execresult, lua_State *L, int stat){ +- SYMBOL_WRAP_CALL(luaL_execresult, L, stat); +-} +-SYMBOL_WRAP_DECL(int, luaL_ref, lua_State *L, int t){ +- SYMBOL_WRAP_CALL(luaL_ref, L, t); +-} +-SYMBOL_WRAP_DECL(void, luaL_unref, lua_State *L, int t, int ref){ +- SYMBOL_WRAP_CALL(luaL_unref, L, t, ref); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadfilex, lua_State *L, const char *filename, const char *mode){ +- SYMBOL_WRAP_CALL(luaL_loadfilex, L, filename, mode); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadbufferx, lua_State *L, const char *buff, size_t sz, const char *name, const char *mode){ +- SYMBOL_WRAP_CALL(luaL_loadbufferx, L, buff, sz, name, mode); +-} +-SYMBOL_WRAP_DECL(int, luaL_loadstring, lua_State *L, const char *s){ +- SYMBOL_WRAP_CALL(luaL_loadstring, L, s); +-} +-SYMBOL_WRAP_DECL(lua_State *, luaL_newstate, void){ +- return __luaL_newstate(); +-} +-SYMBOL_WRAP_DECL(int, luaL_len, lua_State *L, int idx){ +- SYMBOL_WRAP_CALL(luaL_len, L, idx); +-} +-SYMBOL_WRAP_DECL(const char *, luaL_gsub, lua_State *L, const char *s, const char *p, const char *r){ +- SYMBOL_WRAP_CALL(luaL_gsub, L, s, p, r); +-} +-SYMBOL_WRAP_DECL(void, luaL_setfuncs, lua_State *L, const luaL_Reg *l, int nup){ +- SYMBOL_WRAP_CALL(luaL_setfuncs, L, l, nup); +-} +-SYMBOL_WRAP_DECL(int, luaL_getsubtable, lua_State *L, int idx, const char *fname){ +- SYMBOL_WRAP_CALL(luaL_getsubtable, L, idx, fname); +-} +-SYMBOL_WRAP_DECL(void, luaL_traceback, lua_State *L, lua_State *L1, const char *msg, int level){ +- SYMBOL_WRAP_CALL(luaL_traceback, L, L1, msg, level); +-} +-SYMBOL_WRAP_DECL(void, luaL_requiref, lua_State *L, const char *modname, lua_CFunction openf, int glb){ +- SYMBOL_WRAP_CALL(luaL_requiref, L, modname, openf, glb); +-} +-SYMBOL_WRAP_DECL(void, luaL_buffinit, lua_State *L, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_buffinit, L, B); +-} +-SYMBOL_WRAP_DECL(char *, luaL_prepbuffsize, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_prepbuffsize, B, sz); +-} +-SYMBOL_WRAP_DECL(void, luaL_addlstring, luaL_Buffer *B, const char *s, size_t l){ +- SYMBOL_WRAP_CALL(luaL_addlstring, B, s, l); +-} +-SYMBOL_WRAP_DECL(void, luaL_addstring, luaL_Buffer *B, const char *s){ +- SYMBOL_WRAP_CALL(luaL_addstring, B, s); +-} +-SYMBOL_WRAP_DECL(void, luaL_addvalue, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_addvalue, B); +-} +-SYMBOL_WRAP_DECL(void, luaL_pushresult, luaL_Buffer *B){ +- SYMBOL_WRAP_CALL(luaL_pushresult, B); +-} +-SYMBOL_WRAP_DECL(void, luaL_pushresultsize, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_pushresultsize, B, sz); +-} +-SYMBOL_WRAP_DECL(char *, luaL_buffinitsize, lua_State *L, luaL_Buffer *B, size_t sz){ +- SYMBOL_WRAP_CALL(luaL_buffinitsize, L, B, sz); +-} +-SYMBOL_WRAP_DECL(void, luaL_openlibs, lua_State *L){ +- SYMBOL_WRAP_CALL(luaL_openlibs, L); +-} +- +-#define IMPORT_SYMBOL(name, ret, ...) \ +- __##name = (\ +- __##name = (ret (*) (__VA_ARGS__)) symbol(#name), \ +- __##name == NULL ? &__lite_xl_fallback_##name : __##name\ +- ) +- +-#define IMPORT_SYMBOL_OPT(name, ret, ...) \ +- __##name = symbol(#name) +- +-static void lite_xl_plugin_init(void *XL) { +- void* (*symbol)(const char *) = (void* (*) (const char *)) XL; +- IMPORT_SYMBOL(lua_newstate, lua_State *, lua_Alloc f, void *ud); +- IMPORT_SYMBOL(lua_close, void , lua_State *L); +- IMPORT_SYMBOL(lua_newthread, lua_State *, lua_State *L); +- IMPORT_SYMBOL(lua_atpanic, lua_CFunction , lua_State *L, lua_CFunction panicf); +- IMPORT_SYMBOL(lua_version, const lua_Number *, lua_State *L); +- IMPORT_SYMBOL(lua_absindex, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_gettop, int , lua_State *L); +- IMPORT_SYMBOL(lua_settop, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_pushvalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_copy, void , lua_State *L, int fromidx, int toidx); +- IMPORT_SYMBOL(lua_checkstack, int , lua_State *L, int sz); +- IMPORT_SYMBOL(lua_xmove, void , lua_State *from, lua_State *to, int n); +- IMPORT_SYMBOL(lua_isnumber, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_isstring, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_iscfunction, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_isuserdata, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_type, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_typename, const char *, lua_State *L, int tp); +- IMPORT_SYMBOL(lua_tonumberx, lua_Number , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_tointegerx, lua_Integer , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_tounsignedx, lua_Unsigned , lua_State *L, int idx, int *isnum); +- IMPORT_SYMBOL(lua_toboolean, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tolstring, const char *, lua_State *L, int idx, size_t *len); +- IMPORT_SYMBOL(lua_rawlen, size_t , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tocfunction, lua_CFunction , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_touserdata, void *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_tothread, lua_State *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_topointer, const void *, lua_State *L, int idx); +- IMPORT_SYMBOL(lua_arith, void , lua_State *L, int op); +- IMPORT_SYMBOL(lua_rawequal, int , lua_State *L, int idx1, int idx2); +- IMPORT_SYMBOL(lua_compare, int , lua_State *L, int idx1, int idx2, int op); +- IMPORT_SYMBOL(lua_pushnil, void , lua_State *L); +- IMPORT_SYMBOL(lua_pushnumber, void , lua_State *L, lua_Number n); +- IMPORT_SYMBOL(lua_pushinteger, void , lua_State *L, lua_Integer n); +- IMPORT_SYMBOL(lua_pushunsigned, void , lua_State *L, lua_Unsigned n); +- IMPORT_SYMBOL(lua_pushlstring, const char *, lua_State *L, const char *s, size_t l); +- IMPORT_SYMBOL(lua_pushstring, const char *, lua_State *L, const char *s); +- IMPORT_SYMBOL(lua_pushvfstring, const char *, lua_State *L, const char *fmt, va_list argp); +- IMPORT_SYMBOL(lua_pushfstring, const char *, lua_State *L, const char *fmt, ...); +- IMPORT_SYMBOL(lua_pushcclosure, void , lua_State *L, lua_CFunction fn, int n); +- IMPORT_SYMBOL(lua_pushboolean, void , lua_State *L, int b); +- IMPORT_SYMBOL(lua_pushlightuserdata, void , lua_State *L, void *p); +- IMPORT_SYMBOL(lua_pushthread, int , lua_State *L); +- IMPORT_SYMBOL(lua_getglobal, void , lua_State *L, const char *var); +- IMPORT_SYMBOL(lua_gettable, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getfield, void , lua_State *L, int idx, const char *k); +- IMPORT_SYMBOL(lua_rawget, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_rawgeti, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_rawgetp, void , lua_State *L, int idx, const void *p); +- IMPORT_SYMBOL(lua_createtable, void , lua_State *L, int narr, int nrec); +- IMPORT_SYMBOL_OPT(lua_newuserdata, void *, lua_State *L, size_t sz); +- IMPORT_SYMBOL(lua_newuserdatauv, void *, lua_State *L, size_t sz, int nuvalue); +- IMPORT_SYMBOL(lua_getmetatable, int , lua_State *L, int objindex); +- IMPORT_SYMBOL_OPT(lua_getuservalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getiuservalue, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_setglobal, void , lua_State *L, const char *var); +- IMPORT_SYMBOL(lua_settable, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_setfield, void , lua_State *L, int idx, const char *k); +- IMPORT_SYMBOL(lua_rawset, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_rawseti, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_rawsetp, void , lua_State *L, int idx, const void *p); +- IMPORT_SYMBOL(lua_setmetatable, int , lua_State *L, int objindex); +- IMPORT_SYMBOL_OPT(lua_setuservalue, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_setiuservalue, void , lua_State *L, int idx, int n); +- IMPORT_SYMBOL(lua_callk, void , lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_getctx, int , lua_State *L, int *ctx); +- IMPORT_SYMBOL(lua_pcallk, int , lua_State *L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_load, int , lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode); +- IMPORT_SYMBOL(lua_dump, int , lua_State *L, lua_Writer writer, void *data, int strip); +- IMPORT_SYMBOL(lua_yieldk, int , lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k); +- IMPORT_SYMBOL(lua_resume, int , lua_State *L, lua_State *from, int narg); +- IMPORT_SYMBOL(lua_status, int , lua_State *L); +- IMPORT_SYMBOL(lua_gc, int , lua_State *L, int what, int data); +- IMPORT_SYMBOL(lua_error, int , lua_State *L); +- IMPORT_SYMBOL(lua_next, int , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_concat, void , lua_State *L, int n); +- IMPORT_SYMBOL(lua_len, void , lua_State *L, int idx); +- IMPORT_SYMBOL(lua_getallocf, lua_Alloc , lua_State *L, void **ud); +- IMPORT_SYMBOL(lua_setallocf, void , lua_State *L, lua_Alloc f, void *ud); +- IMPORT_SYMBOL(lua_getstack, int , lua_State *L, int level, lua_Debug *ar); +- IMPORT_SYMBOL(lua_getinfo, int , lua_State *L, const char *what, lua_Debug *ar); +- IMPORT_SYMBOL(lua_getlocal, const char *, lua_State *L, const lua_Debug *ar, int n); +- IMPORT_SYMBOL(lua_setlocal, const char *, lua_State *L, const lua_Debug *ar, int n); +- IMPORT_SYMBOL(lua_getupvalue, const char *, lua_State *L, int funcindex, int n); +- IMPORT_SYMBOL(lua_setupvalue, const char *, lua_State *L, int funcindex, int n); +- IMPORT_SYMBOL(lua_upvalueid, void *, lua_State *L, int fidx, int n); +- IMPORT_SYMBOL(lua_upvaluejoin, void , lua_State *L, int fidx1, int n1, int fidx2, int n2); +- IMPORT_SYMBOL(lua_sethook, int , lua_State *L, lua_Hook func, int mask, int count); +- IMPORT_SYMBOL(lua_gethook, lua_Hook , lua_State *L); +- IMPORT_SYMBOL(lua_gethookmask, int , lua_State *L); +- IMPORT_SYMBOL(lua_gethookcount, int , lua_State *L); +- IMPORT_SYMBOL(luaL_checkversion_, void , lua_State *L, lua_Number ver); +- IMPORT_SYMBOL(luaL_getmetafield, int , lua_State *L, int obj, const char *e); +- IMPORT_SYMBOL(luaL_callmeta, int , lua_State *L, int obj, const char *e); +- IMPORT_SYMBOL(luaL_tolstring, const char *, lua_State *L, int idx, size_t *len); +- IMPORT_SYMBOL(luaL_argerror, int , lua_State *L, int numarg, const char *extramsg); +- IMPORT_SYMBOL(luaL_checklstring, const char *, lua_State *L, int numArg, size_t *l); +- IMPORT_SYMBOL(luaL_optlstring, const char *, lua_State *L, int numArg, const char *def, size_t *l); +- IMPORT_SYMBOL(luaL_checknumber, lua_Number , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optnumber, lua_Number , lua_State *L, int nArg, lua_Number def); +- IMPORT_SYMBOL(luaL_checkinteger, lua_Integer , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optinteger, lua_Integer , lua_State *L, int nArg, lua_Integer def); +- IMPORT_SYMBOL(luaL_checkunsigned, lua_Unsigned , lua_State *L, int numArg); +- IMPORT_SYMBOL(luaL_optunsigned, lua_Unsigned , lua_State *L, int numArg, lua_Unsigned def); +- IMPORT_SYMBOL(luaL_checkstack, void , lua_State *L, int sz, const char *msg); +- IMPORT_SYMBOL(luaL_checktype, void , lua_State *L, int narg, int t); +- IMPORT_SYMBOL(luaL_checkany, void , lua_State *L, int narg); +- IMPORT_SYMBOL(luaL_newmetatable, int , lua_State *L, const char *tname); +- IMPORT_SYMBOL(luaL_setmetatable, void , lua_State *L, const char *tname); +- IMPORT_SYMBOL(luaL_testudata, void *, lua_State *L, int ud, const char *tname); +- IMPORT_SYMBOL(luaL_checkudata, void *, lua_State *L, int ud, const char *tname); +- IMPORT_SYMBOL(luaL_where, void , lua_State *L, int lvl); +- IMPORT_SYMBOL(luaL_error, int , lua_State *L, const char *fmt, ...); +- IMPORT_SYMBOL(luaL_checkoption, int , lua_State *L, int narg, const char *def, const char *const lst[]); +- IMPORT_SYMBOL(luaL_fileresult, int , lua_State *L, int stat, const char *fname); +- IMPORT_SYMBOL(luaL_execresult, int , lua_State *L, int stat); +- IMPORT_SYMBOL(luaL_ref, int , lua_State *L, int t); +- IMPORT_SYMBOL(luaL_unref, void , lua_State *L, int t, int ref); +- IMPORT_SYMBOL(luaL_loadfilex, int , lua_State *L, const char *filename, const char *mode); +- IMPORT_SYMBOL(luaL_loadbufferx, int , lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); +- IMPORT_SYMBOL(luaL_loadstring, int , lua_State *L, const char *s); +- IMPORT_SYMBOL(luaL_newstate, lua_State *, void); +- IMPORT_SYMBOL(luaL_len, int , lua_State *L, int idx); +- IMPORT_SYMBOL(luaL_gsub, const char *, lua_State *L, const char *s, const char *p, const char *r); +- IMPORT_SYMBOL(luaL_setfuncs, void , lua_State *L, const luaL_Reg *l, int nup); +- IMPORT_SYMBOL(luaL_getsubtable, int , lua_State *L, int idx, const char *fname); +- IMPORT_SYMBOL(luaL_traceback, void , lua_State *L, lua_State *L1, const char *msg, int level); +- IMPORT_SYMBOL(luaL_requiref, void , lua_State *L, const char *modname, lua_CFunction openf, int glb); +- IMPORT_SYMBOL(luaL_buffinit, void , lua_State *L, luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_prepbuffsize, char *, luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_addlstring, void , luaL_Buffer *B, const char *s, size_t l); +- IMPORT_SYMBOL(luaL_addstring, void , luaL_Buffer *B, const char *s); +- IMPORT_SYMBOL(luaL_addvalue, void , luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_pushresult, void , luaL_Buffer *B); +- IMPORT_SYMBOL(luaL_pushresultsize, void , luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_buffinitsize, char *, lua_State *L, luaL_Buffer *B, size_t sz); +- IMPORT_SYMBOL(luaL_openlibs, void, lua_State* L); +-} +- +-#endif /* LITE_XL_PLUGIN_ENTRYPOINT */ +- +-#endif /* LITE_XL_PLUGIN_API */ diff --git a/tasks/lite-xl__lite-xl-1436/tests/test.sh b/tasks/lite-xl__lite-xl-1436/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..65f52460d338893b2e5faa96ba58bc9e3e70538e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/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 d15108309c8ce98f9a5412e87a05d39a177e5765 > "$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/lite-xl__lite-xl-1436/tests/verifier.py b/tasks/lite-xl__lite-xl-1436/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1436/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/lite-xl__lite-xl-1437/environment/Dockerfile b/tasks/lite-xl__lite-xl-1437/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..934a709dc2c9f0c50b82bacc136c4f5377f085d9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2cdf5d89492242084654de118016dd8cf75bd660 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2cdf5d89492242084654de118016dd8cf75bd660 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2cdf5d89492242084654de118016dd8cf75bd660 \ + && 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/lite-xl__lite-xl-1437/instruction.md b/tasks/lite-xl__lite-xl-1437/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77daba1ba9c6dde8e9c6589a356538860d12807b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** Update api_require to expose more symbols + +## Description + +This time, all visible (dynamically loadable) symbols from lua.dll are exported. +The code is updated to support Lua 5.1, 5.2, 5.3 and 5.4. + +
+To get the appropriate headers + +```sh +#!/bin/bash + +VERSIONS="5.1.5 5.2.4 5.3.6 5.4.4" + +shopt -s globstar +for v in $VERSIONS; do + mkdir -p $v + curl -sSL "http://www.lua.org/ftp/lua-$v.tar.gz" | tar -zxvf - -C $v "lua-$v/src/"{lua,lauxlib,lualib,luaconf}.h + gcc -E "$v/"**/*.h > "$v.pch.h" + ctags --c-kinds=p -f - "$v.pch.h" | awk '/\tp$/ { print $1 }' | grep 'lua' | sort > "$v.txt" +done +``` +
+ +
+To generate the code + +```py +#!/usr/bin/env python3 + +def read_file(name): + return set(line.strip() for line in open(name)) + +def print_symbols(versions, s): + output = [] + count = 0 + line = [] + + output.append(f'#if {" && ".join(f"LUA_VERSION_NUM == {v}" for v in versions)}') + + for item in sorted(s): + if item.startswith('lua_'): + itemstr = f'P({item.removeprefix("lua_")})' + elif item.startswith('luaL_'): + itemstr = f'U({item.removeprefix("luaL_")})' + else: + itemstr = f'S({item})' + + if (count + len(itemstr) + 2) > 74: + output.append(', '.join(line) + ',') + count = 0 + line = [] + + line.append(itemstr) + count += len(itemstr) + 2 + + if len(line) > 0: + output.append(', '.join(line) + ',') + + output.append('#endif') + if len(output) > 2: + print(' ' + '\n '.join(output)) + +f1 = read_file('5.1.5.txt') +f2 = read_file('5.2.4.txt') +f3 = read_file('5.3.6.txt') +f4 = read_file('5.4.4.txt') + +versions = { + 501: f1, + 502: f2, + 503: f3, + 504: f4 +} +allfunc = set.union(f1, f2, f3, f4) + +output = {} + +for f in allfunc: + available_in = sorted([v for v, s in versions.items() if f in s]) + k = tuple(available_in) + var = output.get(k, []) + var.append(f) + output[k] = var + +kvp = list(output.items()) +kvp.sort(reverse=True, key=lambda t: (len(t[0]), t[0])) +for k, v in kvp: + print_symbols(k, v) +``` + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2cdf5d894922`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1437/solution/patch.diff b/tasks/lite-xl__lite-xl-1437/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1cfd124d52be5dd8b2fc6223c003ddd40ab8005d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/solution/patch.diff @@ -0,0 +1,110 @@ +diff --git a/src/api/system.c b/src/api/system.c +index ad7cede8..c7eb3897 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -913,47 +913,70 @@ typedef struct lua_function_node { + + #define P(FUNC) { "lua_" #FUNC, (fptr)(lua_##FUNC) } + #define U(FUNC) { "luaL_" #FUNC, (fptr)(luaL_##FUNC) } ++#define S(FUNC) { #FUNC, (fptr)(FUNC) } + static void* api_require(const char* symbol) { + static const lua_function_node nodes[] = { +- P(atpanic), P(checkstack), +- P(close), P(concat), P(copy), P(createtable), P(dump), +- P(error), P(gc), P(getallocf), P(getfield), +- P(gethook), P(gethookcount), P(gethookmask), P(getinfo), P(getlocal), +- P(getmetatable), P(getstack), P(gettable), P(gettop), P(getupvalue), +- P(isnumber), P(isstring), P(isuserdata), +- P(load), P(newstate), P(newthread), P(next), ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ U(addlstring), U(addstring), U(addvalue), U(argerror), U(buffinit), ++ U(callmeta), U(checkany), U(checkinteger), U(checklstring), ++ U(checknumber), U(checkoption), U(checkstack), U(checktype), ++ U(checkudata), U(error), U(getmetafield), U(gsub), U(loadstring), ++ U(newmetatable), U(newstate), U(openlibs), U(optinteger), U(optlstring), ++ U(optnumber), U(pushresult), U(ref), U(unref), U(where), P(atpanic), ++ P(checkstack), P(close), P(concat), P(createtable), P(dump), P(error), ++ P(gc), P(getallocf), P(getfield), P(gethook), P(gethookcount), ++ P(gethookmask), P(getinfo), P(getlocal), P(getmetatable), P(getstack), ++ P(gettable), P(gettop), P(getupvalue), P(iscfunction), P(isnumber), ++ P(isstring), P(isuserdata), P(load), P(newstate), P(newthread), P(next), + P(pushboolean), P(pushcclosure), P(pushfstring), P(pushinteger), + P(pushlightuserdata), P(pushlstring), P(pushnil), P(pushnumber), +- P(pushstring), P(pushthread), P(pushvalue), +- P(pushvfstring), P(rawequal), P(rawget), P(rawgeti), +- P(rawset), P(rawseti), P(resume), +- P(setallocf), P(setfield), P(sethook), P(setlocal), +- P(setmetatable), P(settable), P(settop), P(setupvalue), +- P(status), P(tocfunction), P(tointegerx), P(tolstring), P(toboolean), +- P(tonumberx), P(topointer), P(tothread), P(touserdata), +- P(type), P(typename), P(upvalueid), P(upvaluejoin), P(version), P(xmove), +- U(getmetafield), U(callmeta), U(argerror), U(checknumber), U(optnumber), +- U(checkinteger), U(checkstack), U(checktype), U(checkany), +- U(newmetatable), U(setmetatable), U(testudata), U(checkudata), U(where), +- U(error), U(fileresult), U(execresult), U(ref), U(unref), U(loadstring), +- U(newstate), U(setfuncs), U(buffinit), U(addlstring), U(addstring), +- U(addvalue), U(pushresult), U(openlibs), {"api_load_libs", (void*)(api_load_libs)}, +- #if LUA_VERSION_NUM >= 502 +- P(absindex), P(arith), P(callk), P(compare), P(getglobal), +- P(len), P(pcallk), P(rawgetp), P(rawlen), P(rawsetp), P(setglobal), +- P(iscfunction), P(yieldk), +- U(checkversion_), U(tolstring), U(len), U(getsubtable), U(prepbuffsize), +- U(pushresultsize), U(buffinitsize), U(checklstring), U(checkoption), U(gsub), U(loadbufferx), +- U(loadfilex), U(optinteger), U(optlstring), U(requiref), U(traceback), +- #else +- P(objlen), ++ P(pushstring), P(pushthread), P(pushvalue), P(pushvfstring), P(rawequal), ++ P(rawget), P(rawgeti), P(rawset), P(rawseti), P(resume), P(setallocf), ++ P(setfield), P(sethook), P(setlocal), P(setmetatable), P(settable), ++ P(settop), P(setupvalue), P(status), P(toboolean), P(tocfunction), ++ P(tolstring), P(topointer), P(tothread), P(touserdata), P(type), ++ P(typename), P(xmove), S(luaopen_base), S(luaopen_debug), S(luaopen_io), ++ S(luaopen_math), S(luaopen_os), S(luaopen_package), S(luaopen_string), ++ S(luaopen_table), S(api_load_libs), + #endif +- #if LUA_VERSION_NUM >= 504 +- P(newuserdatauv), P(setiuservalue), P(getiuservalue) +- #else +- P(newuserdata), P(setuservalue), P(getuservalue) ++ #if LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ U(buffinitsize), U(checkversion_), U(execresult), U(fileresult), ++ U(getsubtable), U(len), U(loadbufferx), U(loadfilex), U(prepbuffsize), ++ U(pushresultsize), U(requiref), U(setfuncs), U(setmetatable), ++ U(testudata), U(tolstring), U(traceback), P(absindex), P(arith), ++ P(callk), P(compare), P(copy), P(getglobal), P(len), P(pcallk), ++ P(rawgetp), P(rawlen), P(rawsetp), P(setglobal), P(tointegerx), ++ P(tonumberx), P(upvalueid), P(upvaluejoin), P(version), P(yieldk), ++ S(luaopen_coroutine), ++ #endif ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 ++ P(newuserdata), ++ #endif ++ #if LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ P(geti), P(isinteger), P(isyieldable), P(rotate), P(seti), ++ P(stringtonumber), S(luaopen_utf8), ++ #endif ++ #if LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 ++ P(getuservalue), P(setuservalue), S(luaopen_bit32), ++ #endif ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 ++ P(insert), P(remove), P(replace), ++ #endif ++ #if LUA_VERSION_NUM == 504 ++ U(addgsub), U(typeerror), P(closeslot), P(getiuservalue), ++ P(newuserdatauv), P(resetthread), P(setcstacklimit), P(setiuservalue), ++ P(setwarnf), P(toclose), P(warning), ++ #endif ++ #if LUA_VERSION_NUM == 502 ++ U(checkunsigned), U(optunsigned), P(getctx), P(pushunsigned), ++ P(tounsignedx), ++ #endif ++ #if LUA_VERSION_NUM == 501 ++ U(findtable), U(loadbuffer), U(loadfile), U(openlib), U(prepbuffer), ++ U(register), U(typerror), P(call), P(cpcall), P(equal), P(getfenv), ++ P(lessthan), P(objlen), P(pcall), P(setfenv), P(setlevel), P(tointeger), ++ P(tonumber), P(yield), + #endif +- + }; + for (size_t i = 0; i < sizeof(nodes) / sizeof(lua_function_node); ++i) { + if (strcmp(nodes[i].symbol, symbol) == 0) diff --git a/tasks/lite-xl__lite-xl-1437/solution/solve.sh b/tasks/lite-xl__lite-xl-1437/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/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/lite-xl__lite-xl-1437/task.toml b/tasks/lite-xl__lite-xl-1437/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d937686202d0b72abca3c24d6caf196574b565e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1437" +description = "Update api_require to expose more symbols" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "2cdf5d89492242084654de118016dd8cf75bd660" +reference = "https://github.com/lite-xl/lite-xl/pull/1437" +source_access = "auto" +built_at = "2026-11-16T16:09:56.248450+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8ade2642c6eb98eca9deecf54fdb194c28b2cdfc881f1733d166052f3df83589" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-07T17:45:28Z" +diff_format = "unified" +context_files = [ + "src/api/system.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 93 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.284255+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:44b8859e20f9c9afe1179feecb5d619764561690d374513ddb23497f0b22a5b8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1437/tests/capture.py b/tasks/lite-xl__lite-xl-1437/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/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/lite-xl__lite-xl-1437/tests/instruction.md b/tasks/lite-xl__lite-xl-1437/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77daba1ba9c6dde8e9c6589a356538860d12807b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/tests/instruction.md @@ -0,0 +1,99 @@ +# Issue + +**Title:** Update api_require to expose more symbols + +## Description + +This time, all visible (dynamically loadable) symbols from lua.dll are exported. +The code is updated to support Lua 5.1, 5.2, 5.3 and 5.4. + +
+To get the appropriate headers + +```sh +#!/bin/bash + +VERSIONS="5.1.5 5.2.4 5.3.6 5.4.4" + +shopt -s globstar +for v in $VERSIONS; do + mkdir -p $v + curl -sSL "http://www.lua.org/ftp/lua-$v.tar.gz" | tar -zxvf - -C $v "lua-$v/src/"{lua,lauxlib,lualib,luaconf}.h + gcc -E "$v/"**/*.h > "$v.pch.h" + ctags --c-kinds=p -f - "$v.pch.h" | awk '/\tp$/ { print $1 }' | grep 'lua' | sort > "$v.txt" +done +``` +
+ +
+To generate the code + +```py +#!/usr/bin/env python3 + +def read_file(name): + return set(line.strip() for line in open(name)) + +def print_symbols(versions, s): + output = [] + count = 0 + line = [] + + output.append(f'#if {" && ".join(f"LUA_VERSION_NUM == {v}" for v in versions)}') + + for item in sorted(s): + if item.startswith('lua_'): + itemstr = f'P({item.removeprefix("lua_")})' + elif item.startswith('luaL_'): + itemstr = f'U({item.removeprefix("luaL_")})' + else: + itemstr = f'S({item})' + + if (count + len(itemstr) + 2) > 74: + output.append(', '.join(line) + ',') + count = 0 + line = [] + + line.append(itemstr) + count += len(itemstr) + 2 + + if len(line) > 0: + output.append(', '.join(line) + ',') + + output.append('#endif') + if len(output) > 2: + print(' ' + '\n '.join(output)) + +f1 = read_file('5.1.5.txt') +f2 = read_file('5.2.4.txt') +f3 = read_file('5.3.6.txt') +f4 = read_file('5.4.4.txt') + +versions = { + 501: f1, + 502: f2, + 503: f3, + 504: f4 +} +allfunc = set.union(f1, f2, f3, f4) + +output = {} + +for f in allfunc: + available_in = sorted([v for v, s in versions.items() if f in s]) + k = tuple(available_in) + var = output.get(k, []) + var.append(f) + output[k] = var + +kvp = list(output.items()) +kvp.sort(reverse=True, key=lambda t: (len(t[0]), t[0])) +for k, v in kvp: + print_symbols(k, v) +``` + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2cdf5d894922`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1437/tests/oracle.patch b/tasks/lite-xl__lite-xl-1437/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1cfd124d52be5dd8b2fc6223c003ddd40ab8005d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/tests/oracle.patch @@ -0,0 +1,110 @@ +diff --git a/src/api/system.c b/src/api/system.c +index ad7cede8..c7eb3897 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -913,47 +913,70 @@ typedef struct lua_function_node { + + #define P(FUNC) { "lua_" #FUNC, (fptr)(lua_##FUNC) } + #define U(FUNC) { "luaL_" #FUNC, (fptr)(luaL_##FUNC) } ++#define S(FUNC) { #FUNC, (fptr)(FUNC) } + static void* api_require(const char* symbol) { + static const lua_function_node nodes[] = { +- P(atpanic), P(checkstack), +- P(close), P(concat), P(copy), P(createtable), P(dump), +- P(error), P(gc), P(getallocf), P(getfield), +- P(gethook), P(gethookcount), P(gethookmask), P(getinfo), P(getlocal), +- P(getmetatable), P(getstack), P(gettable), P(gettop), P(getupvalue), +- P(isnumber), P(isstring), P(isuserdata), +- P(load), P(newstate), P(newthread), P(next), ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ U(addlstring), U(addstring), U(addvalue), U(argerror), U(buffinit), ++ U(callmeta), U(checkany), U(checkinteger), U(checklstring), ++ U(checknumber), U(checkoption), U(checkstack), U(checktype), ++ U(checkudata), U(error), U(getmetafield), U(gsub), U(loadstring), ++ U(newmetatable), U(newstate), U(openlibs), U(optinteger), U(optlstring), ++ U(optnumber), U(pushresult), U(ref), U(unref), U(where), P(atpanic), ++ P(checkstack), P(close), P(concat), P(createtable), P(dump), P(error), ++ P(gc), P(getallocf), P(getfield), P(gethook), P(gethookcount), ++ P(gethookmask), P(getinfo), P(getlocal), P(getmetatable), P(getstack), ++ P(gettable), P(gettop), P(getupvalue), P(iscfunction), P(isnumber), ++ P(isstring), P(isuserdata), P(load), P(newstate), P(newthread), P(next), + P(pushboolean), P(pushcclosure), P(pushfstring), P(pushinteger), + P(pushlightuserdata), P(pushlstring), P(pushnil), P(pushnumber), +- P(pushstring), P(pushthread), P(pushvalue), +- P(pushvfstring), P(rawequal), P(rawget), P(rawgeti), +- P(rawset), P(rawseti), P(resume), +- P(setallocf), P(setfield), P(sethook), P(setlocal), +- P(setmetatable), P(settable), P(settop), P(setupvalue), +- P(status), P(tocfunction), P(tointegerx), P(tolstring), P(toboolean), +- P(tonumberx), P(topointer), P(tothread), P(touserdata), +- P(type), P(typename), P(upvalueid), P(upvaluejoin), P(version), P(xmove), +- U(getmetafield), U(callmeta), U(argerror), U(checknumber), U(optnumber), +- U(checkinteger), U(checkstack), U(checktype), U(checkany), +- U(newmetatable), U(setmetatable), U(testudata), U(checkudata), U(where), +- U(error), U(fileresult), U(execresult), U(ref), U(unref), U(loadstring), +- U(newstate), U(setfuncs), U(buffinit), U(addlstring), U(addstring), +- U(addvalue), U(pushresult), U(openlibs), {"api_load_libs", (void*)(api_load_libs)}, +- #if LUA_VERSION_NUM >= 502 +- P(absindex), P(arith), P(callk), P(compare), P(getglobal), +- P(len), P(pcallk), P(rawgetp), P(rawlen), P(rawsetp), P(setglobal), +- P(iscfunction), P(yieldk), +- U(checkversion_), U(tolstring), U(len), U(getsubtable), U(prepbuffsize), +- U(pushresultsize), U(buffinitsize), U(checklstring), U(checkoption), U(gsub), U(loadbufferx), +- U(loadfilex), U(optinteger), U(optlstring), U(requiref), U(traceback), +- #else +- P(objlen), ++ P(pushstring), P(pushthread), P(pushvalue), P(pushvfstring), P(rawequal), ++ P(rawget), P(rawgeti), P(rawset), P(rawseti), P(resume), P(setallocf), ++ P(setfield), P(sethook), P(setlocal), P(setmetatable), P(settable), ++ P(settop), P(setupvalue), P(status), P(toboolean), P(tocfunction), ++ P(tolstring), P(topointer), P(tothread), P(touserdata), P(type), ++ P(typename), P(xmove), S(luaopen_base), S(luaopen_debug), S(luaopen_io), ++ S(luaopen_math), S(luaopen_os), S(luaopen_package), S(luaopen_string), ++ S(luaopen_table), S(api_load_libs), + #endif +- #if LUA_VERSION_NUM >= 504 +- P(newuserdatauv), P(setiuservalue), P(getiuservalue) +- #else +- P(newuserdata), P(setuservalue), P(getuservalue) ++ #if LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ U(buffinitsize), U(checkversion_), U(execresult), U(fileresult), ++ U(getsubtable), U(len), U(loadbufferx), U(loadfilex), U(prepbuffsize), ++ U(pushresultsize), U(requiref), U(setfuncs), U(setmetatable), ++ U(testudata), U(tolstring), U(traceback), P(absindex), P(arith), ++ P(callk), P(compare), P(copy), P(getglobal), P(len), P(pcallk), ++ P(rawgetp), P(rawlen), P(rawsetp), P(setglobal), P(tointegerx), ++ P(tonumberx), P(upvalueid), P(upvaluejoin), P(version), P(yieldk), ++ S(luaopen_coroutine), ++ #endif ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 ++ P(newuserdata), ++ #endif ++ #if LUA_VERSION_NUM == 503 && LUA_VERSION_NUM == 504 ++ P(geti), P(isinteger), P(isyieldable), P(rotate), P(seti), ++ P(stringtonumber), S(luaopen_utf8), ++ #endif ++ #if LUA_VERSION_NUM == 502 && LUA_VERSION_NUM == 503 ++ P(getuservalue), P(setuservalue), S(luaopen_bit32), ++ #endif ++ #if LUA_VERSION_NUM == 501 && LUA_VERSION_NUM == 502 ++ P(insert), P(remove), P(replace), ++ #endif ++ #if LUA_VERSION_NUM == 504 ++ U(addgsub), U(typeerror), P(closeslot), P(getiuservalue), ++ P(newuserdatauv), P(resetthread), P(setcstacklimit), P(setiuservalue), ++ P(setwarnf), P(toclose), P(warning), ++ #endif ++ #if LUA_VERSION_NUM == 502 ++ U(checkunsigned), U(optunsigned), P(getctx), P(pushunsigned), ++ P(tounsignedx), ++ #endif ++ #if LUA_VERSION_NUM == 501 ++ U(findtable), U(loadbuffer), U(loadfile), U(openlib), U(prepbuffer), ++ U(register), U(typerror), P(call), P(cpcall), P(equal), P(getfenv), ++ P(lessthan), P(objlen), P(pcall), P(setfenv), P(setlevel), P(tointeger), ++ P(tonumber), P(yield), + #endif +- + }; + for (size_t i = 0; i < sizeof(nodes) / sizeof(lua_function_node); ++i) { + if (strcmp(nodes[i].symbol, symbol) == 0) diff --git a/tasks/lite-xl__lite-xl-1437/tests/test.sh b/tasks/lite-xl__lite-xl-1437/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b464f88fae4c9b66992da82ab51c7dd14083f5a8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/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 2cdf5d89492242084654de118016dd8cf75bd660 > "$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/lite-xl__lite-xl-1437/tests/verifier.py b/tasks/lite-xl__lite-xl-1437/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1437/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/lite-xl__lite-xl-1440/environment/Dockerfile b/tasks/lite-xl__lite-xl-1440/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..deb70a9001b18102b158f27c74a6c522f4581ecd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 702c7a9eb3808c80074ea5e76d222e837ed9284e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 702c7a9eb3808c80074ea5e76d222e837ed9284e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 702c7a9eb3808c80074ea5e76d222e837ed9284e \ + && 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/lite-xl__lite-xl-1440/instruction.md b/tasks/lite-xl__lite-xl-1440/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4bc02b55e7996d8d3e0c81143d96f1a2a062cbed --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Move the header into include/ + +## Description + +This allows people to compile by specifying -I../lite-xl/resources/include + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `702c7a9eb380`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1440/solution/patch.diff b/tasks/lite-xl__lite-xl-1440/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44952b47cb53099cbde0eb862bdabe49addb64c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/resources/README.md b/resources/README.md +index 975881c4..cf30432c 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -17,7 +17,7 @@ This folder contains resources that is used for building or packaging the projec + + ### Development + +-- `lite_xl_plugin_api.h`: Native plugin API header. See the contents of `lite_xl_plugin_api.h` for more details. ++- `include/lite_xl_plugin_api.h`: Native plugin API header. See the contents of `lite_xl_plugin_api.h` for more details. + + +-[1]: https://mesonbuild.com/Cross-compilation.html +\ No newline at end of file ++[1]: https://mesonbuild.com/Cross-compilation.html +diff --git a/resources/include/lite_xl_plugin_api.h b/resources/include/lite_xl_plugin_api.h +index 2947039e..0c5e93e9 100644 +--- a/resources/include/lite_xl_plugin_api.h ++++ b/resources/include/lite_xl_plugin_api.h +@@ -2560,4 +2560,4 @@ void lite_xl_plugin_init(void *XL); + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-******************************************************************************/ +\ No newline at end of file ++******************************************************************************/ diff --git a/tasks/lite-xl__lite-xl-1440/solution/solve.sh b/tasks/lite-xl__lite-xl-1440/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/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/lite-xl__lite-xl-1440/task.toml b/tasks/lite-xl__lite-xl-1440/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..926b89dea1122c5b95929d6c39449d3ab25a5a5b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1440" +description = "Move the header into include/" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "702c7a9eb3808c80074ea5e76d222e837ed9284e" +reference = "https://github.com/lite-xl/lite-xl/pull/1440" +source_access = "auto" +built_at = "2026-11-16T16:09:56.240112+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6820abeab6ef43b3da1ac769a3d836377a02227b835bc2eda764e145a6b8b2fd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-14T19:45:46Z" +diff_format = "unified" +context_files = [ + "resources/README.md", + "resources/include/lite_xl_plugin_api.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.284716+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e14cefb30b92a0521cde64f0ae3b02504a3c34f76e0f76f329ed53391a008128" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1440/tests/capture.py b/tasks/lite-xl__lite-xl-1440/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/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/lite-xl__lite-xl-1440/tests/instruction.md b/tasks/lite-xl__lite-xl-1440/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4bc02b55e7996d8d3e0c81143d96f1a2a062cbed --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Move the header into include/ + +## Description + +This allows people to compile by specifying -I../lite-xl/resources/include + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `702c7a9eb380`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1440/tests/oracle.patch b/tasks/lite-xl__lite-xl-1440/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44952b47cb53099cbde0eb862bdabe49addb64c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/resources/README.md b/resources/README.md +index 975881c4..cf30432c 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -17,7 +17,7 @@ This folder contains resources that is used for building or packaging the projec + + ### Development + +-- `lite_xl_plugin_api.h`: Native plugin API header. See the contents of `lite_xl_plugin_api.h` for more details. ++- `include/lite_xl_plugin_api.h`: Native plugin API header. See the contents of `lite_xl_plugin_api.h` for more details. + + +-[1]: https://mesonbuild.com/Cross-compilation.html +\ No newline at end of file ++[1]: https://mesonbuild.com/Cross-compilation.html +diff --git a/resources/include/lite_xl_plugin_api.h b/resources/include/lite_xl_plugin_api.h +index 2947039e..0c5e93e9 100644 +--- a/resources/include/lite_xl_plugin_api.h ++++ b/resources/include/lite_xl_plugin_api.h +@@ -2560,4 +2560,4 @@ void lite_xl_plugin_init(void *XL); + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-******************************************************************************/ +\ No newline at end of file ++******************************************************************************/ diff --git a/tasks/lite-xl__lite-xl-1440/tests/test.sh b/tasks/lite-xl__lite-xl-1440/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b826cbf8c1dfaab1f97127f64c6922bad1c34925 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/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 702c7a9eb3808c80074ea5e76d222e837ed9284e > "$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/lite-xl__lite-xl-1440/tests/verifier.py b/tasks/lite-xl__lite-xl-1440/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1440/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/lite-xl__lite-xl-1460/environment/Dockerfile b/tasks/lite-xl__lite-xl-1460/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..99cb5431a2ddde39e9d8c414067637965a282b4c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d1fe720f06dae2f3ff93c222ccca1be54fd4a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d1fe720f06dae2f3ff93c222ccca1be54fd4a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d1fe720f06dae2f3ff93c222ccca1be54fd4a0 \ + && 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/lite-xl__lite-xl-1460/instruction.md b/tasks/lite-xl__lite-xl-1460/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9528d4ac283961001b670864fd51d5e9385b4980 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Build releases with Ubuntu 18.04 container + +## Description + +This PR will fix the release workflow by using a Ubuntu 18.04 container. +The container is available at https://github.com/lite-xl/lite-xl-build-box. + +This workflow uses my fork because I cannot make our packages public. +If someone forks and wants to run a release they wouldn't be able to download the image. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d1fe720f06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1460/solution/patch.diff b/tasks/lite-xl__lite-xl-1460/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..105cbc6ab1ad182fb5400513cbf04d9b586c969f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 206931c7..581b6469 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -50,6 +50,7 @@ jobs: + name: Linux + needs: release + runs-on: ubuntu-latest ++ container: ghcr.io/takase1121/lite-xl-build-box:latest + env: + CC: gcc + CXX: g++ +@@ -59,16 +60,26 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + - uses: actions/checkout@v3 ++ ++ # disabled because this will break our own Python install + - name: Python Setup ++ if: false + uses: actions/setup-python@v4 + with: + python-version: 3.9 ++ ++ # disabled because the container has up-to-date packages + - name: Update Packages ++ if: false + run: sudo apt-get update ++ ++ # disabled as the dependencies are already installed + - name: Install Dependencies ++ if: false + run: | + bash scripts/install-dependencies.sh --debug + sudo apt-get install -y ccache ++ + - name: Build Portable + run: | + bash --version +diff --git a/scripts/appimage.sh b/scripts/appimage.sh +index 03de616c..17551a48 100644 +--- a/scripts/appimage.sh ++++ b/scripts/appimage.sh +@@ -181,7 +181,7 @@ generate_appimage() { + version="${version}-addons" + fi + +- ./appimagetool LiteXL.AppDir LiteXL${version}-${ARCH}.AppImage ++ ./appimagetool --appimage-extract-and-run LiteXL.AppDir LiteXL${version}-${ARCH}.AppImage + } + + setup_appimagetool diff --git a/tasks/lite-xl__lite-xl-1460/solution/solve.sh b/tasks/lite-xl__lite-xl-1460/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/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/lite-xl__lite-xl-1460/task.toml b/tasks/lite-xl__lite-xl-1460/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52d4975ce27c0b21bb449a4e7282c11c0ac0a28b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1460" +description = "Build releases with Ubuntu 18.04 container" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "a6d1fe720f06dae2f3ff93c222ccca1be54fd4a0" +reference = "https://github.com/lite-xl/lite-xl/pull/1460" +source_access = "auto" +built_at = "2026-11-16T16:09:56.246682+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c032476affd225a1618ed616b4369865e69a161c330da78b61633ab65f21a26a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-16T13:18:41Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.yml", + "scripts/appimage.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.285170+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5e7172ff1cdc26b06f51c0cc889539c676ecf7a9e1e08daa4b20f4814f4b61b0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1460/tests/capture.py b/tasks/lite-xl__lite-xl-1460/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/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/lite-xl__lite-xl-1460/tests/instruction.md b/tasks/lite-xl__lite-xl-1460/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9528d4ac283961001b670864fd51d5e9385b4980 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Build releases with Ubuntu 18.04 container + +## Description + +This PR will fix the release workflow by using a Ubuntu 18.04 container. +The container is available at https://github.com/lite-xl/lite-xl-build-box. + +This workflow uses my fork because I cannot make our packages public. +If someone forks and wants to run a release they wouldn't be able to download the image. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a6d1fe720f06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1460/tests/oracle.patch b/tasks/lite-xl__lite-xl-1460/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..105cbc6ab1ad182fb5400513cbf04d9b586c969f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 206931c7..581b6469 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -50,6 +50,7 @@ jobs: + name: Linux + needs: release + runs-on: ubuntu-latest ++ container: ghcr.io/takase1121/lite-xl-build-box:latest + env: + CC: gcc + CXX: g++ +@@ -59,16 +60,26 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + - uses: actions/checkout@v3 ++ ++ # disabled because this will break our own Python install + - name: Python Setup ++ if: false + uses: actions/setup-python@v4 + with: + python-version: 3.9 ++ ++ # disabled because the container has up-to-date packages + - name: Update Packages ++ if: false + run: sudo apt-get update ++ ++ # disabled as the dependencies are already installed + - name: Install Dependencies ++ if: false + run: | + bash scripts/install-dependencies.sh --debug + sudo apt-get install -y ccache ++ + - name: Build Portable + run: | + bash --version +diff --git a/scripts/appimage.sh b/scripts/appimage.sh +index 03de616c..17551a48 100644 +--- a/scripts/appimage.sh ++++ b/scripts/appimage.sh +@@ -181,7 +181,7 @@ generate_appimage() { + version="${version}-addons" + fi + +- ./appimagetool LiteXL.AppDir LiteXL${version}-${ARCH}.AppImage ++ ./appimagetool --appimage-extract-and-run LiteXL.AppDir LiteXL${version}-${ARCH}.AppImage + } + + setup_appimagetool diff --git a/tasks/lite-xl__lite-xl-1460/tests/test.sh b/tasks/lite-xl__lite-xl-1460/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7ed90fcbe79d364ffca943f6d6b79fe820fee88 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/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 a6d1fe720f06dae2f3ff93c222ccca1be54fd4a0 > "$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/lite-xl__lite-xl-1460/tests/verifier.py b/tasks/lite-xl__lite-xl-1460/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1460/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/lite-xl__lite-xl-1477/environment/Dockerfile b/tasks/lite-xl__lite-xl-1477/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..607dae78e2b9f70eef68330036e68d93e3cf3dec --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f172e1366d9cb5204df0601709aa240d97d2c6e2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f172e1366d9cb5204df0601709aa240d97d2c6e2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f172e1366d9cb5204df0601709aa240d97d2c6e2 \ + && 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/lite-xl__lite-xl-1477/instruction.md b/tasks/lite-xl__lite-xl-1477/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f41fdead07a108e052898f630b26438337c3904d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** feat(process): allow commands and envs on proces_start + +## Description + +This would allow something like this: + +```lua +local cmd = { "bash", "-c", "echo $#", "--" } +for i = 1, 1000 do + table.insert(cmd, "wow" .. i) +end +process.start(cmd, { stdout = process.REDIRECT_PARENT }) +``` +To run correctly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f172e1366d9c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1477/solution/patch.diff b/tasks/lite-xl__lite-xl-1477/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..806bace9cb5d75830ce5de15bde95e8604dfdbb0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/solution/patch.diff @@ -0,0 +1,507 @@ +diff --git a/src/api/process.c b/src/api/process.c +index d7bfeb72..66f27536 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -31,6 +31,8 @@ + typedef DWORD process_error_t; + typedef HANDLE process_stream_t; + typedef HANDLE process_handle_t; ++typedef wchar_t process_arglist_t[32767]; ++typedef wchar_t *process_env_t; + + #define HANDLE_INVALID (INVALID_HANDLE_VALUE) + #define PROCESS_GET_HANDLE(P) ((P)->process_information.hProcess) +@@ -42,12 +44,20 @@ static volatile long PipeSerialNumber; + typedef int process_error_t; + typedef int process_stream_t; + typedef pid_t process_handle_t; ++typedef char **process_arglist_t; ++typedef char **process_env_t; + + #define HANDLE_INVALID (0) + #define PROCESS_GET_HANDLE(P) ((P)->pid) + + #endif + ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ + typedef struct { + bool running, detached; + int returncode, deadline; +@@ -339,51 +349,264 @@ static bool signal_process(process_t* proc, signal_e sig) { + return true; + } + ++ ++static UNUSED char *xstrdup(const char *str) { ++ char *result = str ? malloc(strlen(str) + 1) : NULL; ++ if (result) strcpy(result, str); ++ return result; ++} ++ ++ ++static int process_arglist_init(process_arglist_t *list, size_t *list_len, size_t nargs) { ++ *list_len = 0; ++#ifdef _WIN32 ++ memset(*list, 0, sizeof(process_arglist_t)); ++#else ++ *list = calloc(sizeof(char *), nargs + 1); ++ if (!*list) return ENOMEM; ++#endif ++ return 0; ++} ++ ++ ++static int process_arglist_add(process_arglist_t *list, size_t *list_len, const char *arg, bool escape) { ++ size_t len = *list_len; ++#ifdef _WIN32 ++ int arg_len; ++ wchar_t *cmdline = *list; ++ wchar_t arg_w[32767]; ++ // this length includes the null terminator! ++ if (!(arg_len = MultiByteToWideChar(CP_UTF8, 0, arg, -1, arg_w, 32767))) ++ return GetLastError(); ++ if (arg_len + len > 32767) ++ return ERROR_NOT_ENOUGH_MEMORY; ++ ++ if (!escape) { ++ // replace the current null terminator with a space ++ if (len > 0) cmdline[len-1] = ' '; ++ memcpy(cmdline + len, arg_w, arg_len * sizeof(wchar_t)); ++ len += arg_len; ++ } else { ++ // if the string contains spaces, then we must quote it ++ bool quote = wcspbrk(arg_w, L" \t\v\r\n"); ++ int backslash = 0, escaped_len = quote ? 2 : 0; ++ for (int i = 0; i < arg_len; i++) { ++ if (arg_w[i] == L'\\') { ++ backslash++; ++ } else if (arg_w[i] == L'"') { ++ escaped_len += backslash + 1; ++ backslash = 0; ++ } else { ++ backslash = 0; ++ } ++ escaped_len++; ++ } ++ // escape_len contains NUL terminator ++ if (escaped_len + len > 32767) ++ return ERROR_NOT_ENOUGH_MEMORY; ++ // replace our previous NUL terminator with space ++ if (len > 0) cmdline[len-1] = L' '; ++ if (quote) cmdline[len++] = L'"'; ++ // we are not going to iterate over NUL terminator ++ for (int i = 0;arg_w[i]; i++) { ++ if (arg_w[i] == L'\\') { ++ backslash++; ++ } else if (arg_w[i] == L'"') { ++ // add backslash + 1 backslashes ++ for (int j = 0; j < backslash; j++) ++ cmdline[len++] = L'\\'; ++ cmdline[len++] = L'\\'; ++ backslash = 0; ++ } else { ++ backslash = 0; ++ } ++ cmdline[len++] = arg_w[i]; ++ } ++ if (quote) cmdline[len++] = L'"'; ++ cmdline[len++] = L'\0'; ++ } ++#else ++ char **cmd = *list; ++ cmd[len] = xstrdup(arg); ++ if (!cmd[len]) return ENOMEM; ++ len++; ++#endif ++ *list_len = len; ++ return 0; ++} ++ ++ ++static void process_arglist_free(process_arglist_t *list) { ++#ifndef _WIN32 ++ char **cmd = *list; ++ for (int i = 0; cmd[i]; i++) ++ free(cmd[i]); ++ free(cmd); ++ *list = NULL; ++#endif ++} ++ ++ ++static int process_env_init(process_env_t *env_list, size_t *env_len, size_t nenv) { ++ *env_len = 0; ++#ifdef _WIN32 ++ *env_list = NULL; ++#else ++ *env_list = calloc(sizeof(char *), nenv * 2); ++ if (!*env_list) return ENOMEM; ++#endif ++ return 0; ++} ++ ++ ++#ifdef _WIN32 ++static int cmp_name(wchar_t *a, wchar_t *b) { ++ wchar_t _A[32767], _B[32767], *A = _A, *B = _B, *a_eq, *b_eq; ++ int na, nb, r; ++ a_eq = wcschr(a, L'='); ++ b_eq = wcschr(b, L'='); ++ assert(a_eq); ++ assert(b_eq); ++ na = a_eq - a; ++ nb = b_eq - b; ++ r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na); ++ assert(r == na); ++ A[na] = L'\0'; ++ r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb); ++ assert(r == nb); ++ B[nb] = L'\0'; ++ ++ for (;;) { ++ wchar_t AA = *A++, BB = *B++; ++ if (AA > BB) ++ return 1; ++ else if (AA < BB) ++ return -1; ++ else if (!AA && !BB) ++ return 0; ++ } ++} ++ ++ ++static int process_env_add_variable(process_env_t *env_list, size_t *env_list_len, wchar_t *var, size_t var_len) { ++ wchar_t *list, *list_p; ++ size_t block_var_len, list_len; ++ list = list_p = *env_list; ++ list_len = *env_list_len; ++ if (list_len) { ++ // check if it is already in the block ++ while ((block_var_len = wcslen(list_p))) { ++ if (cmp_name(list_p, var) == 0) ++ return -1; // already installed ++ list_p += block_var_len + 1; ++ } ++ } ++ // allocate list + 1 characters for the block terminator ++ list = realloc(list, (list_len + var_len + 1) * sizeof(wchar_t)); ++ if (!list) return ERROR_NOT_ENOUGH_MEMORY; ++ // copy the env variable to the block ++ memcpy(list + list_len, var, var_len * sizeof(wchar_t)); ++ // terminate the block again ++ list[list_len + var_len] = L'\0'; ++ *env_list = list; ++ *env_list_len = (list_len + var_len); ++ return 0; ++} ++ ++ ++static int process_env_add_system(process_env_t *env_list, size_t *env_list_len) { ++ int retval = 0; ++ wchar_t *proc_env_block, *proc_env_block_p; ++ int proc_env_len; ++ ++ proc_env_block = proc_env_block_p = GetEnvironmentStringsW(); ++ while ((proc_env_len = wcslen(proc_env_block_p))) { ++ // try to add it to the list ++ if ((retval = process_env_add_variable(env_list, env_list_len, proc_env_block_p, proc_env_len + 1)) > 0) ++ goto cleanup; ++ proc_env_block_p += proc_env_len + 1; ++ } ++ retval = 0; ++ ++cleanup: ++ if (proc_env_block) FreeEnvironmentStringsW(proc_env_block); ++ return retval; ++} ++#endif ++ ++ ++static int process_env_add(process_env_t *env_list, size_t *env_len, const char *key, const char *value) { ++#ifdef _WIN32 ++ wchar_t env_var[32767]; ++ int r, var_len = 0; ++ if (!(r = MultiByteToWideChar(CP_UTF8, 0, key, -1, env_var, 32767))) ++ return GetLastError(); ++ var_len += r; ++ env_var[var_len-1] = L'='; ++ if (!(r = MultiByteToWideChar(CP_UTF8, 0, value, -1, env_var + var_len, 32767 - var_len))) ++ return GetLastError(); ++ var_len += r; ++ return process_env_add_variable(env_list, env_len, env_var, var_len); ++#else ++ (*env_list)[*env_len] = xstrdup(key); ++ if (!(*env_list)[*env_len]) ++ return ENOMEM; ++ (*env_list)[*env_len + 1] = xstrdup(value); ++ if (!(*env_list)[*env_len + 1]) ++ return ENOMEM; ++ *env_len += 2; ++#endif ++ return 0; ++} ++ ++ ++static void process_env_free(process_env_t *list) { ++ if (!*list) return; ++#ifdef _WIN32 ++ free(*list); ++#else ++ for (size_t i = 0; (*list)[i]; i++) free((*list)[i]); ++ free(*list); ++#endif ++ *list = NULL; ++} ++ ++ + static int process_start(lua_State* L) { +- int retval = 1; +- size_t env_len = 0, key_len, val_len; +- const char *cmd[256] = { NULL }, *env_names[256] = { NULL }, *env_values[256] = { NULL }, *cwd = NULL; +- bool detach = false, literal = false; ++ int r, retval = 1; ++ size_t env_len = 0, cmd_len = 0, arglist_len = 0, env_vars_len = 0; ++ process_arglist_t arglist; ++ process_env_t env_vars = NULL; ++ const char *cwd = NULL; ++ bool detach = false, escape = true; + int deadline = 10, new_fds[3] = { STDIN_FD, STDOUT_FD, STDERR_FD }; +- size_t arg_len = lua_gettop(L), cmd_len; +- if (lua_type(L, 1) == LUA_TTABLE) { +- #if LUA_VERSION_NUM > 501 +- lua_len(L, 1); +- #else +- lua_pushinteger(L, (int)lua_objlen(L, 1)); +- #endif +- cmd_len = luaL_checknumber(L, -1); lua_pop(L, 1); +- if (!cmd_len) +- // we have not allocated anything here yet, so we can skip cleanup code +- // don't do this anywhere else! +- return luaL_argerror(L, 1,"table cannot be empty"); +- for (size_t i = 1; i <= cmd_len; ++i) { +- lua_pushinteger(L, i); +- lua_rawget(L, 1); +- cmd[i-1] = luaL_checkstring(L, -1); +- } +- } else { +- literal = true; +- cmd[0] = luaL_checkstring(L, 1); +- cmd_len = 1; ++ ++ if (lua_isstring(L, 1)) { ++ escape = false; ++ // create a table that contains the string as the value ++ lua_createtable(L, 1, 0); ++ lua_pushvalue(L, 1); ++ lua_rawseti(L, -2, 1); ++ lua_replace(L, 1); + } + +- if (arg_len > 1) { +- lua_getfield(L, 2, "env"); +- if (!lua_isnil(L, -1)) { +- lua_pushnil(L); +- while (lua_next(L, -2) != 0) { +- const char* key = luaL_checklstring(L, -2, &key_len); +- const char* val = luaL_checklstring(L, -1, &val_len); +- env_names[env_len] = malloc(key_len+1); +- strcpy((char*)env_names[env_len], key); +- env_values[env_len] = malloc(val_len+1); +- strcpy((char*)env_values[env_len], val); +- lua_pop(L, 1); +- ++env_len; +- } +- } else +- lua_pop(L, 1); ++ luaL_checktype(L, 1, LUA_TTABLE); ++ #if LUA_VERSION_NUM > 501 ++ lua_len(L, 1); ++ #else ++ lua_pushinteger(L, (int)lua_objlen(L, 1)); ++ #endif ++ cmd_len = luaL_checknumber(L, -1); lua_pop(L, 1); ++ if (!cmd_len) ++ return luaL_argerror(L, 1, "table cannot be empty"); ++ // check if each arguments is a string ++ for (size_t i = 1; i <= cmd_len; ++i) { ++ lua_rawgeti(L, 1, i); ++ luaL_checkstring(L, -1); ++ lua_pop(L, 1); ++ } ++ ++ if (lua_istable(L, 2)) { + lua_getfield(L, 2, "detach"); detach = lua_toboolean(L, -1); + lua_getfield(L, 2, "timeout"); deadline = luaL_optnumber(L, -1, deadline); + lua_getfield(L, 2, "cwd"); cwd = luaL_optstring(L, -1, NULL); +@@ -391,12 +614,55 @@ static int process_start(lua_State* L) { + lua_getfield(L, 2, "stdout"); new_fds[STDOUT_FD] = luaL_optnumber(L, -1, STDOUT_FD); + lua_getfield(L, 2, "stderr"); new_fds[STDERR_FD] = luaL_optnumber(L, -1, STDERR_FD); + for (int stream = STDIN_FD; stream <= STDERR_FD; ++stream) { +- if (new_fds[stream] > STDERR_FD || new_fds[stream] < REDIRECT_PARENT) { +- lua_pushfstring(L, "error: redirect to handles, FILE* and paths are not supported"); ++ if (new_fds[stream] > STDERR_FD || new_fds[stream] < REDIRECT_PARENT) ++ return luaL_error(L, "error: redirect to handles, FILE* and paths are not supported"); ++ } ++ lua_pop(L, 6); // pop all the values above ++ ++ luaL_getsubtable(L, 2, "env"); ++ // count environment variobles ++ lua_pushnil(L); ++ while (lua_next(L, -2) != 0) { ++ luaL_checkstring(L, -2); ++ luaL_checkstring(L, -1); ++ lua_pop(L, 1); ++ env_len++; ++ } ++ ++ if (env_len) { ++ if ((r = process_env_init(&env_vars, &env_vars_len, env_len)) != 0) { + retval = -1; ++ push_error(L, "cannot allocate environment list", r); + goto cleanup; + } ++ ++ lua_pushnil(L); ++ while (lua_next(L, -2) != 0) { ++ if ((r = process_env_add(&env_vars, &env_vars_len, lua_tostring(L, -2), lua_tostring(L, -1))) != 0) { ++ retval = -1; ++ push_error(L, "cannot copy environment variable", r); ++ goto cleanup; ++ } ++ lua_pop(L, 1); ++ env_len++; ++ } ++ } ++ } ++ ++ // allocate and copy commands ++ if ((r = process_arglist_init(&arglist, &arglist_len, cmd_len)) != 0) { ++ retval = -1; ++ push_error(L, "cannot create argument list", r); ++ goto cleanup; ++ } ++ for (size_t i = 1; i <= cmd_len; i++) { ++ lua_rawgeti(L, 1, i); ++ if ((r = process_arglist_add(&arglist, &arglist_len, lua_tostring(L, -1), escape)) != 0) { ++ retval = -1; ++ push_error(L, "cannot add argument", r); ++ goto cleanup; + } ++ lua_pop(L, 1); + } + + process_t* self = lua_newuserdata(L, sizeof(process_t)); +@@ -405,6 +671,13 @@ static int process_start(lua_State* L) { + self->deadline = deadline; + self->detached = detach; + #if _WIN32 ++ if (env_vars) { ++ if ((r = process_env_add_system(&env_vars, &env_vars_len)) != 0) { ++ retval = -1; ++ push_error(L, "cannot add environment variable", r); ++ goto cleanup; ++ } ++ } + for (int i = 0; i < 3; ++i) { + switch (new_fds[i]) { + case REDIRECT_PARENT: +@@ -455,7 +728,7 @@ static int process_start(lua_State* L) { + self->child_pipes[i][1] = self->child_pipes[new_fds[i]][1]; + } + } +- STARTUPINFO siStartInfo; ++ STARTUPINFOW siStartInfo; + memset(&self->process_information, 0, sizeof(self->process_information)); + memset(&siStartInfo, 0, sizeof(siStartInfo)); + siStartInfo.cb = sizeof(siStartInfo); +@@ -463,48 +736,10 @@ static int process_start(lua_State* L) { + siStartInfo.hStdInput = self->child_pipes[STDIN_FD][0]; + siStartInfo.hStdOutput = self->child_pipes[STDOUT_FD][1]; + siStartInfo.hStdError = self->child_pipes[STDERR_FD][1]; +- char commandLine[32767] = { 0 }, environmentBlock[32767], wideEnvironmentBlock[32767*2]; +- int offset = 0; +- if (!literal) { +- for (size_t i = 0; i < cmd_len; ++i) { +- size_t len = strlen(cmd[i]); +- if (offset + len + 2 >= sizeof(commandLine)) break; +- if (i > 0) +- commandLine[offset++] = ' '; +- commandLine[offset++] = '"'; +- int backslashCount = 0; // Yes, this is necessary. +- for (size_t j = 0; j < len && offset + 2 + backslashCount < sizeof(commandLine); ++j) { +- if (cmd[i][j] == '\\') +- ++backslashCount; +- else if (cmd[i][j] == '"') { +- for (size_t k = 0; k < backslashCount; ++k) +- commandLine[offset++] = '\\'; +- commandLine[offset++] = '\\'; +- backslashCount = 0; +- } else +- backslashCount = 0; +- commandLine[offset++] = cmd[i][j]; +- } +- if (offset + 1 + backslashCount >= sizeof(commandLine)) break; +- for (size_t k = 0; k < backslashCount; ++k) +- commandLine[offset++] = '\\'; +- commandLine[offset++] = '"'; +- } +- commandLine[offset] = 0; +- } else { +- strncpy(commandLine, cmd[0], sizeof(commandLine)); +- } +- offset = 0; +- for (size_t i = 0; i < env_len; ++i) { +- if (offset + strlen(env_values[i]) + strlen(env_names[i]) + 1 >= sizeof(environmentBlock)) +- break; +- offset += snprintf(&environmentBlock[offset], sizeof(environmentBlock) - offset, "%s=%s", env_names[i], env_values[i]); +- environmentBlock[offset++] = 0; +- } +- environmentBlock[offset++] = 0; +- if (env_len > 0) +- MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, environmentBlock, offset, (LPWSTR)wideEnvironmentBlock, sizeof(wideEnvironmentBlock)); +- if (!CreateProcess(NULL, commandLine, NULL, NULL, true, (detach ? DETACHED_PROCESS : CREATE_NO_WINDOW) | CREATE_UNICODE_ENVIRONMENT, env_len > 0 ? wideEnvironmentBlock : NULL, cwd, &siStartInfo, &self->process_information)) { ++ wchar_t cwd_w[MAX_PATH]; ++ if (cwd) // TODO: error handling ++ MultiByteToWideChar(CP_UTF8, 0, cwd, -1, cwd_w, MAX_PATH); ++ if (!CreateProcessW(NULL, arglist, NULL, NULL, true, (detach ? DETACHED_PROCESS : CREATE_NO_WINDOW) | CREATE_UNICODE_ENVIRONMENT, env_vars, cwd ? cwd_w : NULL, &siStartInfo, &self->process_information)) { + push_error(L, NULL, GetLastError()); + retval = -1; + goto cleanup; +@@ -552,9 +787,9 @@ static int process_start(lua_State* L) { + close(self->child_pipes[stream][stream == STDIN_FD ? 1 : 0]); + } + size_t set; +- for (set = 0; set < env_len && setenv(env_names[set], env_values[set], 1) == 0; ++set); +- if (set == env_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) +- execvp(cmd[0], (char** const)cmd); ++ for (set = 0; set < env_vars_len && setenv(env_vars[set], env_vars[set+1], 1) == 0; set += 2); ++ if (set == env_vars_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) ++ execvp(arglist[0], (char** const)arglist); + write(control_pipe[1], &errno, sizeof(errno)); + _exit(-1); + } +@@ -588,16 +823,15 @@ static int process_start(lua_State* L) { + if (control_pipe[0]) close(control_pipe[0]); + if (control_pipe[1]) close(control_pipe[1]); + #endif +- for (size_t i = 0; i < env_len; ++i) { +- free((char*)env_names[i]); +- free((char*)env_values[i]); +- } + for (int stream = 0; stream < 3; ++stream) { + process_stream_t* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; + if (*pipe) { + close_fd(pipe); + } + } ++ process_arglist_free(&arglist); ++ process_env_free(&env_vars); ++ + if (retval == -1) + return lua_error(L); + diff --git a/tasks/lite-xl__lite-xl-1477/solution/solve.sh b/tasks/lite-xl__lite-xl-1477/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/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/lite-xl__lite-xl-1477/task.toml b/tasks/lite-xl__lite-xl-1477/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ec163cd36d95b04826e637e4534f76728333249e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1477" +description = "feat(process): allow commands and envs on proces_start" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f172e1366d9cb5204df0601709aa240d97d2c6e2" +reference = "https://github.com/lite-xl/lite-xl/pull/1477" +source_access = "auto" +built_at = "2026-11-16T16:09:56.215438+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6ff95d770ebd4cb85be56a9c9f156c834c0838969d9523a693959aac446cc146" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-11-30T15:33:25Z" +diff_format = "unified" +context_files = [ + "src/api/process.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 420 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.285614+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:35aa0c8d428aa4923d3d027efd1395302ecd0d04547d41ac1d99f921e7db38bf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1477/tests/capture.py b/tasks/lite-xl__lite-xl-1477/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/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/lite-xl__lite-xl-1477/tests/instruction.md b/tasks/lite-xl__lite-xl-1477/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f41fdead07a108e052898f630b26438337c3904d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** feat(process): allow commands and envs on proces_start + +## Description + +This would allow something like this: + +```lua +local cmd = { "bash", "-c", "echo $#", "--" } +for i = 1, 1000 do + table.insert(cmd, "wow" .. i) +end +process.start(cmd, { stdout = process.REDIRECT_PARENT }) +``` +To run correctly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f172e1366d9c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1477/tests/oracle.patch b/tasks/lite-xl__lite-xl-1477/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..806bace9cb5d75830ce5de15bde95e8604dfdbb0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/tests/oracle.patch @@ -0,0 +1,507 @@ +diff --git a/src/api/process.c b/src/api/process.c +index d7bfeb72..66f27536 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -31,6 +31,8 @@ + typedef DWORD process_error_t; + typedef HANDLE process_stream_t; + typedef HANDLE process_handle_t; ++typedef wchar_t process_arglist_t[32767]; ++typedef wchar_t *process_env_t; + + #define HANDLE_INVALID (INVALID_HANDLE_VALUE) + #define PROCESS_GET_HANDLE(P) ((P)->process_information.hProcess) +@@ -42,12 +44,20 @@ static volatile long PipeSerialNumber; + typedef int process_error_t; + typedef int process_stream_t; + typedef pid_t process_handle_t; ++typedef char **process_arglist_t; ++typedef char **process_env_t; + + #define HANDLE_INVALID (0) + #define PROCESS_GET_HANDLE(P) ((P)->pid) + + #endif + ++#ifdef __GNUC__ ++#define UNUSED __attribute__((__unused__)) ++#else ++#define UNUSED ++#endif ++ + typedef struct { + bool running, detached; + int returncode, deadline; +@@ -339,51 +349,264 @@ static bool signal_process(process_t* proc, signal_e sig) { + return true; + } + ++ ++static UNUSED char *xstrdup(const char *str) { ++ char *result = str ? malloc(strlen(str) + 1) : NULL; ++ if (result) strcpy(result, str); ++ return result; ++} ++ ++ ++static int process_arglist_init(process_arglist_t *list, size_t *list_len, size_t nargs) { ++ *list_len = 0; ++#ifdef _WIN32 ++ memset(*list, 0, sizeof(process_arglist_t)); ++#else ++ *list = calloc(sizeof(char *), nargs + 1); ++ if (!*list) return ENOMEM; ++#endif ++ return 0; ++} ++ ++ ++static int process_arglist_add(process_arglist_t *list, size_t *list_len, const char *arg, bool escape) { ++ size_t len = *list_len; ++#ifdef _WIN32 ++ int arg_len; ++ wchar_t *cmdline = *list; ++ wchar_t arg_w[32767]; ++ // this length includes the null terminator! ++ if (!(arg_len = MultiByteToWideChar(CP_UTF8, 0, arg, -1, arg_w, 32767))) ++ return GetLastError(); ++ if (arg_len + len > 32767) ++ return ERROR_NOT_ENOUGH_MEMORY; ++ ++ if (!escape) { ++ // replace the current null terminator with a space ++ if (len > 0) cmdline[len-1] = ' '; ++ memcpy(cmdline + len, arg_w, arg_len * sizeof(wchar_t)); ++ len += arg_len; ++ } else { ++ // if the string contains spaces, then we must quote it ++ bool quote = wcspbrk(arg_w, L" \t\v\r\n"); ++ int backslash = 0, escaped_len = quote ? 2 : 0; ++ for (int i = 0; i < arg_len; i++) { ++ if (arg_w[i] == L'\\') { ++ backslash++; ++ } else if (arg_w[i] == L'"') { ++ escaped_len += backslash + 1; ++ backslash = 0; ++ } else { ++ backslash = 0; ++ } ++ escaped_len++; ++ } ++ // escape_len contains NUL terminator ++ if (escaped_len + len > 32767) ++ return ERROR_NOT_ENOUGH_MEMORY; ++ // replace our previous NUL terminator with space ++ if (len > 0) cmdline[len-1] = L' '; ++ if (quote) cmdline[len++] = L'"'; ++ // we are not going to iterate over NUL terminator ++ for (int i = 0;arg_w[i]; i++) { ++ if (arg_w[i] == L'\\') { ++ backslash++; ++ } else if (arg_w[i] == L'"') { ++ // add backslash + 1 backslashes ++ for (int j = 0; j < backslash; j++) ++ cmdline[len++] = L'\\'; ++ cmdline[len++] = L'\\'; ++ backslash = 0; ++ } else { ++ backslash = 0; ++ } ++ cmdline[len++] = arg_w[i]; ++ } ++ if (quote) cmdline[len++] = L'"'; ++ cmdline[len++] = L'\0'; ++ } ++#else ++ char **cmd = *list; ++ cmd[len] = xstrdup(arg); ++ if (!cmd[len]) return ENOMEM; ++ len++; ++#endif ++ *list_len = len; ++ return 0; ++} ++ ++ ++static void process_arglist_free(process_arglist_t *list) { ++#ifndef _WIN32 ++ char **cmd = *list; ++ for (int i = 0; cmd[i]; i++) ++ free(cmd[i]); ++ free(cmd); ++ *list = NULL; ++#endif ++} ++ ++ ++static int process_env_init(process_env_t *env_list, size_t *env_len, size_t nenv) { ++ *env_len = 0; ++#ifdef _WIN32 ++ *env_list = NULL; ++#else ++ *env_list = calloc(sizeof(char *), nenv * 2); ++ if (!*env_list) return ENOMEM; ++#endif ++ return 0; ++} ++ ++ ++#ifdef _WIN32 ++static int cmp_name(wchar_t *a, wchar_t *b) { ++ wchar_t _A[32767], _B[32767], *A = _A, *B = _B, *a_eq, *b_eq; ++ int na, nb, r; ++ a_eq = wcschr(a, L'='); ++ b_eq = wcschr(b, L'='); ++ assert(a_eq); ++ assert(b_eq); ++ na = a_eq - a; ++ nb = b_eq - b; ++ r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, a, na, A, na); ++ assert(r == na); ++ A[na] = L'\0'; ++ r = LCMapStringW(LOCALE_INVARIANT, LCMAP_UPPERCASE, b, nb, B, nb); ++ assert(r == nb); ++ B[nb] = L'\0'; ++ ++ for (;;) { ++ wchar_t AA = *A++, BB = *B++; ++ if (AA > BB) ++ return 1; ++ else if (AA < BB) ++ return -1; ++ else if (!AA && !BB) ++ return 0; ++ } ++} ++ ++ ++static int process_env_add_variable(process_env_t *env_list, size_t *env_list_len, wchar_t *var, size_t var_len) { ++ wchar_t *list, *list_p; ++ size_t block_var_len, list_len; ++ list = list_p = *env_list; ++ list_len = *env_list_len; ++ if (list_len) { ++ // check if it is already in the block ++ while ((block_var_len = wcslen(list_p))) { ++ if (cmp_name(list_p, var) == 0) ++ return -1; // already installed ++ list_p += block_var_len + 1; ++ } ++ } ++ // allocate list + 1 characters for the block terminator ++ list = realloc(list, (list_len + var_len + 1) * sizeof(wchar_t)); ++ if (!list) return ERROR_NOT_ENOUGH_MEMORY; ++ // copy the env variable to the block ++ memcpy(list + list_len, var, var_len * sizeof(wchar_t)); ++ // terminate the block again ++ list[list_len + var_len] = L'\0'; ++ *env_list = list; ++ *env_list_len = (list_len + var_len); ++ return 0; ++} ++ ++ ++static int process_env_add_system(process_env_t *env_list, size_t *env_list_len) { ++ int retval = 0; ++ wchar_t *proc_env_block, *proc_env_block_p; ++ int proc_env_len; ++ ++ proc_env_block = proc_env_block_p = GetEnvironmentStringsW(); ++ while ((proc_env_len = wcslen(proc_env_block_p))) { ++ // try to add it to the list ++ if ((retval = process_env_add_variable(env_list, env_list_len, proc_env_block_p, proc_env_len + 1)) > 0) ++ goto cleanup; ++ proc_env_block_p += proc_env_len + 1; ++ } ++ retval = 0; ++ ++cleanup: ++ if (proc_env_block) FreeEnvironmentStringsW(proc_env_block); ++ return retval; ++} ++#endif ++ ++ ++static int process_env_add(process_env_t *env_list, size_t *env_len, const char *key, const char *value) { ++#ifdef _WIN32 ++ wchar_t env_var[32767]; ++ int r, var_len = 0; ++ if (!(r = MultiByteToWideChar(CP_UTF8, 0, key, -1, env_var, 32767))) ++ return GetLastError(); ++ var_len += r; ++ env_var[var_len-1] = L'='; ++ if (!(r = MultiByteToWideChar(CP_UTF8, 0, value, -1, env_var + var_len, 32767 - var_len))) ++ return GetLastError(); ++ var_len += r; ++ return process_env_add_variable(env_list, env_len, env_var, var_len); ++#else ++ (*env_list)[*env_len] = xstrdup(key); ++ if (!(*env_list)[*env_len]) ++ return ENOMEM; ++ (*env_list)[*env_len + 1] = xstrdup(value); ++ if (!(*env_list)[*env_len + 1]) ++ return ENOMEM; ++ *env_len += 2; ++#endif ++ return 0; ++} ++ ++ ++static void process_env_free(process_env_t *list) { ++ if (!*list) return; ++#ifdef _WIN32 ++ free(*list); ++#else ++ for (size_t i = 0; (*list)[i]; i++) free((*list)[i]); ++ free(*list); ++#endif ++ *list = NULL; ++} ++ ++ + static int process_start(lua_State* L) { +- int retval = 1; +- size_t env_len = 0, key_len, val_len; +- const char *cmd[256] = { NULL }, *env_names[256] = { NULL }, *env_values[256] = { NULL }, *cwd = NULL; +- bool detach = false, literal = false; ++ int r, retval = 1; ++ size_t env_len = 0, cmd_len = 0, arglist_len = 0, env_vars_len = 0; ++ process_arglist_t arglist; ++ process_env_t env_vars = NULL; ++ const char *cwd = NULL; ++ bool detach = false, escape = true; + int deadline = 10, new_fds[3] = { STDIN_FD, STDOUT_FD, STDERR_FD }; +- size_t arg_len = lua_gettop(L), cmd_len; +- if (lua_type(L, 1) == LUA_TTABLE) { +- #if LUA_VERSION_NUM > 501 +- lua_len(L, 1); +- #else +- lua_pushinteger(L, (int)lua_objlen(L, 1)); +- #endif +- cmd_len = luaL_checknumber(L, -1); lua_pop(L, 1); +- if (!cmd_len) +- // we have not allocated anything here yet, so we can skip cleanup code +- // don't do this anywhere else! +- return luaL_argerror(L, 1,"table cannot be empty"); +- for (size_t i = 1; i <= cmd_len; ++i) { +- lua_pushinteger(L, i); +- lua_rawget(L, 1); +- cmd[i-1] = luaL_checkstring(L, -1); +- } +- } else { +- literal = true; +- cmd[0] = luaL_checkstring(L, 1); +- cmd_len = 1; ++ ++ if (lua_isstring(L, 1)) { ++ escape = false; ++ // create a table that contains the string as the value ++ lua_createtable(L, 1, 0); ++ lua_pushvalue(L, 1); ++ lua_rawseti(L, -2, 1); ++ lua_replace(L, 1); + } + +- if (arg_len > 1) { +- lua_getfield(L, 2, "env"); +- if (!lua_isnil(L, -1)) { +- lua_pushnil(L); +- while (lua_next(L, -2) != 0) { +- const char* key = luaL_checklstring(L, -2, &key_len); +- const char* val = luaL_checklstring(L, -1, &val_len); +- env_names[env_len] = malloc(key_len+1); +- strcpy((char*)env_names[env_len], key); +- env_values[env_len] = malloc(val_len+1); +- strcpy((char*)env_values[env_len], val); +- lua_pop(L, 1); +- ++env_len; +- } +- } else +- lua_pop(L, 1); ++ luaL_checktype(L, 1, LUA_TTABLE); ++ #if LUA_VERSION_NUM > 501 ++ lua_len(L, 1); ++ #else ++ lua_pushinteger(L, (int)lua_objlen(L, 1)); ++ #endif ++ cmd_len = luaL_checknumber(L, -1); lua_pop(L, 1); ++ if (!cmd_len) ++ return luaL_argerror(L, 1, "table cannot be empty"); ++ // check if each arguments is a string ++ for (size_t i = 1; i <= cmd_len; ++i) { ++ lua_rawgeti(L, 1, i); ++ luaL_checkstring(L, -1); ++ lua_pop(L, 1); ++ } ++ ++ if (lua_istable(L, 2)) { + lua_getfield(L, 2, "detach"); detach = lua_toboolean(L, -1); + lua_getfield(L, 2, "timeout"); deadline = luaL_optnumber(L, -1, deadline); + lua_getfield(L, 2, "cwd"); cwd = luaL_optstring(L, -1, NULL); +@@ -391,12 +614,55 @@ static int process_start(lua_State* L) { + lua_getfield(L, 2, "stdout"); new_fds[STDOUT_FD] = luaL_optnumber(L, -1, STDOUT_FD); + lua_getfield(L, 2, "stderr"); new_fds[STDERR_FD] = luaL_optnumber(L, -1, STDERR_FD); + for (int stream = STDIN_FD; stream <= STDERR_FD; ++stream) { +- if (new_fds[stream] > STDERR_FD || new_fds[stream] < REDIRECT_PARENT) { +- lua_pushfstring(L, "error: redirect to handles, FILE* and paths are not supported"); ++ if (new_fds[stream] > STDERR_FD || new_fds[stream] < REDIRECT_PARENT) ++ return luaL_error(L, "error: redirect to handles, FILE* and paths are not supported"); ++ } ++ lua_pop(L, 6); // pop all the values above ++ ++ luaL_getsubtable(L, 2, "env"); ++ // count environment variobles ++ lua_pushnil(L); ++ while (lua_next(L, -2) != 0) { ++ luaL_checkstring(L, -2); ++ luaL_checkstring(L, -1); ++ lua_pop(L, 1); ++ env_len++; ++ } ++ ++ if (env_len) { ++ if ((r = process_env_init(&env_vars, &env_vars_len, env_len)) != 0) { + retval = -1; ++ push_error(L, "cannot allocate environment list", r); + goto cleanup; + } ++ ++ lua_pushnil(L); ++ while (lua_next(L, -2) != 0) { ++ if ((r = process_env_add(&env_vars, &env_vars_len, lua_tostring(L, -2), lua_tostring(L, -1))) != 0) { ++ retval = -1; ++ push_error(L, "cannot copy environment variable", r); ++ goto cleanup; ++ } ++ lua_pop(L, 1); ++ env_len++; ++ } ++ } ++ } ++ ++ // allocate and copy commands ++ if ((r = process_arglist_init(&arglist, &arglist_len, cmd_len)) != 0) { ++ retval = -1; ++ push_error(L, "cannot create argument list", r); ++ goto cleanup; ++ } ++ for (size_t i = 1; i <= cmd_len; i++) { ++ lua_rawgeti(L, 1, i); ++ if ((r = process_arglist_add(&arglist, &arglist_len, lua_tostring(L, -1), escape)) != 0) { ++ retval = -1; ++ push_error(L, "cannot add argument", r); ++ goto cleanup; + } ++ lua_pop(L, 1); + } + + process_t* self = lua_newuserdata(L, sizeof(process_t)); +@@ -405,6 +671,13 @@ static int process_start(lua_State* L) { + self->deadline = deadline; + self->detached = detach; + #if _WIN32 ++ if (env_vars) { ++ if ((r = process_env_add_system(&env_vars, &env_vars_len)) != 0) { ++ retval = -1; ++ push_error(L, "cannot add environment variable", r); ++ goto cleanup; ++ } ++ } + for (int i = 0; i < 3; ++i) { + switch (new_fds[i]) { + case REDIRECT_PARENT: +@@ -455,7 +728,7 @@ static int process_start(lua_State* L) { + self->child_pipes[i][1] = self->child_pipes[new_fds[i]][1]; + } + } +- STARTUPINFO siStartInfo; ++ STARTUPINFOW siStartInfo; + memset(&self->process_information, 0, sizeof(self->process_information)); + memset(&siStartInfo, 0, sizeof(siStartInfo)); + siStartInfo.cb = sizeof(siStartInfo); +@@ -463,48 +736,10 @@ static int process_start(lua_State* L) { + siStartInfo.hStdInput = self->child_pipes[STDIN_FD][0]; + siStartInfo.hStdOutput = self->child_pipes[STDOUT_FD][1]; + siStartInfo.hStdError = self->child_pipes[STDERR_FD][1]; +- char commandLine[32767] = { 0 }, environmentBlock[32767], wideEnvironmentBlock[32767*2]; +- int offset = 0; +- if (!literal) { +- for (size_t i = 0; i < cmd_len; ++i) { +- size_t len = strlen(cmd[i]); +- if (offset + len + 2 >= sizeof(commandLine)) break; +- if (i > 0) +- commandLine[offset++] = ' '; +- commandLine[offset++] = '"'; +- int backslashCount = 0; // Yes, this is necessary. +- for (size_t j = 0; j < len && offset + 2 + backslashCount < sizeof(commandLine); ++j) { +- if (cmd[i][j] == '\\') +- ++backslashCount; +- else if (cmd[i][j] == '"') { +- for (size_t k = 0; k < backslashCount; ++k) +- commandLine[offset++] = '\\'; +- commandLine[offset++] = '\\'; +- backslashCount = 0; +- } else +- backslashCount = 0; +- commandLine[offset++] = cmd[i][j]; +- } +- if (offset + 1 + backslashCount >= sizeof(commandLine)) break; +- for (size_t k = 0; k < backslashCount; ++k) +- commandLine[offset++] = '\\'; +- commandLine[offset++] = '"'; +- } +- commandLine[offset] = 0; +- } else { +- strncpy(commandLine, cmd[0], sizeof(commandLine)); +- } +- offset = 0; +- for (size_t i = 0; i < env_len; ++i) { +- if (offset + strlen(env_values[i]) + strlen(env_names[i]) + 1 >= sizeof(environmentBlock)) +- break; +- offset += snprintf(&environmentBlock[offset], sizeof(environmentBlock) - offset, "%s=%s", env_names[i], env_values[i]); +- environmentBlock[offset++] = 0; +- } +- environmentBlock[offset++] = 0; +- if (env_len > 0) +- MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, environmentBlock, offset, (LPWSTR)wideEnvironmentBlock, sizeof(wideEnvironmentBlock)); +- if (!CreateProcess(NULL, commandLine, NULL, NULL, true, (detach ? DETACHED_PROCESS : CREATE_NO_WINDOW) | CREATE_UNICODE_ENVIRONMENT, env_len > 0 ? wideEnvironmentBlock : NULL, cwd, &siStartInfo, &self->process_information)) { ++ wchar_t cwd_w[MAX_PATH]; ++ if (cwd) // TODO: error handling ++ MultiByteToWideChar(CP_UTF8, 0, cwd, -1, cwd_w, MAX_PATH); ++ if (!CreateProcessW(NULL, arglist, NULL, NULL, true, (detach ? DETACHED_PROCESS : CREATE_NO_WINDOW) | CREATE_UNICODE_ENVIRONMENT, env_vars, cwd ? cwd_w : NULL, &siStartInfo, &self->process_information)) { + push_error(L, NULL, GetLastError()); + retval = -1; + goto cleanup; +@@ -552,9 +787,9 @@ static int process_start(lua_State* L) { + close(self->child_pipes[stream][stream == STDIN_FD ? 1 : 0]); + } + size_t set; +- for (set = 0; set < env_len && setenv(env_names[set], env_values[set], 1) == 0; ++set); +- if (set == env_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) +- execvp(cmd[0], (char** const)cmd); ++ for (set = 0; set < env_vars_len && setenv(env_vars[set], env_vars[set+1], 1) == 0; set += 2); ++ if (set == env_vars_len && (!detach || setsid() != -1) && (!cwd || chdir(cwd) != -1)) ++ execvp(arglist[0], (char** const)arglist); + write(control_pipe[1], &errno, sizeof(errno)); + _exit(-1); + } +@@ -588,16 +823,15 @@ static int process_start(lua_State* L) { + if (control_pipe[0]) close(control_pipe[0]); + if (control_pipe[1]) close(control_pipe[1]); + #endif +- for (size_t i = 0; i < env_len; ++i) { +- free((char*)env_names[i]); +- free((char*)env_values[i]); +- } + for (int stream = 0; stream < 3; ++stream) { + process_stream_t* pipe = &self->child_pipes[stream][stream == STDIN_FD ? 0 : 1]; + if (*pipe) { + close_fd(pipe); + } + } ++ process_arglist_free(&arglist); ++ process_env_free(&env_vars); ++ + if (retval == -1) + return lua_error(L); + diff --git a/tasks/lite-xl__lite-xl-1477/tests/test.sh b/tasks/lite-xl__lite-xl-1477/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c471d149f5139733ce1a8026137948c21c26d2ab --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/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 f172e1366d9cb5204df0601709aa240d97d2c6e2 > "$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/lite-xl__lite-xl-1477/tests/verifier.py b/tasks/lite-xl__lite-xl-1477/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1477/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/lite-xl__lite-xl-1510/environment/Dockerfile b/tasks/lite-xl__lite-xl-1510/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8730ec3f034bbfbf2d24f015d0a572f93c61241b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7a218f31811812a910dfbfc229b1d5d0a8504141 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7a218f31811812a910dfbfc229b1d5d0a8504141 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7a218f31811812a910dfbfc229b1d5d0a8504141 \ + && 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/lite-xl__lite-xl-1510/instruction.md b/tasks/lite-xl__lite-xl-1510/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c608481b7fa8a5a3ff62671efb4dd6afa2341321 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.common + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7a218f318118`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1510/solution/patch.diff b/tasks/lite-xl__lite-xl-1510/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..95d3964a2034e8dcb877c085064dbc553fbc1bbc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/solution/patch.diff @@ -0,0 +1,428 @@ +diff --git a/data/core/common.lua b/data/core/common.lua +index b6c9db67..272f0d5d 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -1,22 +1,41 @@ + local common = {} + + ++---Checks if the byte at offset is a UTF-8 continuation byte. ++--- ++---UTF-8 encodes code points in 1 to 4 bytes. ++---For a multi-byte sequence, each byte following the start byte is a continuation byte. ++---@param s string ++---@param offset? integer The offset of the string to start searching. Defaults to 1. ++---@return boolean + function common.is_utf8_cont(s, offset) + local byte = s:byte(offset or 1) + return byte >= 0x80 and byte < 0xc0 + end + + ++---Returns an iterator that yields a UTF-8 character on each iteration. ++---@param text string ++---@return fun(): string + function common.utf8_chars(text) + return text:gmatch("[\0-\x7f\xc2-\xf4][\x80-\xbf]*") + end + + ++---Clamps the number n between lo and hi. ++---@param n number ++---@param lo number ++---@param hi number ++---@return number + function common.clamp(n, lo, hi) + return math.max(math.min(n, hi), lo) + end + + ++---Returns a new table containing the contents of b merged into a. ++---@param a table|nil ++---@param b table? ++---@return table + function common.merge(a, b) + a = type(a) == "table" and a or {} + local t = {} +@@ -32,11 +51,19 @@ function common.merge(a, b) + end + + ++---Returns the value of a number rounded to the nearest integer. ++---@param n number ++---@return number + function common.round(n) + return n >= 0 and math.floor(n + 0.5) or math.ceil(n - 0.5) + end + + ++---Returns the first index where a subtable in tbl has prop set. ++---If none is found, nil is returned. ++---@param tbl table ++---@param prop any ++---@return number|nil + function common.find_index(tbl, prop) + for i, o in ipairs(tbl) do + if o[prop] then return i end +@@ -44,6 +71,16 @@ function common.find_index(tbl, prop) + end + + ++---Returns a value between a and b on a linear scale, based on the ++---interpolation point t. ++--- ++---If a and b are tables, a table containing the result for all the ++---elements in a and b is returned. ++---@param a number ++---@param b number ++---@param t number ++---@return number ++---@overload fun(a: table, b: table, t: number): table + function common.lerp(a, b, t) + if type(a) ~= "table" then + return a + (b - a) * t +@@ -56,11 +93,29 @@ function common.lerp(a, b, t) + end + + ++---Returns the euclidean distance between two points. ++---@param x1 number ++---@param y1 number ++---@param x2 number ++---@param y2 number ++---@return number + function common.distance(x1, y1, x2, y2) + return math.sqrt(((x2-x1) ^ 2)+((y2-y1) ^ 2)) + end + + ++---Parses a CSS color string. ++--- ++---Only these formats are supported: ++---* `rgb(r, g, b)` ++---* `rgba(r, g, b, a)` ++---* `#rrggbbaa` ++---* `#rrggbb` ++---@param str string ++---@return number r ++---@return number g ++---@return number b ++---@return number a + function common.color(str) + local r, g, b, a = str:match("^#(%x%x)(%x%x)(%x%x)(%x?%x?)$") + if r then +@@ -81,6 +136,12 @@ function common.color(str) + end + + ++---Splices a numerically indexed table. ++---This function mutates the original table. ++---@param t any[] ++---@param at number Index at which to start splicing. ++---@param remove number Number of elements to remove. ++---@param insert? any[] A table containing elements to insert after splicing. + function common.splice(t, at, remove, insert) + assert(remove >= 0, "bad argument #3 to 'splice' (non-negative value expected)") + insert = insert or {} +@@ -110,6 +171,16 @@ local function fuzzy_match_items(items, needle, files) + end + + ++---Performs fuzzy matching. ++--- ++---If the haystack is a string, a score ranging from 0 to 1 is returned.
++---If the haystack is a table, a table containing the haystack sorted in ascending ++---order of similarity is returned. ++---@param haystack string ++---@param needle string ++---@param files boolean If true, the matching process will be performed in reverse to better match paths. ++---@return number ++---@overload fun(haystack: string[], needle: string, files: boolean): string[] + function common.fuzzy_match(haystack, needle, files) + if type(haystack) == "table" then + return fuzzy_match_items(haystack, needle, files) +@@ -118,6 +189,14 @@ function common.fuzzy_match(haystack, needle, files) + end + + ++---Performs fuzzy matching and returns recently used strings if needed. ++--- ++---If the needle is empty, then a list of recently used strings ++---are added to the result, followed by strings from the haystack. ++---@param haystack string[] ++---@param recents string[] ++---@param needle string ++---@return string[] + function common.fuzzy_match_with_recents(haystack, recents, needle) + if needle == "" then + local recents_ext = {} +@@ -136,6 +215,13 @@ function common.fuzzy_match_with_recents(haystack, recents, needle) + end + + ++---Returns a list of paths that are relative to the input path. ++--- ++---If a root directory is specified, the function returns paths ++---that are relative to the root directory. ++---@param text string The input path. ++---@param root? string The root directory. ++---@return string[] + function common.path_suggest(text, root) + if root and root:sub(-1) ~= PATHSEP then + root = root .. PATHSEP +@@ -189,6 +275,9 @@ function common.path_suggest(text, root) + end + + ++---Returns a list of directories that are related to a path. ++---@param text string The input path. ++---@return string[] + function common.dir_path_suggest(text) + local path, name = text:match("^(.-)([^/\\]*)$") + local files = system.list_dir(path == "" and "." or path) or {} +@@ -204,6 +293,10 @@ function common.dir_path_suggest(text) + end + + ++---Filters a list of paths to find those that are related to the input path. ++---@param text string The input path. ++---@param dir_list string[] A list of paths to filter. ++---@return string[] + function common.dir_list_suggest(text, dir_list) + local path, name = text:match("^(.-)([^/\\]*)$") + local res = {} +@@ -216,6 +309,15 @@ function common.dir_list_suggest(text, dir_list) + end + + ++---Matches a string against a list of patterns. ++--- ++---If a match was found, its start and end index is returned. ++---Otherwise, false is returned. ++---@param text string ++---@param pattern string|string[] ++---@param ... any Other options for string.find(). ++---@return number|boolean start_index ++---@return number|nil end_index + function common.match_pattern(text, pattern, ...) + if type(pattern) == "string" then + return text:find(pattern, ...) +@@ -228,8 +330,24 @@ function common.match_pattern(text, pattern, ...) + end + + ++---Draws text onto the window. ++---The function returns the X and Y coordinates of the bottom-right ++---corner of the text. ++---@param font renderer.font ++---@param color renderer.color ++---@param text string ++---@param align string ++---| '"left"' # Align text to the left of the bounding box ++---| '"right"' # Align text to the right of the bounding box ++---| '"center"' # Center text in the bounding box ++---@param x number ++---@param y number ++---@param w number ++---@param h number ++---@return number x_advance ++---@return number y_advance + function common.draw_text(font, color, text, align, x,y,w,h) +- local tw, th = font:get_width(text), font:get_height(text) ++ local tw, th = font:get_width(text), font:get_height() + if align == "center" then + x = x + (w - tw) / 2 + elseif align == "right" then +@@ -240,6 +358,16 @@ function common.draw_text(font, color, text, align, x,y,w,h) + end + + ++---Prints the execution time of a function. ++--- ++---The execution time and percentage of frame time ++---for the function is printed to standard output.
++---The frame rate is always assumed to be 60 FPS, thus ++---a value of 100% would mean that the benchmark took ++---1/60 of a second to execute. ++---@param name string ++---@param fn fun(...: any): any ++---@return any # The result returned by the function + function common.bench(name, fn, ...) + local start = system.get_time() + local res = fn(...) +@@ -285,14 +413,28 @@ local function serialize(val, pretty, indent_str, escape, sort, limit, level) + return tostring(val) + end + +--- Serialize `val` into a parsable string. +--- Available options +--- * pretty: enable pretty printing +--- * indent_str: indent to use (" " by default) +--- * escape: use normal escape characters instead of the ones used by string.format("%q", ...) +--- * sort: sort the keys inside tables +--- * limit: limit how deep to serialize +--- * initial_indent: the initial indentation level ++ ++---@class common.serializeoptions ++---@field pretty boolean Enables pretty printing. ++---@field indent_str string The indentation character to use. Defaults to `" "`. ++---@field escape boolean Uses normal escape characters ("\n") instead of decimal escape sequences ("\10"). ++---@field limit number Limits the depth when serializing nested tables. Defaults to `math.huge`. ++---@field sort boolean Sorts the output if it is a sortable table. ++---@field initial_indent number The initial indentation level. Defaults to 0. ++ ++---Serializes a value into a Lua string that is loadable with load(). ++--- ++---Only these basic types are supported: ++---* nil ++---* boolean ++---* number (except very large numbers and special constants, e.g. `math.huge`, `inf` and `nan`) ++---* integer ++---* string ++---* table ++--- ++---@param val any ++---@param opts? common.serializeoptions ++---@return string + function common.serialize(val, opts) + opts = opts or {} + local indent_str = opts.indent_str or " " +@@ -304,6 +446,9 @@ function common.serialize(val, opts) + end + + ++---Returns the last portion of a path. ++---@param path string ++---@return string + function common.basename(path) + -- a path should never end by / or \ except if it is '/' (unix root) or + -- 'X:\' (windows drive) +@@ -311,12 +456,18 @@ function common.basename(path) + end + + +--- can return nil if there is no directory part in the path ++---Returns the directory name of a path. ++---If the path doesn't have a directory, this function may return nil. ++---@param path string ++---@return string|nil + function common.dirname(path) + return path:match("(.+)[\\/][^\\/]+$") + end + + ++---Returns a path where the user's home directory is replaced by `"~"`. ++---@param text string ++---@return string + function common.home_encode(text) + if HOME and string.find(text, HOME, 1, true) == 1 then + local dir_pos = #HOME + 1 +@@ -330,6 +481,9 @@ function common.home_encode(text) + end + + ++---Returns a list of paths where the user's home directory is replaced by `"~"`. ++---@param paths string[] A list of paths to encode ++---@return string[] + function common.home_encode_list(paths) + local t = {} + for i = 1, #paths do +@@ -339,6 +493,10 @@ function common.home_encode_list(paths) + end + + ++---Expands the `"~"` prefix in a path into the user's home directory. ++---This function is not guaranteed to return an absolute path. ++---@param text string ++---@return string + function common.home_expand(text) + return HOME and text:gsub("^~", HOME) or text + end +@@ -356,12 +514,13 @@ local function split_on_slash(s, sep_pattern) + end + + +--- The filename argument given to the function is supposed to +--- come from system.absolute_path and as such should be an +--- absolute path without . or .. elements. +--- This function exists because on Windows the drive letter returned +--- by system.absolute_path is sometimes with a lower case and sometimes +--- with an upper case so we normalize to upper case. ++---Normalizes the drive letter in a Windows path to uppercase. ++---This function expects an absolute path, e.g. a path from `system.absolute_path`. ++--- ++---This function is needed because the path returned by `system.absolute_path` ++---may contain drive letters in upper or lowercase. ++---@param filename string|nil The input path. ++---@return string|nil + function common.normalize_volume(filename) + if not filename then return end + if PATHSEP == '\\' then +@@ -374,6 +533,13 @@ function common.normalize_volume(filename) + end + + ++---Normalizes a path into the same format across platforms. ++--- ++---On Windows, all drive letters are converted to uppercase. ++---UNC paths with drive letters are converted back to ordinary Windows paths. ++---All path separators (`"/"`, `"\\"`) are converted to platform-specific ones. ++---@param filename string|nil ++---@return string|nil + function common.normalize_path(filename) + if not filename then return end + local volume +@@ -414,16 +580,27 @@ function common.normalize_path(filename) + end + + ++---Checks whether a path is absolute or relative. ++---@param path string ++---@return boolean + function common.is_absolute_path(path) + return path:sub(1, 1) == PATHSEP or path:match("^(%a):\\") + end + + ++---Checks whether a path belongs to a parent directory. ++---@param filename string The path to check. ++---@param path string The parent path. ++---@return boolean + function common.path_belongs_to(filename, path) + return string.find(filename, path .. PATHSEP, 1, true) == 1 + end + + ++---Checks whether a path is relative to another path. ++---@param ref_dir string The path to check against. ++---@param dir string The input path. ++---@return boolean + function common.relative_path(ref_dir, dir) + local drive_pattern = "^(%a):\\" + local drive, ref_drive = dir:match(drive_pattern), ref_dir:match(drive_pattern) +@@ -449,6 +626,11 @@ function common.relative_path(ref_dir, dir) + end + + ++---Creates a directory recursively if necessary. ++---@param path string ++---@return boolean success ++---@return string|nil error ++---@return string|nil path The path where an error occured. + function common.mkdirp(path) + local stat = system.get_file_info(path) + if stat and stat.type then +@@ -471,6 +653,13 @@ function common.mkdirp(path) + return true + end + ++ ++---Removes a path. ++---@param path string ++---@param recursively boolean If true, the function will attempt to remove everything in the specified path. ++---@return boolean success ++---@return string|nil error ++---@return string|nil path The path where the error occured. + function common.rm(path, recursively) + local stat = system.get_file_info(path) + if not stat or (stat.type ~= "file" and stat.type ~= "dir") then diff --git a/tasks/lite-xl__lite-xl-1510/solution/solve.sh b/tasks/lite-xl__lite-xl-1510/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/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/lite-xl__lite-xl-1510/task.toml b/tasks/lite-xl__lite-xl-1510/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d581bdde7e9bbad420826f42c3a0858f91588705 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1510" +description = "Documentation for core.common" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7a218f31811812a910dfbfc229b1d5d0a8504141" +reference = "https://github.com/lite-xl/lite-xl/pull/1510" +source_access = "auto" +built_at = "2026-11-16T16:09:56.238499+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:be39105becc887a72dab9667f7097eb1f45c63e6bfd2139bd87c49d9b1edb311" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-07-22T19:39:32Z" +diff_format = "unified" +context_files = [ + "data/core/common.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 206 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.286047+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2551f05a5169294abf52291bfbc7dac624a2c1e09743e141a440c6291d885859" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1510/tests/capture.py b/tasks/lite-xl__lite-xl-1510/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/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/lite-xl__lite-xl-1510/tests/instruction.md b/tasks/lite-xl__lite-xl-1510/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c608481b7fa8a5a3ff62671efb4dd6afa2341321 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.common + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7a218f318118`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1510/tests/oracle.patch b/tasks/lite-xl__lite-xl-1510/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..95d3964a2034e8dcb877c085064dbc553fbc1bbc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/tests/oracle.patch @@ -0,0 +1,428 @@ +diff --git a/data/core/common.lua b/data/core/common.lua +index b6c9db67..272f0d5d 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -1,22 +1,41 @@ + local common = {} + + ++---Checks if the byte at offset is a UTF-8 continuation byte. ++--- ++---UTF-8 encodes code points in 1 to 4 bytes. ++---For a multi-byte sequence, each byte following the start byte is a continuation byte. ++---@param s string ++---@param offset? integer The offset of the string to start searching. Defaults to 1. ++---@return boolean + function common.is_utf8_cont(s, offset) + local byte = s:byte(offset or 1) + return byte >= 0x80 and byte < 0xc0 + end + + ++---Returns an iterator that yields a UTF-8 character on each iteration. ++---@param text string ++---@return fun(): string + function common.utf8_chars(text) + return text:gmatch("[\0-\x7f\xc2-\xf4][\x80-\xbf]*") + end + + ++---Clamps the number n between lo and hi. ++---@param n number ++---@param lo number ++---@param hi number ++---@return number + function common.clamp(n, lo, hi) + return math.max(math.min(n, hi), lo) + end + + ++---Returns a new table containing the contents of b merged into a. ++---@param a table|nil ++---@param b table? ++---@return table + function common.merge(a, b) + a = type(a) == "table" and a or {} + local t = {} +@@ -32,11 +51,19 @@ function common.merge(a, b) + end + + ++---Returns the value of a number rounded to the nearest integer. ++---@param n number ++---@return number + function common.round(n) + return n >= 0 and math.floor(n + 0.5) or math.ceil(n - 0.5) + end + + ++---Returns the first index where a subtable in tbl has prop set. ++---If none is found, nil is returned. ++---@param tbl table ++---@param prop any ++---@return number|nil + function common.find_index(tbl, prop) + for i, o in ipairs(tbl) do + if o[prop] then return i end +@@ -44,6 +71,16 @@ function common.find_index(tbl, prop) + end + + ++---Returns a value between a and b on a linear scale, based on the ++---interpolation point t. ++--- ++---If a and b are tables, a table containing the result for all the ++---elements in a and b is returned. ++---@param a number ++---@param b number ++---@param t number ++---@return number ++---@overload fun(a: table, b: table, t: number): table + function common.lerp(a, b, t) + if type(a) ~= "table" then + return a + (b - a) * t +@@ -56,11 +93,29 @@ function common.lerp(a, b, t) + end + + ++---Returns the euclidean distance between two points. ++---@param x1 number ++---@param y1 number ++---@param x2 number ++---@param y2 number ++---@return number + function common.distance(x1, y1, x2, y2) + return math.sqrt(((x2-x1) ^ 2)+((y2-y1) ^ 2)) + end + + ++---Parses a CSS color string. ++--- ++---Only these formats are supported: ++---* `rgb(r, g, b)` ++---* `rgba(r, g, b, a)` ++---* `#rrggbbaa` ++---* `#rrggbb` ++---@param str string ++---@return number r ++---@return number g ++---@return number b ++---@return number a + function common.color(str) + local r, g, b, a = str:match("^#(%x%x)(%x%x)(%x%x)(%x?%x?)$") + if r then +@@ -81,6 +136,12 @@ function common.color(str) + end + + ++---Splices a numerically indexed table. ++---This function mutates the original table. ++---@param t any[] ++---@param at number Index at which to start splicing. ++---@param remove number Number of elements to remove. ++---@param insert? any[] A table containing elements to insert after splicing. + function common.splice(t, at, remove, insert) + assert(remove >= 0, "bad argument #3 to 'splice' (non-negative value expected)") + insert = insert or {} +@@ -110,6 +171,16 @@ local function fuzzy_match_items(items, needle, files) + end + + ++---Performs fuzzy matching. ++--- ++---If the haystack is a string, a score ranging from 0 to 1 is returned.
++---If the haystack is a table, a table containing the haystack sorted in ascending ++---order of similarity is returned. ++---@param haystack string ++---@param needle string ++---@param files boolean If true, the matching process will be performed in reverse to better match paths. ++---@return number ++---@overload fun(haystack: string[], needle: string, files: boolean): string[] + function common.fuzzy_match(haystack, needle, files) + if type(haystack) == "table" then + return fuzzy_match_items(haystack, needle, files) +@@ -118,6 +189,14 @@ function common.fuzzy_match(haystack, needle, files) + end + + ++---Performs fuzzy matching and returns recently used strings if needed. ++--- ++---If the needle is empty, then a list of recently used strings ++---are added to the result, followed by strings from the haystack. ++---@param haystack string[] ++---@param recents string[] ++---@param needle string ++---@return string[] + function common.fuzzy_match_with_recents(haystack, recents, needle) + if needle == "" then + local recents_ext = {} +@@ -136,6 +215,13 @@ function common.fuzzy_match_with_recents(haystack, recents, needle) + end + + ++---Returns a list of paths that are relative to the input path. ++--- ++---If a root directory is specified, the function returns paths ++---that are relative to the root directory. ++---@param text string The input path. ++---@param root? string The root directory. ++---@return string[] + function common.path_suggest(text, root) + if root and root:sub(-1) ~= PATHSEP then + root = root .. PATHSEP +@@ -189,6 +275,9 @@ function common.path_suggest(text, root) + end + + ++---Returns a list of directories that are related to a path. ++---@param text string The input path. ++---@return string[] + function common.dir_path_suggest(text) + local path, name = text:match("^(.-)([^/\\]*)$") + local files = system.list_dir(path == "" and "." or path) or {} +@@ -204,6 +293,10 @@ function common.dir_path_suggest(text) + end + + ++---Filters a list of paths to find those that are related to the input path. ++---@param text string The input path. ++---@param dir_list string[] A list of paths to filter. ++---@return string[] + function common.dir_list_suggest(text, dir_list) + local path, name = text:match("^(.-)([^/\\]*)$") + local res = {} +@@ -216,6 +309,15 @@ function common.dir_list_suggest(text, dir_list) + end + + ++---Matches a string against a list of patterns. ++--- ++---If a match was found, its start and end index is returned. ++---Otherwise, false is returned. ++---@param text string ++---@param pattern string|string[] ++---@param ... any Other options for string.find(). ++---@return number|boolean start_index ++---@return number|nil end_index + function common.match_pattern(text, pattern, ...) + if type(pattern) == "string" then + return text:find(pattern, ...) +@@ -228,8 +330,24 @@ function common.match_pattern(text, pattern, ...) + end + + ++---Draws text onto the window. ++---The function returns the X and Y coordinates of the bottom-right ++---corner of the text. ++---@param font renderer.font ++---@param color renderer.color ++---@param text string ++---@param align string ++---| '"left"' # Align text to the left of the bounding box ++---| '"right"' # Align text to the right of the bounding box ++---| '"center"' # Center text in the bounding box ++---@param x number ++---@param y number ++---@param w number ++---@param h number ++---@return number x_advance ++---@return number y_advance + function common.draw_text(font, color, text, align, x,y,w,h) +- local tw, th = font:get_width(text), font:get_height(text) ++ local tw, th = font:get_width(text), font:get_height() + if align == "center" then + x = x + (w - tw) / 2 + elseif align == "right" then +@@ -240,6 +358,16 @@ function common.draw_text(font, color, text, align, x,y,w,h) + end + + ++---Prints the execution time of a function. ++--- ++---The execution time and percentage of frame time ++---for the function is printed to standard output.
++---The frame rate is always assumed to be 60 FPS, thus ++---a value of 100% would mean that the benchmark took ++---1/60 of a second to execute. ++---@param name string ++---@param fn fun(...: any): any ++---@return any # The result returned by the function + function common.bench(name, fn, ...) + local start = system.get_time() + local res = fn(...) +@@ -285,14 +413,28 @@ local function serialize(val, pretty, indent_str, escape, sort, limit, level) + return tostring(val) + end + +--- Serialize `val` into a parsable string. +--- Available options +--- * pretty: enable pretty printing +--- * indent_str: indent to use (" " by default) +--- * escape: use normal escape characters instead of the ones used by string.format("%q", ...) +--- * sort: sort the keys inside tables +--- * limit: limit how deep to serialize +--- * initial_indent: the initial indentation level ++ ++---@class common.serializeoptions ++---@field pretty boolean Enables pretty printing. ++---@field indent_str string The indentation character to use. Defaults to `" "`. ++---@field escape boolean Uses normal escape characters ("\n") instead of decimal escape sequences ("\10"). ++---@field limit number Limits the depth when serializing nested tables. Defaults to `math.huge`. ++---@field sort boolean Sorts the output if it is a sortable table. ++---@field initial_indent number The initial indentation level. Defaults to 0. ++ ++---Serializes a value into a Lua string that is loadable with load(). ++--- ++---Only these basic types are supported: ++---* nil ++---* boolean ++---* number (except very large numbers and special constants, e.g. `math.huge`, `inf` and `nan`) ++---* integer ++---* string ++---* table ++--- ++---@param val any ++---@param opts? common.serializeoptions ++---@return string + function common.serialize(val, opts) + opts = opts or {} + local indent_str = opts.indent_str or " " +@@ -304,6 +446,9 @@ function common.serialize(val, opts) + end + + ++---Returns the last portion of a path. ++---@param path string ++---@return string + function common.basename(path) + -- a path should never end by / or \ except if it is '/' (unix root) or + -- 'X:\' (windows drive) +@@ -311,12 +456,18 @@ function common.basename(path) + end + + +--- can return nil if there is no directory part in the path ++---Returns the directory name of a path. ++---If the path doesn't have a directory, this function may return nil. ++---@param path string ++---@return string|nil + function common.dirname(path) + return path:match("(.+)[\\/][^\\/]+$") + end + + ++---Returns a path where the user's home directory is replaced by `"~"`. ++---@param text string ++---@return string + function common.home_encode(text) + if HOME and string.find(text, HOME, 1, true) == 1 then + local dir_pos = #HOME + 1 +@@ -330,6 +481,9 @@ function common.home_encode(text) + end + + ++---Returns a list of paths where the user's home directory is replaced by `"~"`. ++---@param paths string[] A list of paths to encode ++---@return string[] + function common.home_encode_list(paths) + local t = {} + for i = 1, #paths do +@@ -339,6 +493,10 @@ function common.home_encode_list(paths) + end + + ++---Expands the `"~"` prefix in a path into the user's home directory. ++---This function is not guaranteed to return an absolute path. ++---@param text string ++---@return string + function common.home_expand(text) + return HOME and text:gsub("^~", HOME) or text + end +@@ -356,12 +514,13 @@ local function split_on_slash(s, sep_pattern) + end + + +--- The filename argument given to the function is supposed to +--- come from system.absolute_path and as such should be an +--- absolute path without . or .. elements. +--- This function exists because on Windows the drive letter returned +--- by system.absolute_path is sometimes with a lower case and sometimes +--- with an upper case so we normalize to upper case. ++---Normalizes the drive letter in a Windows path to uppercase. ++---This function expects an absolute path, e.g. a path from `system.absolute_path`. ++--- ++---This function is needed because the path returned by `system.absolute_path` ++---may contain drive letters in upper or lowercase. ++---@param filename string|nil The input path. ++---@return string|nil + function common.normalize_volume(filename) + if not filename then return end + if PATHSEP == '\\' then +@@ -374,6 +533,13 @@ function common.normalize_volume(filename) + end + + ++---Normalizes a path into the same format across platforms. ++--- ++---On Windows, all drive letters are converted to uppercase. ++---UNC paths with drive letters are converted back to ordinary Windows paths. ++---All path separators (`"/"`, `"\\"`) are converted to platform-specific ones. ++---@param filename string|nil ++---@return string|nil + function common.normalize_path(filename) + if not filename then return end + local volume +@@ -414,16 +580,27 @@ function common.normalize_path(filename) + end + + ++---Checks whether a path is absolute or relative. ++---@param path string ++---@return boolean + function common.is_absolute_path(path) + return path:sub(1, 1) == PATHSEP or path:match("^(%a):\\") + end + + ++---Checks whether a path belongs to a parent directory. ++---@param filename string The path to check. ++---@param path string The parent path. ++---@return boolean + function common.path_belongs_to(filename, path) + return string.find(filename, path .. PATHSEP, 1, true) == 1 + end + + ++---Checks whether a path is relative to another path. ++---@param ref_dir string The path to check against. ++---@param dir string The input path. ++---@return boolean + function common.relative_path(ref_dir, dir) + local drive_pattern = "^(%a):\\" + local drive, ref_drive = dir:match(drive_pattern), ref_dir:match(drive_pattern) +@@ -449,6 +626,11 @@ function common.relative_path(ref_dir, dir) + end + + ++---Creates a directory recursively if necessary. ++---@param path string ++---@return boolean success ++---@return string|nil error ++---@return string|nil path The path where an error occured. + function common.mkdirp(path) + local stat = system.get_file_info(path) + if stat and stat.type then +@@ -471,6 +653,13 @@ function common.mkdirp(path) + return true + end + ++ ++---Removes a path. ++---@param path string ++---@param recursively boolean If true, the function will attempt to remove everything in the specified path. ++---@return boolean success ++---@return string|nil error ++---@return string|nil path The path where the error occured. + function common.rm(path, recursively) + local stat = system.get_file_info(path) + if not stat or (stat.type ~= "file" and stat.type ~= "dir") then diff --git a/tasks/lite-xl__lite-xl-1510/tests/test.sh b/tasks/lite-xl__lite-xl-1510/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff059469d5e88775eaf22d56edd07771b9499c6b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/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 7a218f31811812a910dfbfc229b1d5d0a8504141 > "$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/lite-xl__lite-xl-1510/tests/verifier.py b/tasks/lite-xl__lite-xl-1510/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1510/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/lite-xl__lite-xl-1547/environment/Dockerfile b/tasks/lite-xl__lite-xl-1547/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1547/instruction.md b/tasks/lite-xl__lite-xl-1547/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5582ea510eb4c3cab7379f1929b002c456835fa3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Backporting ancient fix to allow for large amounts of reading. + +## Description + +Allows for read to read more than LUAL_BUFFERSIZE. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1547/solution/patch.diff b/tasks/lite-xl__lite-xl-1547/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ed56b1bcb5d6a7996e707d2da39020873364bf9e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/src/api/process.c b/src/api/process.c +index d7bfeb72..4f0935de 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -605,7 +605,7 @@ static int process_start(lua_State* L) { + return retval; + } + +-static int g_read(lua_State* L, int stream, unsigned long read_size) { ++static int g_read(lua_State* L, int stream, lua_Integer read_size) { + process_t* self = (process_t*) luaL_checkudata(L, 1, API_TYPE_PROCESS); + long length = 0; + if (stream != STDOUT_FD && stream != STDERR_FD) +@@ -633,17 +633,22 @@ static int g_read(lua_State* L, int stream, unsigned long read_size) { + #else + luaL_Buffer b; + luaL_buffinit(L, &b); +- uint8_t* buffer = (uint8_t*)luaL_prepbuffsize(&b, READ_BUF_SIZE); +- length = read(self->child_pipes[stream][0], buffer, read_size > READ_BUF_SIZE ? READ_BUF_SIZE : read_size); +- if (length == 0 && !poll_process(self, WAIT_NONE)) +- return 0; +- else if (length < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) +- length = 0; +- if (length < 0) { +- signal_process(self, SIGNAL_TERM); +- return 0; +- } +- luaL_addsize(&b, length); ++ do { ++ uint8_t* buffer = (uint8_t*)luaL_prepbuffer(&b); ++ length = read(self->child_pipes[stream][0], buffer, read_size < LUAL_BUFFERSIZE ? read_size : LUAL_BUFFERSIZE); ++ if (length == 0 && !poll_process(self, WAIT_NONE)) ++ break; ++ else if (length < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) ++ length = 0; ++ if (length < 0) { ++ signal_process(self, SIGNAL_TERM); ++ return 0; ++ } ++ if (length) { ++ luaL_addsize(&b, length); ++ read_size -= length; ++ } ++ } while (read_size > 0 && length > 0); + luaL_pushresult(&b); + #endif + return 1; diff --git a/tasks/lite-xl__lite-xl-1547/solution/solve.sh b/tasks/lite-xl__lite-xl-1547/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/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/lite-xl__lite-xl-1547/task.toml b/tasks/lite-xl__lite-xl-1547/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9f8ab2feca3cf2da5a37fe00505470b9898534c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1547" +description = "Backporting ancient fix to allow for large amounts of reading." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1547" +source_access = "auto" +built_at = "2026-11-16T16:09:56.163135+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7b08089a0921f325a7a1dcc4c159cd19368a7ba378f38df8b617d63a591895e3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-09-13T14:36:36Z" +diff_format = "unified" +context_files = [ + "src/api/process.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.286476+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1547/tests/capture.py b/tasks/lite-xl__lite-xl-1547/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/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/lite-xl__lite-xl-1547/tests/instruction.md b/tasks/lite-xl__lite-xl-1547/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5582ea510eb4c3cab7379f1929b002c456835fa3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Backporting ancient fix to allow for large amounts of reading. + +## Description + +Allows for read to read more than LUAL_BUFFERSIZE. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1547/tests/oracle.patch b/tasks/lite-xl__lite-xl-1547/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ed56b1bcb5d6a7996e707d2da39020873364bf9e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/src/api/process.c b/src/api/process.c +index d7bfeb72..4f0935de 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -605,7 +605,7 @@ static int process_start(lua_State* L) { + return retval; + } + +-static int g_read(lua_State* L, int stream, unsigned long read_size) { ++static int g_read(lua_State* L, int stream, lua_Integer read_size) { + process_t* self = (process_t*) luaL_checkudata(L, 1, API_TYPE_PROCESS); + long length = 0; + if (stream != STDOUT_FD && stream != STDERR_FD) +@@ -633,17 +633,22 @@ static int g_read(lua_State* L, int stream, unsigned long read_size) { + #else + luaL_Buffer b; + luaL_buffinit(L, &b); +- uint8_t* buffer = (uint8_t*)luaL_prepbuffsize(&b, READ_BUF_SIZE); +- length = read(self->child_pipes[stream][0], buffer, read_size > READ_BUF_SIZE ? READ_BUF_SIZE : read_size); +- if (length == 0 && !poll_process(self, WAIT_NONE)) +- return 0; +- else if (length < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) +- length = 0; +- if (length < 0) { +- signal_process(self, SIGNAL_TERM); +- return 0; +- } +- luaL_addsize(&b, length); ++ do { ++ uint8_t* buffer = (uint8_t*)luaL_prepbuffer(&b); ++ length = read(self->child_pipes[stream][0], buffer, read_size < LUAL_BUFFERSIZE ? read_size : LUAL_BUFFERSIZE); ++ if (length == 0 && !poll_process(self, WAIT_NONE)) ++ break; ++ else if (length < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) ++ length = 0; ++ if (length < 0) { ++ signal_process(self, SIGNAL_TERM); ++ return 0; ++ } ++ if (length) { ++ luaL_addsize(&b, length); ++ read_size -= length; ++ } ++ } while (read_size > 0 && length > 0); + luaL_pushresult(&b); + #endif + return 1; diff --git a/tasks/lite-xl__lite-xl-1547/tests/test.sh b/tasks/lite-xl__lite-xl-1547/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1547/tests/verifier.py b/tasks/lite-xl__lite-xl-1547/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1547/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/lite-xl__lite-xl-1554/environment/Dockerfile b/tasks/lite-xl__lite-xl-1554/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..061581499b296a8feed6c7304daad25e2f17a785 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f52f01742485d39e9847654e016e2dabe60a4711 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f52f01742485d39e9847654e016e2dabe60a4711 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f52f01742485d39e9847654e016e2dabe60a4711 \ + && 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/lite-xl__lite-xl-1554/instruction.md b/tasks/lite-xl__lite-xl-1554/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2b8b2d5067e3a0486fc4a20fbabbf92e103aa83 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** style(src/renderer): use FreeType header names + +## Description + +Simple PR, doesn't really break anything, and follows FreeType conventions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f52f01742485`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1554/solution/patch.diff b/tasks/lite-xl__lite-xl-1554/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1ddc1f382f5103ff9c272fdcad1dda73d9add59f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/src/renderer.c b/src/renderer.c +index f8ae6302..6d95beeb 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -4,9 +4,9 @@ + #include + #include + #include +-#include +-#include + #include FT_FREETYPE_H ++#include FT_LCD_FILTER_H ++#include FT_OUTLINE_H + + #ifdef _WIN32 + #include diff --git a/tasks/lite-xl__lite-xl-1554/solution/solve.sh b/tasks/lite-xl__lite-xl-1554/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/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/lite-xl__lite-xl-1554/task.toml b/tasks/lite-xl__lite-xl-1554/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9dfd2ff5286dfda61ef2a870f90759a1db817ae2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1554" +description = "style(src/renderer): use FreeType header names" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f52f01742485d39e9847654e016e2dabe60a4711" +reference = "https://github.com/lite-xl/lite-xl/pull/1554" +source_access = "auto" +built_at = "2026-11-16T16:09:56.237189+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5a665353122a74e4d6ea75a8c4fcc6e973d44d319a9c8b43ee3c2dd5571cce93" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-07-09T00:42:40Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.286910+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:cb08e4479d65d004b1ed451962fb07f541c5123b667a6e1078400375dbf5b4ce" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1554/tests/capture.py b/tasks/lite-xl__lite-xl-1554/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/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/lite-xl__lite-xl-1554/tests/instruction.md b/tasks/lite-xl__lite-xl-1554/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2b8b2d5067e3a0486fc4a20fbabbf92e103aa83 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** style(src/renderer): use FreeType header names + +## Description + +Simple PR, doesn't really break anything, and follows FreeType conventions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f52f01742485`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1554/tests/oracle.patch b/tasks/lite-xl__lite-xl-1554/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1ddc1f382f5103ff9c272fdcad1dda73d9add59f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/src/renderer.c b/src/renderer.c +index f8ae6302..6d95beeb 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -4,9 +4,9 @@ + #include + #include + #include +-#include +-#include + #include FT_FREETYPE_H ++#include FT_LCD_FILTER_H ++#include FT_OUTLINE_H + + #ifdef _WIN32 + #include diff --git a/tasks/lite-xl__lite-xl-1554/tests/test.sh b/tasks/lite-xl__lite-xl-1554/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..339ea3f49b6be2af4516420d956619c3436f9436 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/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 f52f01742485d39e9847654e016e2dabe60a4711 > "$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/lite-xl__lite-xl-1554/tests/verifier.py b/tasks/lite-xl__lite-xl-1554/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1554/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/lite-xl__lite-xl-1555/environment/Dockerfile b/tasks/lite-xl__lite-xl-1555/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e6898da612e099da12d19f1c57cf48dd86964f47 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 96d6d9acacda9f27b432d31c666d9783ae284b21 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 96d6d9acacda9f27b432d31c666d9783ae284b21 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 96d6d9acacda9f27b432d31c666d9783ae284b21 \ + && 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/lite-xl__lite-xl-1555/instruction.md b/tasks/lite-xl__lite-xl-1555/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..437ba5a99ca85554be649cf0294006a23cea22cc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** feat(src/renderer): stream fonts with SDL_RWops on all platforms + +## Description + +This PR loads the font file with SDL_RWops on all platforms. This will support UTF-8 filename on Windows without loading the entire file into memory, which partially causes #1529. The other part of the issue is with too much glyphsets loaded at once (and slow load), but this will reduce the memory used. + +Partially . + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96d6d9acacda`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1555/solution/patch.diff b/tasks/lite-xl__lite-xl-1555/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e1b990d4c544bdf51756b4592fe5d7863728e057 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/solution/patch.diff @@ -0,0 +1,177 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 6d95beeb..d08565ea 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -7,6 +7,7 @@ + #include FT_FREETYPE_H + #include FT_LCD_FILTER_H + #include FT_OUTLINE_H ++#include FT_SYSTEM_H + + #ifdef _WIN32 + #include +@@ -50,6 +51,7 @@ typedef struct { + + typedef struct RenFont { + FT_Face face; ++ FT_StreamRec stream; + GlyphSet* sets[SUBPIXEL_BITMAPS_CACHED][MAX_LOADABLE_GLYPHSETS]; + float size, space_advance, tab_advance; + unsigned short max_height, baseline, height; +@@ -57,10 +59,6 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; +-#ifdef _WIN32 +- unsigned char *file; +- HANDLE file_handle; +-#endif + char path[]; + } RenFont; + +@@ -215,54 +213,49 @@ static void font_clear_glyph_cache(RenFont* font) { + } + } + +-RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { +- FT_Face face = NULL; +- +-#ifdef _WIN32 +- +- HANDLE file = INVALID_HANDLE_VALUE; +- DWORD read; +- int font_file_len = 0; +- unsigned char *font_file = NULL; +- wchar_t *wpath = NULL; +- +- if ((wpath = utfconv_utf8towc(path)) == NULL) +- return NULL; +- +- if ((file = CreateFileW(wpath, +- GENERIC_READ, +- FILE_SHARE_READ, // or else we can't copy fonts +- NULL, +- OPEN_EXISTING, +- FILE_ATTRIBUTE_NORMAL, +- NULL)) == INVALID_HANDLE_VALUE) +- goto failure; +- +- if ((font_file_len = GetFileSize(file, NULL)) == INVALID_FILE_SIZE) +- goto failure; ++// based on https://github.com/libsdl-org/SDL_ttf/blob/2a094959055fba09f7deed6e1ffeb986188982ae/SDL_ttf.c#L1735 ++static unsigned long font_file_read(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) { ++ uint64_t amount; ++ SDL_RWops *file = (SDL_RWops *) stream->descriptor.pointer; ++ SDL_RWseek(file, (int) offset, RW_SEEK_SET); ++ if (count == 0) ++ return 0; ++ amount = SDL_RWread(file, buffer, sizeof(char), count); ++ if (amount <= 0) ++ return 0; ++ return (unsigned long) amount; ++} + +- font_file = check_alloc(malloc(font_file_len * sizeof(unsigned char))); +- if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) +- goto failure; ++static void font_file_close(FT_Stream stream) { ++ if (stream && stream->descriptor.pointer) { ++ SDL_RWclose((SDL_RWops *) stream->descriptor.pointer); ++ stream->descriptor.pointer = NULL; ++ } ++} + +- free(wpath); +- wpath = NULL; ++RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { ++ RenFont *font = NULL; ++ FT_Face face = NULL; ++ ++ SDL_RWops *file = SDL_RWFromFile(path, "rb"); ++ if (!file) ++ goto rwops_failure; + +- if (FT_New_Memory_Face(library, font_file, read, 0, &face)) ++ int len = strlen(path); ++ font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); ++ font->stream.read = font_file_read; ++ font->stream.close = font_file_close; ++ font->stream.descriptor.pointer = file; ++ font->stream.pos = 0; ++ font->stream.size = (unsigned long) SDL_RWsize(file); ++ ++ if (FT_Open_Face(library, &(FT_Open_Args){ .flags = FT_OPEN_STREAM, .stream = &font->stream }, 0, &face)) + goto failure; + +-#else +- +- if (FT_New_Face(library, path, 0, &face)) +- return NULL; +- +-#endif +- + const int surface_scale = renwin_get_surface(window_renderer).scale; + if (FT_Set_Pixel_Sizes(face, 0, (int)(size*surface_scale))) + goto failure; +- int len = strlen(path); +- RenFont* font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); ++ + strcpy(font->path, path); + font->face = face; + font->size = size; +@@ -272,32 +265,28 @@ RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, + font->hinting = hinting; + font->style = style; + +-#ifdef _WIN32 +- // we need to keep this for freetype +- font->file = font_file; +- font->file_handle = file; +-#endif +- + if(FT_IS_SCALABLE(face)) + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); +- if(!font->underline_thickness) font->underline_thickness = ceil((double) font->height / 14.0); ++ if(!font->underline_thickness) ++ font->underline_thickness = ceil((double) font->height / 14.0); + +- if (FT_Load_Char(face, ' ', font_set_load_options(font))) { +- free(font); ++ if (FT_Load_Char(face, ' ', font_set_load_options(font))) + goto failure; +- } ++ + font->space_advance = face->glyph->advance.x / 64.0f; + font->tab_advance = font->space_advance * 2; + return font; + + failure: +-#ifdef _WIN32 +- free(wpath); +- free(font_file); +- if (file != INVALID_HANDLE_VALUE) CloseHandle(file); +-#endif +- if (face != NULL) ++ if (face) + FT_Done_Face(face); ++ if (font) ++ free(font); ++ return NULL; ++ ++rwops_failure: ++ if (file) ++ SDL_RWclose(file); + return NULL; + } + +@@ -316,10 +305,6 @@ const char* ren_font_get_path(RenFont *font) { + void ren_font_free(RenFont* font) { + font_clear_glyph_cache(font); + FT_Done_Face(font->face); +-#ifdef _WIN32 +- free(font->file); +- CloseHandle(font->file_handle); +-#endif + free(font); + } + diff --git a/tasks/lite-xl__lite-xl-1555/solution/solve.sh b/tasks/lite-xl__lite-xl-1555/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/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/lite-xl__lite-xl-1555/task.toml b/tasks/lite-xl__lite-xl-1555/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f527b6b71b56059b8f444461abe9c09f4ce00cb8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1555" +description = "feat(src/renderer): stream fonts with SDL_RWops on all platforms" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "96d6d9acacda9f27b432d31c666d9783ae284b21" +reference = "https://github.com/lite-xl/lite-xl/pull/1555" +source_access = "auto" +built_at = "2026-11-16T16:09:56.235838+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a0c8f5d8fa13c84173fe0d50be580e4e27c70a1ba54c8086de332c0528759096" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-07-11T01:45:36Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 113 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.287351+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:acb5a822099ba3a2145106579112317b90abd1e79410605479f9d03ea58af43a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1555/tests/capture.py b/tasks/lite-xl__lite-xl-1555/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/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/lite-xl__lite-xl-1555/tests/instruction.md b/tasks/lite-xl__lite-xl-1555/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..437ba5a99ca85554be649cf0294006a23cea22cc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** feat(src/renderer): stream fonts with SDL_RWops on all platforms + +## Description + +This PR loads the font file with SDL_RWops on all platforms. This will support UTF-8 filename on Windows without loading the entire file into memory, which partially causes #1529. The other part of the issue is with too much glyphsets loaded at once (and slow load), but this will reduce the memory used. + +Partially . + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96d6d9acacda`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1555/tests/oracle.patch b/tasks/lite-xl__lite-xl-1555/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e1b990d4c544bdf51756b4592fe5d7863728e057 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/tests/oracle.patch @@ -0,0 +1,177 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 6d95beeb..d08565ea 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -7,6 +7,7 @@ + #include FT_FREETYPE_H + #include FT_LCD_FILTER_H + #include FT_OUTLINE_H ++#include FT_SYSTEM_H + + #ifdef _WIN32 + #include +@@ -50,6 +51,7 @@ typedef struct { + + typedef struct RenFont { + FT_Face face; ++ FT_StreamRec stream; + GlyphSet* sets[SUBPIXEL_BITMAPS_CACHED][MAX_LOADABLE_GLYPHSETS]; + float size, space_advance, tab_advance; + unsigned short max_height, baseline, height; +@@ -57,10 +59,6 @@ typedef struct RenFont { + ERenFontHinting hinting; + unsigned char style; + unsigned short underline_thickness; +-#ifdef _WIN32 +- unsigned char *file; +- HANDLE file_handle; +-#endif + char path[]; + } RenFont; + +@@ -215,54 +213,49 @@ static void font_clear_glyph_cache(RenFont* font) { + } + } + +-RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { +- FT_Face face = NULL; +- +-#ifdef _WIN32 +- +- HANDLE file = INVALID_HANDLE_VALUE; +- DWORD read; +- int font_file_len = 0; +- unsigned char *font_file = NULL; +- wchar_t *wpath = NULL; +- +- if ((wpath = utfconv_utf8towc(path)) == NULL) +- return NULL; +- +- if ((file = CreateFileW(wpath, +- GENERIC_READ, +- FILE_SHARE_READ, // or else we can't copy fonts +- NULL, +- OPEN_EXISTING, +- FILE_ATTRIBUTE_NORMAL, +- NULL)) == INVALID_HANDLE_VALUE) +- goto failure; +- +- if ((font_file_len = GetFileSize(file, NULL)) == INVALID_FILE_SIZE) +- goto failure; ++// based on https://github.com/libsdl-org/SDL_ttf/blob/2a094959055fba09f7deed6e1ffeb986188982ae/SDL_ttf.c#L1735 ++static unsigned long font_file_read(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) { ++ uint64_t amount; ++ SDL_RWops *file = (SDL_RWops *) stream->descriptor.pointer; ++ SDL_RWseek(file, (int) offset, RW_SEEK_SET); ++ if (count == 0) ++ return 0; ++ amount = SDL_RWread(file, buffer, sizeof(char), count); ++ if (amount <= 0) ++ return 0; ++ return (unsigned long) amount; ++} + +- font_file = check_alloc(malloc(font_file_len * sizeof(unsigned char))); +- if (!ReadFile(file, font_file, font_file_len, &read, NULL) || read != font_file_len) +- goto failure; ++static void font_file_close(FT_Stream stream) { ++ if (stream && stream->descriptor.pointer) { ++ SDL_RWclose((SDL_RWops *) stream->descriptor.pointer); ++ stream->descriptor.pointer = NULL; ++ } ++} + +- free(wpath); +- wpath = NULL; ++RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { ++ RenFont *font = NULL; ++ FT_Face face = NULL; ++ ++ SDL_RWops *file = SDL_RWFromFile(path, "rb"); ++ if (!file) ++ goto rwops_failure; + +- if (FT_New_Memory_Face(library, font_file, read, 0, &face)) ++ int len = strlen(path); ++ font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); ++ font->stream.read = font_file_read; ++ font->stream.close = font_file_close; ++ font->stream.descriptor.pointer = file; ++ font->stream.pos = 0; ++ font->stream.size = (unsigned long) SDL_RWsize(file); ++ ++ if (FT_Open_Face(library, &(FT_Open_Args){ .flags = FT_OPEN_STREAM, .stream = &font->stream }, 0, &face)) + goto failure; + +-#else +- +- if (FT_New_Face(library, path, 0, &face)) +- return NULL; +- +-#endif +- + const int surface_scale = renwin_get_surface(window_renderer).scale; + if (FT_Set_Pixel_Sizes(face, 0, (int)(size*surface_scale))) + goto failure; +- int len = strlen(path); +- RenFont* font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); ++ + strcpy(font->path, path); + font->face = face; + font->size = size; +@@ -272,32 +265,28 @@ RenFont* ren_font_load(RenWindow *window_renderer, const char* path, float size, + font->hinting = hinting; + font->style = style; + +-#ifdef _WIN32 +- // we need to keep this for freetype +- font->file = font_file; +- font->file_handle = file; +-#endif +- + if(FT_IS_SCALABLE(face)) + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); +- if(!font->underline_thickness) font->underline_thickness = ceil((double) font->height / 14.0); ++ if(!font->underline_thickness) ++ font->underline_thickness = ceil((double) font->height / 14.0); + +- if (FT_Load_Char(face, ' ', font_set_load_options(font))) { +- free(font); ++ if (FT_Load_Char(face, ' ', font_set_load_options(font))) + goto failure; +- } ++ + font->space_advance = face->glyph->advance.x / 64.0f; + font->tab_advance = font->space_advance * 2; + return font; + + failure: +-#ifdef _WIN32 +- free(wpath); +- free(font_file); +- if (file != INVALID_HANDLE_VALUE) CloseHandle(file); +-#endif +- if (face != NULL) ++ if (face) + FT_Done_Face(face); ++ if (font) ++ free(font); ++ return NULL; ++ ++rwops_failure: ++ if (file) ++ SDL_RWclose(file); + return NULL; + } + +@@ -316,10 +305,6 @@ const char* ren_font_get_path(RenFont *font) { + void ren_font_free(RenFont* font) { + font_clear_glyph_cache(font); + FT_Done_Face(font->face); +-#ifdef _WIN32 +- free(font->file); +- CloseHandle(font->file_handle); +-#endif + free(font); + } + diff --git a/tasks/lite-xl__lite-xl-1555/tests/test.sh b/tasks/lite-xl__lite-xl-1555/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a602d262b4cbeae8f30bc69771822d715178db5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/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 96d6d9acacda9f27b432d31c666d9783ae284b21 > "$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/lite-xl__lite-xl-1555/tests/verifier.py b/tasks/lite-xl__lite-xl-1555/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1555/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/lite-xl__lite-xl-1564/environment/Dockerfile b/tasks/lite-xl__lite-xl-1564/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c08e1b5c8f679bac8db233efe182747677df127a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7b330ae81b942f91a45c9cfa45f44454da867303 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7b330ae81b942f91a45c9cfa45f44454da867303 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7b330ae81b942f91a45c9cfa45f44454da867303 \ + && 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/lite-xl__lite-xl-1564/instruction.md b/tasks/lite-xl__lite-xl-1564/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f593fc036b9d4082de8aed6a5a974d56e6452e7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.command + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b330ae81b94`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1564/solution/patch.diff b/tasks/lite-xl__lite-xl-1564/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eda6e800b0a56bfb9172b755781f9392d15aba04 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/solution/patch.diff @@ -0,0 +1,156 @@ +diff --git a/data/core/command.lua b/data/core/command.lua +index faf872e2..2b28f63b 100644 +--- a/data/core/command.lua ++++ b/data/core/command.lua +@@ -1,25 +1,55 @@ + local core = require "core" + local command = {} + ++---A predicate function accepts arguments from `command.perform()` and evaluates to a boolean.
++---If the function returns true, then the function associated with the command is executed. ++--- ++---The predicate function can also return other values after the boolean, which will ++---be passed into the function associated with the command. ++---@alias core.command.predicate_function fun(...: any): boolean, ... ++ ++---A predicate is a string, an Object or a function, that is used to determine ++---whether a command should be executed. ++--- ++---If the predicate is a string, it is resolved into an `Object` via `require()` ++---and checked against the active view with `Object:extends()`.
++---For example, `"core.docview"` will match any view that inherits from `DocView`.
++---A `!` can be appended to the predicate to strictly match the current view via `Object:is()`, ++---instead of matching any view that inherits the predicate. ++--- ++---If the predicate is a table, it is checked against the active view with `Object:extends()`. ++---Strict matching via `Object:is()` is not available. ++--- ++---If the predicate is a function, it must behave like a predicate function. ++---@see core.command.predicate_function ++---@alias core.command.predicate string|core.object|core.command.predicate_function ++ ++---A command is identified by a command name. ++---The command name contains a category and the name itself, separated by a colon (':'). ++--- ++---All commands should be in lowercase and should not contain whitespaces; instead ++---they should be replaced by a dash ('-'). ++---@alias core.command.command_name string ++ ++---The predicate and its associated function. ++---@class core.command.command ++---@field predicate core.command.predicate_function ++---@field perform fun(...: any) ++ ++---@type { [string]: core.command.command } + command.map = {} + ++---@type core.command.predicate_function + local always_true = function() return true end + + +----Used iternally by command.add, statusview, and contextmenu to generate a +----function with a condition to evaluate returning the boolean result of this +----evaluation. ++---This function takes in a predicate and produces a predicate function ++---that is internally used to dispatch and execute commands. + --- +----If a string predicate is given it is treated as a require import that should +----return a valid object which is checked against the current active view, +----eg: "core.docview" will match any view that inherits from DocView. Appending +----a `!` at the end of the string means we want to match the given object +----from the import strcitly eg: "core.docview!" only DocView is matched. +----A function that returns a boolean can be used instead to perform a custom +----evaluation, setting to nil means always evaluates to true. +---- +----@param predicate string | table | function +----@return function ++---This function should not be called manually. ++---@see core.command.predicate ++---@param predicate core.command.predicate|nil If nil, the predicate always evaluates to true. ++---@return core.command.predicate_function + function command.generate_predicate(predicate) + predicate = predicate or always_true + local strict = false +@@ -38,10 +68,20 @@ function command.generate_predicate(predicate) + predicate = function(...) return core.active_view:is(class), core.active_view, ... end + end + end ++ ---@cast predicate core.command.predicate_function + return predicate + end + + ++---Adds commands to the map. ++--- ++---The function accepts a table containing a list of commands ++---and their functions.
++---If a command already exists, it will be replaced. ++---@see core.command.predicate ++---@see core.command.command_name ++---@param predicate core.command.predicate ++---@param map { [core.command.command_name]: fun(...: any) } + function command.add(predicate, map) + predicate = command.generate_predicate(predicate) + for name, fn in pairs(map) do +@@ -57,11 +97,21 @@ local function capitalize_first(str) + return str:sub(1, 1):upper() .. str:sub(2) + end + ++---Prettifies the command name. ++--- ++---This function adds a space between the colon and the command name, ++---replaces dashes with spaces and capitalizes the command appropriately. ++---@see core.command.command_name ++---@param name core.command.command_name ++---@return string + function command.prettify_name(name) ++ ---@diagnostic disable-next-line: redundant-return-value + return name:gsub(":", ": "):gsub("-", " "):gsub("%S+", capitalize_first) + end + + ++---Returns all the commands that can be executed (their predicates evaluate to true). ++---@return core.command.command_name[] + function command.get_all_valid() + local res = {} + local memoized_predicates = {} +@@ -76,6 +126,10 @@ function command.get_all_valid() + return res + end + ++---Checks whether a command can be executed (its predicate evaluates to true). ++---@param name core.command.command_name ++---@param ... any ++---@return boolean + function command.is_valid(name, ...) + return command.map[name] and command.map[name].predicate(...) + end +@@ -98,12 +152,26 @@ local function perform(name, ...) + end + + +-function command.perform(...) +- local ok, res = core.try(perform, ...) ++---Performs a command. ++--- ++---The arguments passed into this function are forwarded to the predicate function.
++---If the predicate function returns more than 1 value, the other values are passed ++---to the command. ++--- ++---Otherwise, the arguments passed into this function are passed directly ++---to the command. ++---@see core.command.predicate ++---@see core.command.predicate_function ++---@param name core.command.command_name ++---@param ... any ++---@return boolean # true if the command is performed successfully. ++function command.perform(name, ...) ++ local ok, res = core.try(perform, name, ...) + return not ok or res + end + + ++---Inserts the default commands for Lite XL into the map. + function command.add_defaults() + local reg = { + "core", "root", "command", "doc", "findreplace", diff --git a/tasks/lite-xl__lite-xl-1564/solution/solve.sh b/tasks/lite-xl__lite-xl-1564/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/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/lite-xl__lite-xl-1564/task.toml b/tasks/lite-xl__lite-xl-1564/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2e076e600d0c4ac330edc8bb5077e14f63972d8c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1564" +description = "Documentation for core.command" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7b330ae81b942f91a45c9cfa45f44454da867303" +reference = "https://github.com/lite-xl/lite-xl/pull/1564" +source_access = "auto" +built_at = "2026-11-16T16:09:56.234117+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:47e9a344a78101d63540234dc288fd2ba9e0dbb6e52672809cb1932069aa0bbc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-07-27T11:04:45Z" +diff_format = "unified" +context_files = [ + "data/core/command.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 98 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.287793+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:08d80a5f05d343227911a77cbb5b9db39fc4bce0c3256c3365d4cf00e2d27e77" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1564/tests/capture.py b/tasks/lite-xl__lite-xl-1564/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/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/lite-xl__lite-xl-1564/tests/instruction.md b/tasks/lite-xl__lite-xl-1564/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f593fc036b9d4082de8aed6a5a974d56e6452e7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.command + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b330ae81b94`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1564/tests/oracle.patch b/tasks/lite-xl__lite-xl-1564/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eda6e800b0a56bfb9172b755781f9392d15aba04 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/tests/oracle.patch @@ -0,0 +1,156 @@ +diff --git a/data/core/command.lua b/data/core/command.lua +index faf872e2..2b28f63b 100644 +--- a/data/core/command.lua ++++ b/data/core/command.lua +@@ -1,25 +1,55 @@ + local core = require "core" + local command = {} + ++---A predicate function accepts arguments from `command.perform()` and evaluates to a boolean.
++---If the function returns true, then the function associated with the command is executed. ++--- ++---The predicate function can also return other values after the boolean, which will ++---be passed into the function associated with the command. ++---@alias core.command.predicate_function fun(...: any): boolean, ... ++ ++---A predicate is a string, an Object or a function, that is used to determine ++---whether a command should be executed. ++--- ++---If the predicate is a string, it is resolved into an `Object` via `require()` ++---and checked against the active view with `Object:extends()`.
++---For example, `"core.docview"` will match any view that inherits from `DocView`.
++---A `!` can be appended to the predicate to strictly match the current view via `Object:is()`, ++---instead of matching any view that inherits the predicate. ++--- ++---If the predicate is a table, it is checked against the active view with `Object:extends()`. ++---Strict matching via `Object:is()` is not available. ++--- ++---If the predicate is a function, it must behave like a predicate function. ++---@see core.command.predicate_function ++---@alias core.command.predicate string|core.object|core.command.predicate_function ++ ++---A command is identified by a command name. ++---The command name contains a category and the name itself, separated by a colon (':'). ++--- ++---All commands should be in lowercase and should not contain whitespaces; instead ++---they should be replaced by a dash ('-'). ++---@alias core.command.command_name string ++ ++---The predicate and its associated function. ++---@class core.command.command ++---@field predicate core.command.predicate_function ++---@field perform fun(...: any) ++ ++---@type { [string]: core.command.command } + command.map = {} + ++---@type core.command.predicate_function + local always_true = function() return true end + + +----Used iternally by command.add, statusview, and contextmenu to generate a +----function with a condition to evaluate returning the boolean result of this +----evaluation. ++---This function takes in a predicate and produces a predicate function ++---that is internally used to dispatch and execute commands. + --- +----If a string predicate is given it is treated as a require import that should +----return a valid object which is checked against the current active view, +----eg: "core.docview" will match any view that inherits from DocView. Appending +----a `!` at the end of the string means we want to match the given object +----from the import strcitly eg: "core.docview!" only DocView is matched. +----A function that returns a boolean can be used instead to perform a custom +----evaluation, setting to nil means always evaluates to true. +---- +----@param predicate string | table | function +----@return function ++---This function should not be called manually. ++---@see core.command.predicate ++---@param predicate core.command.predicate|nil If nil, the predicate always evaluates to true. ++---@return core.command.predicate_function + function command.generate_predicate(predicate) + predicate = predicate or always_true + local strict = false +@@ -38,10 +68,20 @@ function command.generate_predicate(predicate) + predicate = function(...) return core.active_view:is(class), core.active_view, ... end + end + end ++ ---@cast predicate core.command.predicate_function + return predicate + end + + ++---Adds commands to the map. ++--- ++---The function accepts a table containing a list of commands ++---and their functions.
++---If a command already exists, it will be replaced. ++---@see core.command.predicate ++---@see core.command.command_name ++---@param predicate core.command.predicate ++---@param map { [core.command.command_name]: fun(...: any) } + function command.add(predicate, map) + predicate = command.generate_predicate(predicate) + for name, fn in pairs(map) do +@@ -57,11 +97,21 @@ local function capitalize_first(str) + return str:sub(1, 1):upper() .. str:sub(2) + end + ++---Prettifies the command name. ++--- ++---This function adds a space between the colon and the command name, ++---replaces dashes with spaces and capitalizes the command appropriately. ++---@see core.command.command_name ++---@param name core.command.command_name ++---@return string + function command.prettify_name(name) ++ ---@diagnostic disable-next-line: redundant-return-value + return name:gsub(":", ": "):gsub("-", " "):gsub("%S+", capitalize_first) + end + + ++---Returns all the commands that can be executed (their predicates evaluate to true). ++---@return core.command.command_name[] + function command.get_all_valid() + local res = {} + local memoized_predicates = {} +@@ -76,6 +126,10 @@ function command.get_all_valid() + return res + end + ++---Checks whether a command can be executed (its predicate evaluates to true). ++---@param name core.command.command_name ++---@param ... any ++---@return boolean + function command.is_valid(name, ...) + return command.map[name] and command.map[name].predicate(...) + end +@@ -98,12 +152,26 @@ local function perform(name, ...) + end + + +-function command.perform(...) +- local ok, res = core.try(perform, ...) ++---Performs a command. ++--- ++---The arguments passed into this function are forwarded to the predicate function.
++---If the predicate function returns more than 1 value, the other values are passed ++---to the command. ++--- ++---Otherwise, the arguments passed into this function are passed directly ++---to the command. ++---@see core.command.predicate ++---@see core.command.predicate_function ++---@param name core.command.command_name ++---@param ... any ++---@return boolean # true if the command is performed successfully. ++function command.perform(name, ...) ++ local ok, res = core.try(perform, name, ...) + return not ok or res + end + + ++---Inserts the default commands for Lite XL into the map. + function command.add_defaults() + local reg = { + "core", "root", "command", "doc", "findreplace", diff --git a/tasks/lite-xl__lite-xl-1564/tests/test.sh b/tasks/lite-xl__lite-xl-1564/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7069fc218d730c63bbc81b40da92732049149d74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/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 7b330ae81b942f91a45c9cfa45f44454da867303 > "$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/lite-xl__lite-xl-1564/tests/verifier.py b/tasks/lite-xl__lite-xl-1564/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1564/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/lite-xl__lite-xl-1565/environment/Dockerfile b/tasks/lite-xl__lite-xl-1565/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79f6aaffbbf5305249b71b69391ee9b034229a9a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 819fa9d30e2c0e737fad519fbff63ce2baff4456 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && 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/lite-xl__lite-xl-1565/instruction.md b/tasks/lite-xl__lite-xl-1565/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5d1ace4510f8f07867da5341e6e58b1a06ad072f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.dirwatch + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1565/solution/patch.diff b/tasks/lite-xl__lite-xl-1565/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ae677097c1c6319cc6be9808e6c0825ef963bcb2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/solution/patch.diff @@ -0,0 +1,129 @@ +diff --git a/data/core/dirwatch.lua b/data/core/dirwatch.lua +index 16aecd77..0cad65cd 100644 +--- a/data/core/dirwatch.lua ++++ b/data/core/dirwatch.lua +@@ -8,6 +8,21 @@ function dirwatch:__index(idx) + return dirwatch[idx] + end + ++---A directory watcher. ++--- ++---It can be used to watch changes in files and directories. ++---The user repeatedly calls dirwatch:check() with a callback inside a coroutine. ++---If a file or directory had changed, the callback is called with the corresponding file. ++---@class core.dirwatch ++---@field scanned { [string]: number } Stores the last modified time of paths. ++---@field watched { [string]: boolean|number } Stores the paths that are being watched, and their unique fd. ++---@field reverse_watched { [number]: string } Stores the paths mapped by their unique fd. ++---@field monitor dirmonitor The dirmonitor instance associated with this watcher. ++---@field single_watch_top string The first file that is being watched. ++---@field single_watch_count number Number of files that are being watched. ++ ++---Creates a directory monitor. ++---@return core.dirwatch + function dirwatch.new() + local t = { + scanned = {}, +@@ -22,54 +37,65 @@ function dirwatch.new() + end + + +-function dirwatch:scan(directory, bool) +- if bool == false then return self:unwatch(directory) end +- self.scanned[directory] = system.get_file_info(directory).modified ++---Schedules a path for scanning. ++---If a path points to a file, it is watched directly. ++---Otherwise, the contents of the path are watched (non-recursively). ++---@param path string ++---@param unwatch? boolean If true, remove this directory from the watch list. ++function dirwatch:scan(path, unwatch) ++ if unwatch == false then return self:unwatch(path) end ++ self.scanned[path] = system.get_file_info(path).modified + end + +--- Should be called on every directory in a subdirectory. +--- On Windows, this is a no-op for anything underneath a top-level directory, +--- but code should be called anyway, so we can ensure that we have a proper +--- experience across all platforms. Should be an absolute path. +--- Can also be called on individual files, though this should be used sparingly, +--- so as not to run into system limits (like in the autoreload plugin). +-function dirwatch:watch(directory, bool) +- if bool == false then return self:unwatch(directory) end +- local info = system.get_file_info(directory) ++ ++---Watches a path. ++--- ++---It is recommended to call this function on every subdirectory if the given path ++---points to a directory. This is not required for Windows, but should be done to ensure ++---cross-platform compatibility. ++--- ++---Using this function on individual files is possible, but discouraged as it can cause ++---system resource exhaustion. ++---@param path string The path to watch. This should be an absolute path. ++---@param unwatch? boolean If true, the path is removed from the watch list. ++function dirwatch:watch(path, unwatch) ++ if unwatch == false then return self:unwatch(path) end ++ local info = system.get_file_info(path) + if not info then return end +- if not self.watched[directory] and not self.scanned[directory] then ++ if not self.watched[path] and not self.scanned[path] then + if self.monitor:mode() == "single" then +- if info.type ~= "dir" then return self:scan(directory) end +- if not self.single_watch_top or directory:find(self.single_watch_top, 1, true) ~= 1 then ++ if info.type ~= "dir" then return self:scan(path) end ++ if not self.single_watch_top or path:find(self.single_watch_top, 1, true) ~= 1 then + -- Get the highest level of directory that is common to this directory, and the original. +- local target = directory ++ local target = path + while self.single_watch_top and self.single_watch_top:find(target, 1, true) ~= 1 do + target = common.dirname(target) + end + if target ~= self.single_watch_top then + local value = self.monitor:watch(target) + if value and value < 0 then +- return self:scan(directory) ++ return self:scan(path) + end + self.single_watch_top = target + end + end + self.single_watch_count = self.single_watch_count + 1 +- self.watched[directory] = true ++ self.watched[path] = true + else +- local value = self.monitor:watch(directory) ++ local value = self.monitor:watch(path) + -- If for whatever reason, we can't watch this directory, revert back to scanning. + -- Don't bother trying to find out why, for now. + if value and value < 0 then +- return self:scan(directory) ++ return self:scan(path) + end +- self.watched[directory] = value +- self.reverse_watched[value] = directory ++ self.watched[path] = value ++ self.reverse_watched[value] = path + end + end + end + +--- this should be an absolute path ++---Removes a path from the watch list. ++---@param directory string The path to remove. This should be an absolute path. + function dirwatch:unwatch(directory) + if self.watched[directory] then + if self.monitor:mode() == "multiple" then +@@ -88,7 +114,12 @@ function dirwatch:unwatch(directory) + end + end + +--- designed to be run inside a coroutine. ++---Checks each watched paths for changes. ++---This function must be called in a coroutine, e.g. inside a thread created with `core.add_thread()`. ++---@param change_callback fun(path: string) ++---@param scan_time? number Maximum amount of time, in seconds, before the function yields execution. ++---@param wait_time? number The duration to yield execution (in seconds). ++---@return boolean # If true, a path had changed. + function dirwatch:check(change_callback, scan_time, wait_time) + local had_change = false + local last_error diff --git a/tasks/lite-xl__lite-xl-1565/solution/solve.sh b/tasks/lite-xl__lite-xl-1565/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/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/lite-xl__lite-xl-1565/task.toml b/tasks/lite-xl__lite-xl-1565/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6906bb8a2789e6c0aea001ea9b4b1e0b666f2f02 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1565" +description = "Documentation for core.dirwatch" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "819fa9d30e2c0e737fad519fbff63ce2baff4456" +reference = "https://github.com/lite-xl/lite-xl/pull/1565" +source_access = "auto" +built_at = "2026-11-16T16:09:56.174902+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cc77e8120c401077586a6ad3d1759ae004fa0ef4faaf6b40b70a70fe36b4b68c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-08-29T15:39:53Z" +diff_format = "unified" +context_files = [ + "data/core/dirwatch.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 71 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.288229+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8157ccb850d65e11de5d9535f476f68f7af87fe114bfff9d7bfe590be94ed8a2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1565/tests/capture.py b/tasks/lite-xl__lite-xl-1565/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/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/lite-xl__lite-xl-1565/tests/instruction.md b/tasks/lite-xl__lite-xl-1565/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5d1ace4510f8f07867da5341e6e58b1a06ad072f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.dirwatch + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1565/tests/oracle.patch b/tasks/lite-xl__lite-xl-1565/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ae677097c1c6319cc6be9808e6c0825ef963bcb2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/tests/oracle.patch @@ -0,0 +1,129 @@ +diff --git a/data/core/dirwatch.lua b/data/core/dirwatch.lua +index 16aecd77..0cad65cd 100644 +--- a/data/core/dirwatch.lua ++++ b/data/core/dirwatch.lua +@@ -8,6 +8,21 @@ function dirwatch:__index(idx) + return dirwatch[idx] + end + ++---A directory watcher. ++--- ++---It can be used to watch changes in files and directories. ++---The user repeatedly calls dirwatch:check() with a callback inside a coroutine. ++---If a file or directory had changed, the callback is called with the corresponding file. ++---@class core.dirwatch ++---@field scanned { [string]: number } Stores the last modified time of paths. ++---@field watched { [string]: boolean|number } Stores the paths that are being watched, and their unique fd. ++---@field reverse_watched { [number]: string } Stores the paths mapped by their unique fd. ++---@field monitor dirmonitor The dirmonitor instance associated with this watcher. ++---@field single_watch_top string The first file that is being watched. ++---@field single_watch_count number Number of files that are being watched. ++ ++---Creates a directory monitor. ++---@return core.dirwatch + function dirwatch.new() + local t = { + scanned = {}, +@@ -22,54 +37,65 @@ function dirwatch.new() + end + + +-function dirwatch:scan(directory, bool) +- if bool == false then return self:unwatch(directory) end +- self.scanned[directory] = system.get_file_info(directory).modified ++---Schedules a path for scanning. ++---If a path points to a file, it is watched directly. ++---Otherwise, the contents of the path are watched (non-recursively). ++---@param path string ++---@param unwatch? boolean If true, remove this directory from the watch list. ++function dirwatch:scan(path, unwatch) ++ if unwatch == false then return self:unwatch(path) end ++ self.scanned[path] = system.get_file_info(path).modified + end + +--- Should be called on every directory in a subdirectory. +--- On Windows, this is a no-op for anything underneath a top-level directory, +--- but code should be called anyway, so we can ensure that we have a proper +--- experience across all platforms. Should be an absolute path. +--- Can also be called on individual files, though this should be used sparingly, +--- so as not to run into system limits (like in the autoreload plugin). +-function dirwatch:watch(directory, bool) +- if bool == false then return self:unwatch(directory) end +- local info = system.get_file_info(directory) ++ ++---Watches a path. ++--- ++---It is recommended to call this function on every subdirectory if the given path ++---points to a directory. This is not required for Windows, but should be done to ensure ++---cross-platform compatibility. ++--- ++---Using this function on individual files is possible, but discouraged as it can cause ++---system resource exhaustion. ++---@param path string The path to watch. This should be an absolute path. ++---@param unwatch? boolean If true, the path is removed from the watch list. ++function dirwatch:watch(path, unwatch) ++ if unwatch == false then return self:unwatch(path) end ++ local info = system.get_file_info(path) + if not info then return end +- if not self.watched[directory] and not self.scanned[directory] then ++ if not self.watched[path] and not self.scanned[path] then + if self.monitor:mode() == "single" then +- if info.type ~= "dir" then return self:scan(directory) end +- if not self.single_watch_top or directory:find(self.single_watch_top, 1, true) ~= 1 then ++ if info.type ~= "dir" then return self:scan(path) end ++ if not self.single_watch_top or path:find(self.single_watch_top, 1, true) ~= 1 then + -- Get the highest level of directory that is common to this directory, and the original. +- local target = directory ++ local target = path + while self.single_watch_top and self.single_watch_top:find(target, 1, true) ~= 1 do + target = common.dirname(target) + end + if target ~= self.single_watch_top then + local value = self.monitor:watch(target) + if value and value < 0 then +- return self:scan(directory) ++ return self:scan(path) + end + self.single_watch_top = target + end + end + self.single_watch_count = self.single_watch_count + 1 +- self.watched[directory] = true ++ self.watched[path] = true + else +- local value = self.monitor:watch(directory) ++ local value = self.monitor:watch(path) + -- If for whatever reason, we can't watch this directory, revert back to scanning. + -- Don't bother trying to find out why, for now. + if value and value < 0 then +- return self:scan(directory) ++ return self:scan(path) + end +- self.watched[directory] = value +- self.reverse_watched[value] = directory ++ self.watched[path] = value ++ self.reverse_watched[value] = path + end + end + end + +--- this should be an absolute path ++---Removes a path from the watch list. ++---@param directory string The path to remove. This should be an absolute path. + function dirwatch:unwatch(directory) + if self.watched[directory] then + if self.monitor:mode() == "multiple" then +@@ -88,7 +114,12 @@ function dirwatch:unwatch(directory) + end + end + +--- designed to be run inside a coroutine. ++---Checks each watched paths for changes. ++---This function must be called in a coroutine, e.g. inside a thread created with `core.add_thread()`. ++---@param change_callback fun(path: string) ++---@param scan_time? number Maximum amount of time, in seconds, before the function yields execution. ++---@param wait_time? number The duration to yield execution (in seconds). ++---@return boolean # If true, a path had changed. + function dirwatch:check(change_callback, scan_time, wait_time) + local had_change = false + local last_error diff --git a/tasks/lite-xl__lite-xl-1565/tests/test.sh b/tasks/lite-xl__lite-xl-1565/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b633fca4f9bab861c01a786a0068cc7c5aeb58d3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/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 819fa9d30e2c0e737fad519fbff63ce2baff4456 > "$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/lite-xl__lite-xl-1565/tests/verifier.py b/tasks/lite-xl__lite-xl-1565/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1565/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/lite-xl__lite-xl-1567/environment/Dockerfile b/tasks/lite-xl__lite-xl-1567/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c08e1b5c8f679bac8db233efe182747677df127a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7b330ae81b942f91a45c9cfa45f44454da867303 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7b330ae81b942f91a45c9cfa45f44454da867303 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7b330ae81b942f91a45c9cfa45f44454da867303 \ + && 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/lite-xl__lite-xl-1567/instruction.md b/tasks/lite-xl__lite-xl-1567/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f3245a695184e482701f3225381a669b248367d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.contextmenu + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b330ae81b94`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1567/solution/patch.diff b/tasks/lite-xl__lite-xl-1567/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a367de176ece7777ee61358dbe76457a958f5ea0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/solution/patch.diff @@ -0,0 +1,168 @@ +diff --git a/data/core/contextmenu.lua b/data/core/contextmenu.lua +index 4b466907..d59609d7 100644 +--- a/data/core/contextmenu.lua ++++ b/data/core/contextmenu.lua +@@ -12,11 +12,31 @@ local divider_width = 1 + local divider_padding = 5 + local DIVIDER = {} + ++---An item in the context menu. ++---@class core.contextmenu.item ++---@field text string ++---@field info string|nil If provided, this text is displayed on the right side of the menu. ++---@field command string|fun() ++ ++---A list of items with the same predicate. ++---@see core.command.predicate ++---@class core.contextmenu.itemset ++---@field predicate core.command.predicate ++---@field items core.contextmenu.item[] ++ ++---A context menu. + ---@class core.contextmenu : core.object ++---@field itemset core.contextmenu.itemset[] ++---@field show_context_menu boolean ++---@field selected number ++---@field position core.view.position ++---@field current_scale number + local ContextMenu = Object:extend() + ++---A unique value representing the divider in a context menu. + ContextMenu.DIVIDER = DIVIDER + ++---Creates a new context menu. + function ContextMenu:new() + self.itemset = {} + self.show_context_menu = false +@@ -55,12 +75,19 @@ local function update_items_size(items, update_binding) + items.width, items.height = width, height + end + ++---Registers a list of items into the context menu with a predicate. ++---@param predicate core.command.predicate ++---@param items core.contextmenu.item[] + function ContextMenu:register(predicate, items) + predicate = command.generate_predicate(predicate) + update_items_size(items, true) + table.insert(self.itemset, { predicate = predicate, items = items }) + end + ++---Shows the context menu. ++---@param x number ++---@param y number ++---@return boolean # If true, the context menu is shown. + function ContextMenu:show(x, y) + self.items = nil + local items_list = { width = 0, height = 0 } +@@ -94,6 +121,7 @@ function ContextMenu:show(x, y) + return false + end + ++---Hides the context menu. + function ContextMenu:hide() + self.show_context_menu = false + self.items = nil +@@ -102,6 +130,8 @@ function ContextMenu:hide() + core.request_cursor(core.active_view.cursor) + end + ++---Returns an iterator that iterates over each context menu item and their dimensions. ++---@return fun(): number, core.contextmenu.item, number, number, number, number + function ContextMenu:each_item() + local x, y, w = self.position.x, self.position.y, self.items.width + local oy = y +@@ -115,8 +145,12 @@ function ContextMenu:each_item() + end) + end + ++---Event handler for mouse movements. ++---@param px any ++---@param py any ++---@return boolean # true if the event is caught. + function ContextMenu:on_mouse_moved(px, py) +- if not self.show_context_menu then return end ++ if not self.show_context_menu then return false end + + self.selected = -1 + for i, item, x, y, w, h in self:each_item() do +@@ -128,6 +162,8 @@ function ContextMenu:on_mouse_moved(px, py) + return true + end + ++---Event handler for when the selection is confirmed. ++---@param item core.contextmenu.item + function ContextMenu:on_selected(item) + if type(item.command) == "string" then + command.perform(item.command) +@@ -140,6 +176,7 @@ local function change_value(value, change) + return value + change + end + ++---Selects the the previous item. + function ContextMenu:focus_previous() + self.selected = (self.selected == -1 or self.selected == 1) and #self.items or change_value(self.selected, -1) + if self:get_item_selected() == DIVIDER then +@@ -147,6 +184,7 @@ function ContextMenu:focus_previous() + end + end + ++---Selects the next item. + function ContextMenu:focus_next() + self.selected = (self.selected == -1 or self.selected == #self.items) and 1 or change_value(self.selected, 1) + if self:get_item_selected() == DIVIDER then +@@ -154,10 +192,13 @@ function ContextMenu:focus_next() + end + end + ++---Gets the currently selected item. ++---@return core.contextmenu.item|nil + function ContextMenu:get_item_selected() + return (self.items or {})[self.selected] + end + ++---Hides the context menu and performs the command if an item is selected. + function ContextMenu:call_selected_item() + local selected = self:get_item_selected() + self:hide() +@@ -166,6 +207,12 @@ function ContextMenu:call_selected_item() + end + end + ++---Event handler for mouse press. ++---@param button core.view.mousebutton ++---@param px number ++---@param py number ++---@param clicks number ++---@return boolean # true if the event is caught. + function ContextMenu:on_mouse_pressed(button, px, py, clicks) + local caught = false + +@@ -186,14 +233,20 @@ function ContextMenu:on_mouse_pressed(button, px, py, clicks) + return caught + end + ++---@type fun(self: table, k: string, dest: number, rate?: number, name?: string) + ContextMenu.move_towards = View.move_towards + ++---Event handler for content update. + function ContextMenu:update() + if self.show_context_menu then + self:move_towards("height", self.items.height, nil, "contextmenu") + end + end + ++---Draws the context menu. ++--- ++---This wraps `ContextMenu:draw_context_menu()`. ++---@see core.contextmenu.draw_context_menu + function ContextMenu:draw() + if not self.show_context_menu then return end + if self.current_scale ~= SCALE then +@@ -206,6 +259,7 @@ function ContextMenu:draw() + core.root_view:defer_draw(self.draw_context_menu, self) + end + ++---Draws the context menu. + function ContextMenu:draw_context_menu() + if not self.items then return end + local bx, by, bw, bh = self.position.x, self.position.y, self.items.width, self.height diff --git a/tasks/lite-xl__lite-xl-1567/solution/solve.sh b/tasks/lite-xl__lite-xl-1567/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/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/lite-xl__lite-xl-1567/task.toml b/tasks/lite-xl__lite-xl-1567/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c294ba2582402e9ee1cb5c010d7517b6d737c2e1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1567" +description = "Documentation for core.contextmenu" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7b330ae81b942f91a45c9cfa45f44454da867303" +reference = "https://github.com/lite-xl/lite-xl/pull/1567" +source_access = "auto" +built_at = "2026-11-16T16:09:56.232469+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6190f70b0fd81dc590b79432b0b222b8c9b8174da99e6c0e655c5625af683173" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-08-25T02:32:07Z" +diff_format = "unified" +context_files = [ + "data/core/contextmenu.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 56 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.288659+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:08d80a5f05d343227911a77cbb5b9db39fc4bce0c3256c3365d4cf00e2d27e77" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1567/tests/capture.py b/tasks/lite-xl__lite-xl-1567/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/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/lite-xl__lite-xl-1567/tests/instruction.md b/tasks/lite-xl__lite-xl-1567/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f3245a695184e482701f3225381a669b248367d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Documentation for core.contextmenu + +## Description + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7b330ae81b94`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1567/tests/oracle.patch b/tasks/lite-xl__lite-xl-1567/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a367de176ece7777ee61358dbe76457a958f5ea0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/tests/oracle.patch @@ -0,0 +1,168 @@ +diff --git a/data/core/contextmenu.lua b/data/core/contextmenu.lua +index 4b466907..d59609d7 100644 +--- a/data/core/contextmenu.lua ++++ b/data/core/contextmenu.lua +@@ -12,11 +12,31 @@ local divider_width = 1 + local divider_padding = 5 + local DIVIDER = {} + ++---An item in the context menu. ++---@class core.contextmenu.item ++---@field text string ++---@field info string|nil If provided, this text is displayed on the right side of the menu. ++---@field command string|fun() ++ ++---A list of items with the same predicate. ++---@see core.command.predicate ++---@class core.contextmenu.itemset ++---@field predicate core.command.predicate ++---@field items core.contextmenu.item[] ++ ++---A context menu. + ---@class core.contextmenu : core.object ++---@field itemset core.contextmenu.itemset[] ++---@field show_context_menu boolean ++---@field selected number ++---@field position core.view.position ++---@field current_scale number + local ContextMenu = Object:extend() + ++---A unique value representing the divider in a context menu. + ContextMenu.DIVIDER = DIVIDER + ++---Creates a new context menu. + function ContextMenu:new() + self.itemset = {} + self.show_context_menu = false +@@ -55,12 +75,19 @@ local function update_items_size(items, update_binding) + items.width, items.height = width, height + end + ++---Registers a list of items into the context menu with a predicate. ++---@param predicate core.command.predicate ++---@param items core.contextmenu.item[] + function ContextMenu:register(predicate, items) + predicate = command.generate_predicate(predicate) + update_items_size(items, true) + table.insert(self.itemset, { predicate = predicate, items = items }) + end + ++---Shows the context menu. ++---@param x number ++---@param y number ++---@return boolean # If true, the context menu is shown. + function ContextMenu:show(x, y) + self.items = nil + local items_list = { width = 0, height = 0 } +@@ -94,6 +121,7 @@ function ContextMenu:show(x, y) + return false + end + ++---Hides the context menu. + function ContextMenu:hide() + self.show_context_menu = false + self.items = nil +@@ -102,6 +130,8 @@ function ContextMenu:hide() + core.request_cursor(core.active_view.cursor) + end + ++---Returns an iterator that iterates over each context menu item and their dimensions. ++---@return fun(): number, core.contextmenu.item, number, number, number, number + function ContextMenu:each_item() + local x, y, w = self.position.x, self.position.y, self.items.width + local oy = y +@@ -115,8 +145,12 @@ function ContextMenu:each_item() + end) + end + ++---Event handler for mouse movements. ++---@param px any ++---@param py any ++---@return boolean # true if the event is caught. + function ContextMenu:on_mouse_moved(px, py) +- if not self.show_context_menu then return end ++ if not self.show_context_menu then return false end + + self.selected = -1 + for i, item, x, y, w, h in self:each_item() do +@@ -128,6 +162,8 @@ function ContextMenu:on_mouse_moved(px, py) + return true + end + ++---Event handler for when the selection is confirmed. ++---@param item core.contextmenu.item + function ContextMenu:on_selected(item) + if type(item.command) == "string" then + command.perform(item.command) +@@ -140,6 +176,7 @@ local function change_value(value, change) + return value + change + end + ++---Selects the the previous item. + function ContextMenu:focus_previous() + self.selected = (self.selected == -1 or self.selected == 1) and #self.items or change_value(self.selected, -1) + if self:get_item_selected() == DIVIDER then +@@ -147,6 +184,7 @@ function ContextMenu:focus_previous() + end + end + ++---Selects the next item. + function ContextMenu:focus_next() + self.selected = (self.selected == -1 or self.selected == #self.items) and 1 or change_value(self.selected, 1) + if self:get_item_selected() == DIVIDER then +@@ -154,10 +192,13 @@ function ContextMenu:focus_next() + end + end + ++---Gets the currently selected item. ++---@return core.contextmenu.item|nil + function ContextMenu:get_item_selected() + return (self.items or {})[self.selected] + end + ++---Hides the context menu and performs the command if an item is selected. + function ContextMenu:call_selected_item() + local selected = self:get_item_selected() + self:hide() +@@ -166,6 +207,12 @@ function ContextMenu:call_selected_item() + end + end + ++---Event handler for mouse press. ++---@param button core.view.mousebutton ++---@param px number ++---@param py number ++---@param clicks number ++---@return boolean # true if the event is caught. + function ContextMenu:on_mouse_pressed(button, px, py, clicks) + local caught = false + +@@ -186,14 +233,20 @@ function ContextMenu:on_mouse_pressed(button, px, py, clicks) + return caught + end + ++---@type fun(self: table, k: string, dest: number, rate?: number, name?: string) + ContextMenu.move_towards = View.move_towards + ++---Event handler for content update. + function ContextMenu:update() + if self.show_context_menu then + self:move_towards("height", self.items.height, nil, "contextmenu") + end + end + ++---Draws the context menu. ++--- ++---This wraps `ContextMenu:draw_context_menu()`. ++---@see core.contextmenu.draw_context_menu + function ContextMenu:draw() + if not self.show_context_menu then return end + if self.current_scale ~= SCALE then +@@ -206,6 +259,7 @@ function ContextMenu:draw() + core.root_view:defer_draw(self.draw_context_menu, self) + end + ++---Draws the context menu. + function ContextMenu:draw_context_menu() + if not self.items then return end + local bx, by, bw, bh = self.position.x, self.position.y, self.items.width, self.height diff --git a/tasks/lite-xl__lite-xl-1567/tests/test.sh b/tasks/lite-xl__lite-xl-1567/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7069fc218d730c63bbc81b40da92732049149d74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/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 7b330ae81b942f91a45c9cfa45f44454da867303 > "$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/lite-xl__lite-xl-1567/tests/verifier.py b/tasks/lite-xl__lite-xl-1567/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1567/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/lite-xl__lite-xl-1569/environment/Dockerfile b/tasks/lite-xl__lite-xl-1569/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1569/instruction.md b/tasks/lite-xl__lite-xl-1569/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b5006555ec0874e9e01781b4968ad1d5b56a4c7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** feat(core.emptyview): add name to emptyview + +## Description + +This has always been a nit for me; When plugins fail to load it always shows `---` for `EmptyView`. +This PR changes it to `Get Started`. Maybe there are more suitable names, but I think this one's just fine. + +As a side effect, it also says `Get Started` when nothing is opened now. Perhaps it should return the current project name, etc. but I think this looks okay. +![image](https://github.com/lite-xl/lite-xl/assets/20792268/5ec9f849-45fd-4282-bb54-7f10ac87d033) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1569/solution/patch.diff b/tasks/lite-xl__lite-xl-1569/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..30cbb6c3024fb2c688815f6fcc2780b013c3ad74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/data/core/emptyview.lua b/data/core/emptyview.lua +index 2152da3b..865dc55d 100644 +--- a/data/core/emptyview.lua ++++ b/data/core/emptyview.lua +@@ -6,6 +6,14 @@ local View = require "core.view" + ---@field super core.view + local EmptyView = View:extend() + ++function EmptyView:get_name() ++ return "Get Started" ++end ++ ++function EmptyView:get_filename() ++ return "" ++end ++ + local function draw_text(x, y, color) + local lines = { + { fmt = "%s to run a command", cmd = "core:find-command" }, diff --git a/tasks/lite-xl__lite-xl-1569/solution/solve.sh b/tasks/lite-xl__lite-xl-1569/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/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/lite-xl__lite-xl-1569/task.toml b/tasks/lite-xl__lite-xl-1569/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d08753876f7f33b1e8e67e00cc200b2c395e1c8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1569" +description = "feat(core.emptyview): add name to emptyview" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1569" +source_access = "auto" +built_at = "2026-11-16T16:09:56.231119+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e95b2236a425c5d61d7b0012f5325a455c2df6d1c9053a9b49da1504ffacc53b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T16:44:04Z" +diff_format = "unified" +context_files = [ + "data/core/emptyview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.289096+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1569/tests/capture.py b/tasks/lite-xl__lite-xl-1569/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/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/lite-xl__lite-xl-1569/tests/instruction.md b/tasks/lite-xl__lite-xl-1569/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b5006555ec0874e9e01781b4968ad1d5b56a4c7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** feat(core.emptyview): add name to emptyview + +## Description + +This has always been a nit for me; When plugins fail to load it always shows `---` for `EmptyView`. +This PR changes it to `Get Started`. Maybe there are more suitable names, but I think this one's just fine. + +As a side effect, it also says `Get Started` when nothing is opened now. Perhaps it should return the current project name, etc. but I think this looks okay. +![image](https://github.com/lite-xl/lite-xl/assets/20792268/5ec9f849-45fd-4282-bb54-7f10ac87d033) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1569/tests/oracle.patch b/tasks/lite-xl__lite-xl-1569/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..30cbb6c3024fb2c688815f6fcc2780b013c3ad74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/data/core/emptyview.lua b/data/core/emptyview.lua +index 2152da3b..865dc55d 100644 +--- a/data/core/emptyview.lua ++++ b/data/core/emptyview.lua +@@ -6,6 +6,14 @@ local View = require "core.view" + ---@field super core.view + local EmptyView = View:extend() + ++function EmptyView:get_name() ++ return "Get Started" ++end ++ ++function EmptyView:get_filename() ++ return "" ++end ++ + local function draw_text(x, y, color) + local lines = { + { fmt = "%s to run a command", cmd = "core:find-command" }, diff --git a/tasks/lite-xl__lite-xl-1569/tests/test.sh b/tasks/lite-xl__lite-xl-1569/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1569/tests/verifier.py b/tasks/lite-xl__lite-xl-1569/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1569/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/lite-xl__lite-xl-1585/environment/Dockerfile b/tasks/lite-xl__lite-xl-1585/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..371314ba44d4f87d0ee5cc64f7b67567d1e967c8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 397973067f14420b26e3b20a238a50016c0b75e2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 397973067f14420b26e3b20a238a50016c0b75e2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 397973067f14420b26e3b20a238a50016c0b75e2 \ + && 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/lite-xl__lite-xl-1585/instruction.md b/tasks/lite-xl__lite-xl-1585/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e5301834cf849945e179ee64426e5b0826388b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(core): defer core:open-log until everything is loaded + +## Description + +Complements #1569. + +If a plugin / user module fails to load, the LogView is opened immediately, causing EmptyView to come later and adds a tab to the current Node. This prevents it by just opening LogView after EmptyView is displayed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `397973067f14`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1585/solution/patch.diff b/tasks/lite-xl__lite-xl-1585/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ce5bccdc1b9f2cb55972de6bea947d56c1b709f3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/data/core/init.lua b/data/core/init.lua +index 16cb265e..890d79c5 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -810,7 +810,11 @@ function core.init() + end + + if not plugins_success or got_user_error or got_project_error then +- command.perform("core:open-log") ++ -- defer LogView to after everything is initialized, ++ -- so that EmptyView won't be added after LogView. ++ core.add_thread(function() ++ command.perform("core:open-log") ++ end) + end + + core.configure_borderless_window() diff --git a/tasks/lite-xl__lite-xl-1585/solution/solve.sh b/tasks/lite-xl__lite-xl-1585/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/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/lite-xl__lite-xl-1585/task.toml b/tasks/lite-xl__lite-xl-1585/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46046577ad952d793459a570269524a369cd0d5c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1585" +description = "fix(core): defer core:open-log until everything is loaded" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "397973067f14420b26e3b20a238a50016c0b75e2" +reference = "https://github.com/lite-xl/lite-xl/pull/1585" +source_access = "auto" +built_at = "2026-11-16T16:09:56.229900+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:44e3557244e13ad053cff21f80d924e44e3d7a65a42a2a4f42ab689a08094499" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-08-18T13:25:10Z" +diff_format = "unified" +context_files = [ + "data/core/init.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.289547+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a456f3c2383aac0021478de5129d0c4e148a8425ce1e7f96819cd69048dbf937" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1585/tests/capture.py b/tasks/lite-xl__lite-xl-1585/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/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/lite-xl__lite-xl-1585/tests/instruction.md b/tasks/lite-xl__lite-xl-1585/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e5301834cf849945e179ee64426e5b0826388b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(core): defer core:open-log until everything is loaded + +## Description + +Complements #1569. + +If a plugin / user module fails to load, the LogView is opened immediately, causing EmptyView to come later and adds a tab to the current Node. This prevents it by just opening LogView after EmptyView is displayed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `397973067f14`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1585/tests/oracle.patch b/tasks/lite-xl__lite-xl-1585/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ce5bccdc1b9f2cb55972de6bea947d56c1b709f3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/data/core/init.lua b/data/core/init.lua +index 16cb265e..890d79c5 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -810,7 +810,11 @@ function core.init() + end + + if not plugins_success or got_user_error or got_project_error then +- command.perform("core:open-log") ++ -- defer LogView to after everything is initialized, ++ -- so that EmptyView won't be added after LogView. ++ core.add_thread(function() ++ command.perform("core:open-log") ++ end) + end + + core.configure_borderless_window() diff --git a/tasks/lite-xl__lite-xl-1585/tests/test.sh b/tasks/lite-xl__lite-xl-1585/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..be76e627224a3451f54cde4c53628aaedf906cf6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/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 397973067f14420b26e3b20a238a50016c0b75e2 > "$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/lite-xl__lite-xl-1585/tests/verifier.py b/tasks/lite-xl__lite-xl-1585/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1585/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/lite-xl__lite-xl-1589/environment/Dockerfile b/tasks/lite-xl__lite-xl-1589/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1589/instruction.md b/tasks/lite-xl__lite-xl-1589/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b41719c7da6c9e6663f5a95bed2ab3cfe34ed3d9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add `minimum_thumb_size` and `{contracted,expanded}_scrollbar_margin` to `Scrollbar` + +## Description + +This will be useful for accessibility reasons, and to simplify the `minimap` plugin. + +Might need a modversion bump. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1589/solution/patch.diff b/tasks/lite-xl__lite-xl-1589/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8505196416274a783eca3d96a5fa6b6adffd4387 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/solution/patch.diff @@ -0,0 +1,68 @@ +diff --git a/data/core/scrollbar.lua b/data/core/scrollbar.lua +index c7590b8c..51e02be6 100644 +--- a/data/core/scrollbar.lua ++++ b/data/core/scrollbar.lua +@@ -25,6 +25,9 @@ local Scrollbar = Object:extend() + ---@field force_status "expanded" | "contracted" | false @Force the scrollbar status + ---@field expanded_size number? @Override the default value specified by `style.expanded_scrollbar_size` + ---@field contracted_size number? @Override the default value specified by `style.scrollbar_size` ++---@field minimum_thumb_size number? @Override the default value specified by `style.minimum_thumb_size` ++---@field contracted_margin number? @Override the default value specified by `style.contracted_scrollbar_margin` ++---@field expanded_margin number? @Override the default value specified by `style.expanded_scrollbar_margin` + + ---@param options ScrollbarOptions + function Scrollbar:new(options) +@@ -62,6 +65,12 @@ function Scrollbar:new(options) + self.contracted_size = options.contracted_size + ---@type number? @Override the default value specified by `style.scrollbar_size` + self.expanded_size = options.expanded_size ++ ---@type number? @Override the default value specified by `style.minimum_thumb_size` ++ self.minimum_thumb_size = options.minimum_thumb_size ++ ---@type number? @Override the default value specified by `style.contracted_scrollbar_margin` ++ self.contracted_margin = options.contracted_margin ++ ---@type number? @Override the default value specified by `style.expanded_scrollbar_margin` ++ self.expanded_margin = options.expanded_margin + end + + +@@ -116,7 +125,7 @@ function Scrollbar:_get_thumb_rect_normal() + end + local scrollbar_size = self.contracted_size or style.scrollbar_size + local expanded_scrollbar_size = self.expanded_size or style.expanded_scrollbar_size +- local along_size = math.max(20, nr.along_size * nr.along_size / sz) ++ local along_size = math.max(self.minimum_thumb_size or style.minimum_thumb_size, nr.along_size * nr.along_size / sz) + local across_size = scrollbar_size + across_size = across_size + (expanded_scrollbar_size - scrollbar_size) * self.expand_percent + return +@@ -159,13 +168,14 @@ end + + function Scrollbar:_overlaps_normal(x, y) + local sx, sy, sw, sh = self:_get_thumb_rect_normal() +- local scrollbar_size = self.contracted_size or style.scrollbar_size ++ local scrollbar_margin = self.expand_percent * (self.expanded_margin or style.expanded_scrollbar_margin) + ++ (1 - self.expand_percent) * (self.contracted_margin or style.contracted_scrollbar_margin) + local result +- if x >= sx - scrollbar_size * 3 and x <= sx + sw and y >= sy and y <= sy + sh then ++ if x >= sx - scrollbar_margin and x <= sx + sw and y >= sy and y <= sy + sh then + result = "thumb" + else + sx, sy, sw, sh = self:_get_track_rect_normal() +- if x >= sx - scrollbar_size * 3 and x <= sx + sw and y >= sy and y <= sy + sh then ++ if x >= sx - scrollbar_margin and x <= sx + sw and y >= sy and y <= sy + sh then + result = "track" + end + end +diff --git a/data/core/style.lua b/data/core/style.lua +index 8f174315..447fd7d2 100644 +--- a/data/core/style.lua ++++ b/data/core/style.lua +@@ -4,6 +4,9 @@ local style = {} + style.divider_size = common.round(1 * SCALE) + style.scrollbar_size = common.round(4 * SCALE) + style.expanded_scrollbar_size = common.round(12 * SCALE) ++style.minimum_thumb_size = common.round(20 * SCALE) ++style.contracted_scrollbar_margin = common.round(8 * SCALE) ++style.expanded_scrollbar_margin = common.round(12 * SCALE) + style.caret_width = common.round(2 * SCALE) + style.tab_width = common.round(170 * SCALE) + diff --git a/tasks/lite-xl__lite-xl-1589/solution/solve.sh b/tasks/lite-xl__lite-xl-1589/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/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/lite-xl__lite-xl-1589/task.toml b/tasks/lite-xl__lite-xl-1589/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da11ec4f1e30a0902a13aa925d0a93c17092563a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1589" +description = "Add `minimum_thumb_size` and `{contracted,expanded}_scrollbar_margin` to `Scrollbar`" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1589" +source_access = "auto" +built_at = "2026-11-16T16:09:56.333263+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0f71a3400275b03cf8bfaf8a1dcd65d93b3a12259e6622d269a615a688bab4b5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T17:05:07Z" +diff_format = "unified" +context_files = [ + "data/core/scrollbar.lua", + "data/core/style.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 21 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.290000+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1589/tests/capture.py b/tasks/lite-xl__lite-xl-1589/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/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/lite-xl__lite-xl-1589/tests/instruction.md b/tasks/lite-xl__lite-xl-1589/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b41719c7da6c9e6663f5a95bed2ab3cfe34ed3d9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add `minimum_thumb_size` and `{contracted,expanded}_scrollbar_margin` to `Scrollbar` + +## Description + +This will be useful for accessibility reasons, and to simplify the `minimap` plugin. + +Might need a modversion bump. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1589/tests/oracle.patch b/tasks/lite-xl__lite-xl-1589/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8505196416274a783eca3d96a5fa6b6adffd4387 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/tests/oracle.patch @@ -0,0 +1,68 @@ +diff --git a/data/core/scrollbar.lua b/data/core/scrollbar.lua +index c7590b8c..51e02be6 100644 +--- a/data/core/scrollbar.lua ++++ b/data/core/scrollbar.lua +@@ -25,6 +25,9 @@ local Scrollbar = Object:extend() + ---@field force_status "expanded" | "contracted" | false @Force the scrollbar status + ---@field expanded_size number? @Override the default value specified by `style.expanded_scrollbar_size` + ---@field contracted_size number? @Override the default value specified by `style.scrollbar_size` ++---@field minimum_thumb_size number? @Override the default value specified by `style.minimum_thumb_size` ++---@field contracted_margin number? @Override the default value specified by `style.contracted_scrollbar_margin` ++---@field expanded_margin number? @Override the default value specified by `style.expanded_scrollbar_margin` + + ---@param options ScrollbarOptions + function Scrollbar:new(options) +@@ -62,6 +65,12 @@ function Scrollbar:new(options) + self.contracted_size = options.contracted_size + ---@type number? @Override the default value specified by `style.scrollbar_size` + self.expanded_size = options.expanded_size ++ ---@type number? @Override the default value specified by `style.minimum_thumb_size` ++ self.minimum_thumb_size = options.minimum_thumb_size ++ ---@type number? @Override the default value specified by `style.contracted_scrollbar_margin` ++ self.contracted_margin = options.contracted_margin ++ ---@type number? @Override the default value specified by `style.expanded_scrollbar_margin` ++ self.expanded_margin = options.expanded_margin + end + + +@@ -116,7 +125,7 @@ function Scrollbar:_get_thumb_rect_normal() + end + local scrollbar_size = self.contracted_size or style.scrollbar_size + local expanded_scrollbar_size = self.expanded_size or style.expanded_scrollbar_size +- local along_size = math.max(20, nr.along_size * nr.along_size / sz) ++ local along_size = math.max(self.minimum_thumb_size or style.minimum_thumb_size, nr.along_size * nr.along_size / sz) + local across_size = scrollbar_size + across_size = across_size + (expanded_scrollbar_size - scrollbar_size) * self.expand_percent + return +@@ -159,13 +168,14 @@ end + + function Scrollbar:_overlaps_normal(x, y) + local sx, sy, sw, sh = self:_get_thumb_rect_normal() +- local scrollbar_size = self.contracted_size or style.scrollbar_size ++ local scrollbar_margin = self.expand_percent * (self.expanded_margin or style.expanded_scrollbar_margin) + ++ (1 - self.expand_percent) * (self.contracted_margin or style.contracted_scrollbar_margin) + local result +- if x >= sx - scrollbar_size * 3 and x <= sx + sw and y >= sy and y <= sy + sh then ++ if x >= sx - scrollbar_margin and x <= sx + sw and y >= sy and y <= sy + sh then + result = "thumb" + else + sx, sy, sw, sh = self:_get_track_rect_normal() +- if x >= sx - scrollbar_size * 3 and x <= sx + sw and y >= sy and y <= sy + sh then ++ if x >= sx - scrollbar_margin and x <= sx + sw and y >= sy and y <= sy + sh then + result = "track" + end + end +diff --git a/data/core/style.lua b/data/core/style.lua +index 8f174315..447fd7d2 100644 +--- a/data/core/style.lua ++++ b/data/core/style.lua +@@ -4,6 +4,9 @@ local style = {} + style.divider_size = common.round(1 * SCALE) + style.scrollbar_size = common.round(4 * SCALE) + style.expanded_scrollbar_size = common.round(12 * SCALE) ++style.minimum_thumb_size = common.round(20 * SCALE) ++style.contracted_scrollbar_margin = common.round(8 * SCALE) ++style.expanded_scrollbar_margin = common.round(12 * SCALE) + style.caret_width = common.round(2 * SCALE) + style.tab_width = common.round(170 * SCALE) + diff --git a/tasks/lite-xl__lite-xl-1589/tests/test.sh b/tasks/lite-xl__lite-xl-1589/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1589/tests/verifier.py b/tasks/lite-xl__lite-xl-1589/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1589/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/lite-xl__lite-xl-1617/environment/Dockerfile b/tasks/lite-xl__lite-xl-1617/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f73a11a3fec048f91b33918808c6f52a47da2c2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b4e95b865c9a18ba4cb193ff7d2f3657d8995cd8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b4e95b865c9a18ba4cb193ff7d2f3657d8995cd8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b4e95b865c9a18ba4cb193ff7d2f3657d8995cd8 \ + && 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/lite-xl__lite-xl-1617/instruction.md b/tasks/lite-xl__lite-xl-1617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68ab018f636b6229a727f1b3ec2fb59487c14fb7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Configurable statusview icon + +## Description + +For years now, this particular icon in the StatusView does not have any meaning into it. This PR fixes that. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b4e95b865c9a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1617/solution/patch.diff b/tasks/lite-xl__lite-xl-1617/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a1bc8f9dcb5cf1665cae6846bb9710849a1bada3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/solution/patch.diff @@ -0,0 +1,135 @@ +diff --git a/data/core/config.lua b/data/core/config.lua +index 2381639f..0dc6e706 100644 +--- a/data/core/config.lua ++++ b/data/core/config.lua +@@ -248,6 +248,13 @@ config.max_clicks = 3 + ---@type boolean + config.skip_plugins_version = false + ++---Increases the performance of the editor and its user. ++---Do not change this unless you know what you are doing. ++--- ++---Defaults to true. ++---@type boolean | { font: renderer.font, icon: string } | nil ++config.stonks = true ++ + -- holds the plugins real config table + local plugins_config = {} + +diff --git a/data/core/statusview.lua b/data/core/statusview.lua +index 3ef40d82..3165dbfb 100644 +--- a/data/core/statusview.lua ++++ b/data/core/statusview.lua +@@ -94,7 +94,7 @@ local StatusViewItem = Object:extend() + ---of 1 will insert the item at the beggining. + ---@field position? integer + ---@field tooltip? string @Text displayed when mouse hovers the item. +----@field visible boolean @Flag to show or hide the item ++---@field visible? boolean @Flag to show or hide the item + ---The type of separator rendered to the right of the item if another item + ---follows it. + ---@field separator? core.statusview.item.separator +@@ -190,6 +190,9 @@ function StatusView:new() + self:register_command_items() + end + ++local clicks = -1 ++local gx, gy, dx, dy, gc = 0, 0, 2, -2, { table.unpack(style.text) } ++ + ---The predefined status bar items displayed when a document view is active. + function StatusView:register_docview_items() + if self:get_item("doc:file") then return end +@@ -291,6 +294,28 @@ function StatusView:register_docview_items() + separator = self.separator2 + }) + ++ self:add_item({ ++ predicate = predicate_docview, ++ name = "doc:stats", ++ alignment = StatusView.Item.RIGHT, ++ get_item = function() ++ return config.stonks == nil and {} or { ++ style.text, ++ type(config.stonks) == "table" and config.stonks.font or style.icon_font, ++ type(config.stonks) == "table" and config.stonks.icon or ( config.stonks and "g" or "h" ), ++ } ++ end, ++ separator = self.separator2, ++ command = function(button, x, y) ++ if button == "left" then ++ clicks = clicks + 1 ++ elseif button == "right" then ++ clicks = -1 ++ end ++ gx, gy = x, y ++ end ++ }) ++ + self:add_item({ + predicate = predicate_docview, + name = "doc:lines", +@@ -298,9 +323,6 @@ function StatusView:register_docview_items() + get_item = function() + local dv = core.active_view + return { +- style.text, +- style.icon_font, "g", +- style.font, style.dim, self.separator2, + style.text, #dv.doc.lines, " lines", + } + end, +@@ -1200,6 +1222,25 @@ function StatusView:draw() + end + end + end ++ ++ if clicks > 5 then ++ if config.stonks == nil then clicks = -1 end ++ core.root_view:defer_draw(function() ++ local font = type(config.stonks) == "table" and config.stonks.font or style.icon_font ++ local icon = type(config.stonks) == "table" and config.stonks.icon or ( config.stonks and "g" or "h" ) ++ local xadv = renderer.draw_text(font, icon, gx, gy, gc) ++ local x2, y2 = core.root_view.size.x - (xadv - gx), core.root_view.size.y - font:get_height() ++ gx, gy = common.clamp(gx + dx, 0, x2), common.clamp(gy + dy, 0, y2) ++ local odx, ody = dx, dy ++ if gx <= 0 then dx = math.abs(dx) elseif gx >= x2 then dx = -math.abs(dx) end ++ if gy <= 0 then dy = math.abs(dy) elseif gy >= y2 then dy = -math.abs(dy) end ++ if odx ~= dx or ody ~= dy then ++ local major = math.random(1, 3) ++ for i = 1, 3 do gc[i] = major == i and math.random(200, 255) or math.random(0, 100) end ++ end ++ core.redraw = true ++ end) ++ end + end + + return StatusView +diff --git a/data/fonts/icons.ttf b/data/fonts/icons.ttf +index 5fd6d9e9..33d62b11 100644 +Binary files a/data/fonts/icons.ttf and b/data/fonts/icons.ttf differ +diff --git a/scripts/fontello-config.json b/scripts/fontello-config.json +index 76349182..e68f4cc3 100644 +--- a/scripts/fontello-config.json ++++ b/scripts/fontello-config.json +@@ -195,6 +195,20 @@ + "search": [ + "lite-xl4" + ] ++ }, ++ { ++ "uid": "b1c9ba6ba7db344177bf4906b41303ee", ++ "css": "chart-line-down", ++ "code": 104, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M1071.4 728.2V485.5Q1071.4 473.8 1060.5 469 1049.7 464.3 1040.7 473.2L973.2 540.7 620 187.5Q614.4 181.9 607.1 181.9 599.9 181.9 594.3 187.5L464.3 317.5 232.1 85.4 125 192.5 451.5 519Q457 524.6 464.3 524.6 471.5 524.6 477.1 519L607.1 389 866.1 647.9 798.5 715.4Q789.6 724.3 794.4 735.2 799.1 746.1 810.8 746.1H1053.6Q1061.4 746.1 1066.4 741.1 1071.4 736 1071.4 728.2ZM1142.9 799.7V871.1H0V14H71.4V799.7Z", ++ "width": 1154 ++ }, ++ "search": [ ++ "_481_fontawesome" ++ ] + } + ] + } +\ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1617/solution/solve.sh b/tasks/lite-xl__lite-xl-1617/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/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/lite-xl__lite-xl-1617/task.toml b/tasks/lite-xl__lite-xl-1617/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c4ceed6b9c61c5f999e885b7b5a0ba3515d377c7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1617" +description = "Configurable statusview icon" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "b4e95b865c9a18ba4cb193ff7d2f3657d8995cd8" +reference = "https://github.com/lite-xl/lite-xl/pull/1617" +source_access = "auto" +built_at = "2026-11-16T16:09:56.228598+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:045a7541fb0ff6149a71672cb3c2efd97dfb7ff4a998ae4cabafccb011a0366c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-09-03T17:42:55Z" +diff_format = "unified" +context_files = [ + "data/core/config.lua", + "data/core/statusview.lua", + "data/fonts/icons.ttf", + "scripts/fontello-config.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 70 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.290452+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33fa37e4dae2a2e02b09ddfca6f1fa21377261d816b6845bb0dad005399db547" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1617/tests/capture.py b/tasks/lite-xl__lite-xl-1617/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/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/lite-xl__lite-xl-1617/tests/instruction.md b/tasks/lite-xl__lite-xl-1617/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68ab018f636b6229a727f1b3ec2fb59487c14fb7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Configurable statusview icon + +## Description + +For years now, this particular icon in the StatusView does not have any meaning into it. This PR fixes that. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b4e95b865c9a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1617/tests/oracle.patch b/tasks/lite-xl__lite-xl-1617/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a1bc8f9dcb5cf1665cae6846bb9710849a1bada3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/tests/oracle.patch @@ -0,0 +1,135 @@ +diff --git a/data/core/config.lua b/data/core/config.lua +index 2381639f..0dc6e706 100644 +--- a/data/core/config.lua ++++ b/data/core/config.lua +@@ -248,6 +248,13 @@ config.max_clicks = 3 + ---@type boolean + config.skip_plugins_version = false + ++---Increases the performance of the editor and its user. ++---Do not change this unless you know what you are doing. ++--- ++---Defaults to true. ++---@type boolean | { font: renderer.font, icon: string } | nil ++config.stonks = true ++ + -- holds the plugins real config table + local plugins_config = {} + +diff --git a/data/core/statusview.lua b/data/core/statusview.lua +index 3ef40d82..3165dbfb 100644 +--- a/data/core/statusview.lua ++++ b/data/core/statusview.lua +@@ -94,7 +94,7 @@ local StatusViewItem = Object:extend() + ---of 1 will insert the item at the beggining. + ---@field position? integer + ---@field tooltip? string @Text displayed when mouse hovers the item. +----@field visible boolean @Flag to show or hide the item ++---@field visible? boolean @Flag to show or hide the item + ---The type of separator rendered to the right of the item if another item + ---follows it. + ---@field separator? core.statusview.item.separator +@@ -190,6 +190,9 @@ function StatusView:new() + self:register_command_items() + end + ++local clicks = -1 ++local gx, gy, dx, dy, gc = 0, 0, 2, -2, { table.unpack(style.text) } ++ + ---The predefined status bar items displayed when a document view is active. + function StatusView:register_docview_items() + if self:get_item("doc:file") then return end +@@ -291,6 +294,28 @@ function StatusView:register_docview_items() + separator = self.separator2 + }) + ++ self:add_item({ ++ predicate = predicate_docview, ++ name = "doc:stats", ++ alignment = StatusView.Item.RIGHT, ++ get_item = function() ++ return config.stonks == nil and {} or { ++ style.text, ++ type(config.stonks) == "table" and config.stonks.font or style.icon_font, ++ type(config.stonks) == "table" and config.stonks.icon or ( config.stonks and "g" or "h" ), ++ } ++ end, ++ separator = self.separator2, ++ command = function(button, x, y) ++ if button == "left" then ++ clicks = clicks + 1 ++ elseif button == "right" then ++ clicks = -1 ++ end ++ gx, gy = x, y ++ end ++ }) ++ + self:add_item({ + predicate = predicate_docview, + name = "doc:lines", +@@ -298,9 +323,6 @@ function StatusView:register_docview_items() + get_item = function() + local dv = core.active_view + return { +- style.text, +- style.icon_font, "g", +- style.font, style.dim, self.separator2, + style.text, #dv.doc.lines, " lines", + } + end, +@@ -1200,6 +1222,25 @@ function StatusView:draw() + end + end + end ++ ++ if clicks > 5 then ++ if config.stonks == nil then clicks = -1 end ++ core.root_view:defer_draw(function() ++ local font = type(config.stonks) == "table" and config.stonks.font or style.icon_font ++ local icon = type(config.stonks) == "table" and config.stonks.icon or ( config.stonks and "g" or "h" ) ++ local xadv = renderer.draw_text(font, icon, gx, gy, gc) ++ local x2, y2 = core.root_view.size.x - (xadv - gx), core.root_view.size.y - font:get_height() ++ gx, gy = common.clamp(gx + dx, 0, x2), common.clamp(gy + dy, 0, y2) ++ local odx, ody = dx, dy ++ if gx <= 0 then dx = math.abs(dx) elseif gx >= x2 then dx = -math.abs(dx) end ++ if gy <= 0 then dy = math.abs(dy) elseif gy >= y2 then dy = -math.abs(dy) end ++ if odx ~= dx or ody ~= dy then ++ local major = math.random(1, 3) ++ for i = 1, 3 do gc[i] = major == i and math.random(200, 255) or math.random(0, 100) end ++ end ++ core.redraw = true ++ end) ++ end + end + + return StatusView +diff --git a/data/fonts/icons.ttf b/data/fonts/icons.ttf +index 5fd6d9e9..33d62b11 100644 +Binary files a/data/fonts/icons.ttf and b/data/fonts/icons.ttf differ +diff --git a/scripts/fontello-config.json b/scripts/fontello-config.json +index 76349182..e68f4cc3 100644 +--- a/scripts/fontello-config.json ++++ b/scripts/fontello-config.json +@@ -195,6 +195,20 @@ + "search": [ + "lite-xl4" + ] ++ }, ++ { ++ "uid": "b1c9ba6ba7db344177bf4906b41303ee", ++ "css": "chart-line-down", ++ "code": 104, ++ "src": "custom_icons", ++ "selected": true, ++ "svg": { ++ "path": "M1071.4 728.2V485.5Q1071.4 473.8 1060.5 469 1049.7 464.3 1040.7 473.2L973.2 540.7 620 187.5Q614.4 181.9 607.1 181.9 599.9 181.9 594.3 187.5L464.3 317.5 232.1 85.4 125 192.5 451.5 519Q457 524.6 464.3 524.6 471.5 524.6 477.1 519L607.1 389 866.1 647.9 798.5 715.4Q789.6 724.3 794.4 735.2 799.1 746.1 810.8 746.1H1053.6Q1061.4 746.1 1066.4 741.1 1071.4 736 1071.4 728.2ZM1142.9 799.7V871.1H0V14H71.4V799.7Z", ++ "width": 1154 ++ }, ++ "search": [ ++ "_481_fontawesome" ++ ] + } + ] + } +\ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1617/tests/test.sh b/tasks/lite-xl__lite-xl-1617/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a619b77053cf1abce0c52af3b9b67e5d219ba3dc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/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 b4e95b865c9a18ba4cb193ff7d2f3657d8995cd8 > "$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/lite-xl__lite-xl-1617/tests/verifier.py b/tasks/lite-xl__lite-xl-1617/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1617/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/lite-xl__lite-xl-1634/environment/Dockerfile b/tasks/lite-xl__lite-xl-1634/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..905fe0e192abe82a101bddd6eb262535c35275f8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d925da47fa80c627933a9f4fc535d61872978c52 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d925da47fa80c627933a9f4fc535d61872978c52 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d925da47fa80c627933a9f4fc535d61872978c52 \ + && 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/lite-xl__lite-xl-1634/instruction.md b/tasks/lite-xl__lite-xl-1634/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6331b7fa040cbcf10319ef6ab71b1ef28f418e4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Add support for relative `require`s + +## Description + +This keeps a stack of `require` "paths", and uses the topmost one when resolving relative requires to calculate the "absolute path". + +From inside `"path_1.path_2"`: +* Calling `require ".b"` will require `"path_1.path_2.b"`. +* Calling `require "..b"` will require `"path_1.b"`. + +This has a few caveats: +1. The relative `require` must be called "inside" the parent `require`; this means that `require`s called "later" will have the wrong path. + So: + ```lua + require ".b" -- OK + + local function blabla() + require ".c" -- Not OK + end + ``` +3. The path traversal is limited by the parent path; so if the parent path is `core.plugins` and the relative path is `.......plugin_name`, the resulting path is `plugin_name`. + +(2) might be considered a feature, to limit the require range and not go outside our managed directories (even thought a plugin could still add its own custom search path). + +To provide a workaround for (1), I added `get_current_require_path` which will return the topmost path in the stack. This still needs to be called inside the parent `require`, but its result can be used later. +So: +```lua +require ".b" -- OK +local path = get_current_require_path() -- OK + +local function blabla() + require ".c" -- Not OK + require(path .. ".c") -- OK + get_current_require_path() -- Not OK +end +``` + + +Suggestions for a better name for `get_current_require_path` are welcome. +Should we also add a `level` parameter to `get_current_require_path`, so that path traversal doesn't need to be implemented by each plugin that uses it? + +EDIT: If we want to avoid using `pcall`, we could use a to-be-closed object that does the stack popping. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d925da47fa80`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1634/solution/patch.diff b/tasks/lite-xl__lite-xl-1634/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8ebc61650dcfa4277d5e002cf0028e486e6daa65 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/solution/patch.diff @@ -0,0 +1,89 @@ +diff --git a/data/core/doc/init.lua b/data/core/doc/init.lua +index ec9d46bc..3999937f 100644 +--- a/data/core/doc/init.lua ++++ b/data/core/doc/init.lua +@@ -1,6 +1,6 @@ + local Object = require "core.object" +-local Highlighter = require "core.doc.highlighter" +-local translate = require "core.doc.translate" ++local Highlighter = require ".highlighter" ++local translate = require ".translate" + local core = require "core" + local syntax = require "core.syntax" + local config = require "core.config" +diff --git a/data/core/start.lua b/data/core/start.lua +index bfa74810..439f1cbc 100644 +--- a/data/core/start.lua ++++ b/data/core/start.lua +@@ -46,6 +46,71 @@ end } + table.pack = table.pack or pack or function(...) return {...} end + table.unpack = table.unpack or unpack + ++local lua_require = require ++local require_stack = { "" } ++---Loads the given module, returns any value returned by the searcher (`true` when `nil`). ++---Besides that value, also returns as a second result the loader data returned by the searcher, ++---which indicates how `require` found the module. ++---(For instance, if the module came from a file, this loader data is the file path.) ++--- ++---This is a variant that also supports relative imports. ++--- ++---For example `require ".b"` will require `b` in the same path of the current ++---file. ++---This also supports multiple levels traversal. For example `require "...b"` ++---will require `b` from two levels above the current one. ++---This method has a few caveats: it uses the last `require` call to get the ++---current "path", so this only works if the relative `require` is called inside ++---its parent `require`. ++---Calling a relative `require` in a function called outside the parent ++---`require`, will result in the wrong "path" being used. ++--- ++---It's possible to save the current "path" with `get_current_require_path` ++---called inside the parent `require`, and use its return value to populate ++---future requires. ++---@see get_current_require_path ++---@param modname string ++---@return unknown ++---@return unknown loaderdata ++function require(modname, ...) ++ if modname then ++ local level, rel_path = string.match(modname, "^(%.*)(.*)") ++ level = #(level or "") ++ if level > 0 then ++ if #require_stack == 0 then ++ return error("Require stack underflowed.") ++ else ++ local base_path = require_stack[#require_stack] ++ while level > 1 do ++ base_path = string.match(base_path, "^(.*)%.") or "" ++ level = level - 1 ++ end ++ modname = base_path ++ if #base_path > 0 then ++ modname = modname .. "." ++ end ++ modname = modname .. rel_path ++ end ++ end ++ end ++ ++ table.insert(require_stack, modname) ++ local ok, result, loaderdata = pcall(lua_require, modname, ...) ++ table.remove(require_stack) ++ ++ if not ok then ++ return error(result) ++ end ++ return result, loaderdata ++end ++ ++---Returns the current `require` path. ++---@see require for details and caveats ++---@return string ++function get_current_require_path() ++ return require_stack[#require_stack] ++end ++ + bit32 = bit32 or require "core.bit" + + require "core.utf8string" diff --git a/tasks/lite-xl__lite-xl-1634/solution/solve.sh b/tasks/lite-xl__lite-xl-1634/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/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/lite-xl__lite-xl-1634/task.toml b/tasks/lite-xl__lite-xl-1634/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5505712544f3d4ff2dbde45dfa7bd22bbaff16c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1634" +description = "Add support for relative `require`s" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d925da47fa80c627933a9f4fc535d61872978c52" +reference = "https://github.com/lite-xl/lite-xl/pull/1634" +source_access = "auto" +built_at = "2026-11-16T16:09:56.336181+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:99d973c87b10cef146baab20da302a83d8c4d54ceb0b5e0baa092fec46cd62eb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T16:31:45Z" +diff_format = "unified" +context_files = [ + "data/core/doc/init.lua", + "data/core/start.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 69 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.290892+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:14e96e87176fd7af1e139f34f86570d39e40300d889ecad631eec5415657c3bd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1634/tests/capture.py b/tasks/lite-xl__lite-xl-1634/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/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/lite-xl__lite-xl-1634/tests/instruction.md b/tasks/lite-xl__lite-xl-1634/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6331b7fa040cbcf10319ef6ab71b1ef28f418e4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Add support for relative `require`s + +## Description + +This keeps a stack of `require` "paths", and uses the topmost one when resolving relative requires to calculate the "absolute path". + +From inside `"path_1.path_2"`: +* Calling `require ".b"` will require `"path_1.path_2.b"`. +* Calling `require "..b"` will require `"path_1.b"`. + +This has a few caveats: +1. The relative `require` must be called "inside" the parent `require`; this means that `require`s called "later" will have the wrong path. + So: + ```lua + require ".b" -- OK + + local function blabla() + require ".c" -- Not OK + end + ``` +3. The path traversal is limited by the parent path; so if the parent path is `core.plugins` and the relative path is `.......plugin_name`, the resulting path is `plugin_name`. + +(2) might be considered a feature, to limit the require range and not go outside our managed directories (even thought a plugin could still add its own custom search path). + +To provide a workaround for (1), I added `get_current_require_path` which will return the topmost path in the stack. This still needs to be called inside the parent `require`, but its result can be used later. +So: +```lua +require ".b" -- OK +local path = get_current_require_path() -- OK + +local function blabla() + require ".c" -- Not OK + require(path .. ".c") -- OK + get_current_require_path() -- Not OK +end +``` + + +Suggestions for a better name for `get_current_require_path` are welcome. +Should we also add a `level` parameter to `get_current_require_path`, so that path traversal doesn't need to be implemented by each plugin that uses it? + +EDIT: If we want to avoid using `pcall`, we could use a to-be-closed object that does the stack popping. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d925da47fa80`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1634/tests/oracle.patch b/tasks/lite-xl__lite-xl-1634/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8ebc61650dcfa4277d5e002cf0028e486e6daa65 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/tests/oracle.patch @@ -0,0 +1,89 @@ +diff --git a/data/core/doc/init.lua b/data/core/doc/init.lua +index ec9d46bc..3999937f 100644 +--- a/data/core/doc/init.lua ++++ b/data/core/doc/init.lua +@@ -1,6 +1,6 @@ + local Object = require "core.object" +-local Highlighter = require "core.doc.highlighter" +-local translate = require "core.doc.translate" ++local Highlighter = require ".highlighter" ++local translate = require ".translate" + local core = require "core" + local syntax = require "core.syntax" + local config = require "core.config" +diff --git a/data/core/start.lua b/data/core/start.lua +index bfa74810..439f1cbc 100644 +--- a/data/core/start.lua ++++ b/data/core/start.lua +@@ -46,6 +46,71 @@ end } + table.pack = table.pack or pack or function(...) return {...} end + table.unpack = table.unpack or unpack + ++local lua_require = require ++local require_stack = { "" } ++---Loads the given module, returns any value returned by the searcher (`true` when `nil`). ++---Besides that value, also returns as a second result the loader data returned by the searcher, ++---which indicates how `require` found the module. ++---(For instance, if the module came from a file, this loader data is the file path.) ++--- ++---This is a variant that also supports relative imports. ++--- ++---For example `require ".b"` will require `b` in the same path of the current ++---file. ++---This also supports multiple levels traversal. For example `require "...b"` ++---will require `b` from two levels above the current one. ++---This method has a few caveats: it uses the last `require` call to get the ++---current "path", so this only works if the relative `require` is called inside ++---its parent `require`. ++---Calling a relative `require` in a function called outside the parent ++---`require`, will result in the wrong "path" being used. ++--- ++---It's possible to save the current "path" with `get_current_require_path` ++---called inside the parent `require`, and use its return value to populate ++---future requires. ++---@see get_current_require_path ++---@param modname string ++---@return unknown ++---@return unknown loaderdata ++function require(modname, ...) ++ if modname then ++ local level, rel_path = string.match(modname, "^(%.*)(.*)") ++ level = #(level or "") ++ if level > 0 then ++ if #require_stack == 0 then ++ return error("Require stack underflowed.") ++ else ++ local base_path = require_stack[#require_stack] ++ while level > 1 do ++ base_path = string.match(base_path, "^(.*)%.") or "" ++ level = level - 1 ++ end ++ modname = base_path ++ if #base_path > 0 then ++ modname = modname .. "." ++ end ++ modname = modname .. rel_path ++ end ++ end ++ end ++ ++ table.insert(require_stack, modname) ++ local ok, result, loaderdata = pcall(lua_require, modname, ...) ++ table.remove(require_stack) ++ ++ if not ok then ++ return error(result) ++ end ++ return result, loaderdata ++end ++ ++---Returns the current `require` path. ++---@see require for details and caveats ++---@return string ++function get_current_require_path() ++ return require_stack[#require_stack] ++end ++ + bit32 = bit32 or require "core.bit" + + require "core.utf8string" diff --git a/tasks/lite-xl__lite-xl-1634/tests/test.sh b/tasks/lite-xl__lite-xl-1634/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..08ddd06737eaa93234190114a322cbfca9f488e7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/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 d925da47fa80c627933a9f4fc535d61872978c52 > "$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/lite-xl__lite-xl-1634/tests/verifier.py b/tasks/lite-xl__lite-xl-1634/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1634/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/lite-xl__lite-xl-1647/environment/Dockerfile b/tasks/lite-xl__lite-xl-1647/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e312680c8fc448f0179d843c12862e7977fd678 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e \ + && 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/lite-xl__lite-xl-1647/instruction.md b/tasks/lite-xl__lite-xl-1647/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f07fa8c6a2f7ca16b0707b4d6cca891a1adf8927 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix: deadlock if error handler jumps somewhere else + +## Description + +This PR complements #1599. + +The root issue is that the check callback runs within a critical section. It is very possible to longjmp out of it via errors. This PR allows errors to be caught by an error handler. This prevents an error from escaping the critical section and cause a deadlock. + +Likely fixes (maybe too?). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c5475d1ef`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1647/solution/patch.diff b/tasks/lite-xl__lite-xl-1647/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3e36c0840b7c963a8c8069346aff04cf61886497 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/solution/patch.diff @@ -0,0 +1,94 @@ +diff --git a/data/core/dirwatch.lua b/data/core/dirwatch.lua +index e3b6d61c..3b62fa24 100644 +--- a/data/core/dirwatch.lua ++++ b/data/core/dirwatch.lua +@@ -91,6 +91,7 @@ end + -- designed to be run inside a coroutine. + function dirwatch:check(change_callback, scan_time, wait_time) + local had_change = false ++ local last_error + self.monitor:check(function(id) + had_change = true + if self.monitor:mode() == "single" then +@@ -102,7 +103,10 @@ function dirwatch:check(change_callback, scan_time, wait_time) + elseif self.reverse_watched[id] then + change_callback(self.reverse_watched[id]) + end ++ end, function(err) ++ last_error = err + end) ++ if last_error ~= nil then error(last_error) end + local start_time = system.get_time() + for directory, old_modified in pairs(self.scanned) do + if old_modified then +diff --git a/docs/api/dirmonitor.lua b/docs/api/dirmonitor.lua +index 439e0ec4..a12b61f1 100644 +--- a/docs/api/dirmonitor.lua ++++ b/docs/api/dirmonitor.lua +@@ -45,10 +45,14 @@ function dirmonitor:unwatch(fd_or_path) end + ---edited, removed or added. A file descriptor will be passed to the + ---callback in "multiple" mode or a path in "single" mode. + --- ++---If an error occurred during the callback execution, the error callback will be called with the error object. ++---This callback should not manipulate coroutines to avoid deadlocks. ++--- + ---@param callback dirmonitor.callback ++---@param error_callback fun(error: any): nil + --- + ---@return boolean? changes True when changes were detected. +-function dirmonitor:check(callback) end ++function dirmonitor:check(callback, error_callback) end + + --- + ---Get the working mode for the current file system monitoring backend. +diff --git a/src/api/dirmonitor.c b/src/api/dirmonitor.c +index 1bccfd13..320235a0 100644 +--- a/src/api/dirmonitor.c ++++ b/src/api/dirmonitor.c +@@ -1,4 +1,5 @@ + #include "api.h" ++#include "lua.h" + #include + #include + #include +@@ -25,13 +26,16 @@ int get_mode_dirmonitor(); + + + static int f_check_dir_callback(int watch_id, const char* path, void* L) { +- lua_pushvalue(L, -1); ++ // using absolute indices from f_dirmonitor_check (2: callback, 3: error_callback) ++ lua_pushvalue(L, 2); + if (path) + lua_pushlstring(L, path, watch_id); + else + lua_pushnumber(L, watch_id); +- lua_call(L, 1, 1); +- int result = lua_toboolean(L, -1); ++ ++ int result = 0; ++ if (lua_pcall(L, 1, 1, 3) == LUA_OK) ++ result = lua_toboolean(L, -1); + lua_pop(L, 1); + return !result; + } +@@ -95,8 +99,20 @@ static int f_dirmonitor_unwatch(lua_State *L) { + } + + ++static int f_noop(lua_State *L) { return 0; } ++ ++ + static int f_dirmonitor_check(lua_State* L) { + struct dirmonitor* monitor = luaL_checkudata(L, 1, API_TYPE_DIRMONITOR); ++ luaL_checktype(L, 2, LUA_TFUNCTION); ++ if (!lua_isnoneornil(L, 3)) { ++ luaL_checktype(L, 3, LUA_TFUNCTION); ++ } else { ++ lua_settop(L, 2); ++ lua_pushcfunction(L, f_noop); ++ } ++ lua_settop(L, 3); ++ + SDL_LockMutex(monitor->mutex); + if (monitor->length < 0) + lua_pushnil(L); diff --git a/tasks/lite-xl__lite-xl-1647/solution/solve.sh b/tasks/lite-xl__lite-xl-1647/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/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/lite-xl__lite-xl-1647/task.toml b/tasks/lite-xl__lite-xl-1647/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..685101562d27fbfc9f0b27c3ec5cc78f81cf9cd8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1647" +description = "fix: deadlock if error handler jumps somewhere else" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e" +reference = "https://github.com/lite-xl/lite-xl/pull/1647" +source_access = "auto" +built_at = "2026-11-16T16:09:56.222126+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:efbffb8444f59dcc6c48aec39b697b8a1592d78003f42b3fb1bd8771d6535d67" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-10-21T17:17:49Z" +diff_format = "unified" +context_files = [ + "data/core/dirwatch.lua", + "docs/api/dirmonitor.lua", + "src/api/dirmonitor.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 32 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.291354+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b024b1b6f215005c574a1d1448b8dd93aba70e068aa244f3466a6c03f2b7873e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1647/tests/capture.py b/tasks/lite-xl__lite-xl-1647/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/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/lite-xl__lite-xl-1647/tests/instruction.md b/tasks/lite-xl__lite-xl-1647/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f07fa8c6a2f7ca16b0707b4d6cca891a1adf8927 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix: deadlock if error handler jumps somewhere else + +## Description + +This PR complements #1599. + +The root issue is that the check callback runs within a critical section. It is very possible to longjmp out of it via errors. This PR allows errors to be caught by an error handler. This prevents an error from escaping the critical section and cause a deadlock. + +Likely fixes (maybe too?). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c5475d1ef`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1647/tests/oracle.patch b/tasks/lite-xl__lite-xl-1647/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3e36c0840b7c963a8c8069346aff04cf61886497 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/tests/oracle.patch @@ -0,0 +1,94 @@ +diff --git a/data/core/dirwatch.lua b/data/core/dirwatch.lua +index e3b6d61c..3b62fa24 100644 +--- a/data/core/dirwatch.lua ++++ b/data/core/dirwatch.lua +@@ -91,6 +91,7 @@ end + -- designed to be run inside a coroutine. + function dirwatch:check(change_callback, scan_time, wait_time) + local had_change = false ++ local last_error + self.monitor:check(function(id) + had_change = true + if self.monitor:mode() == "single" then +@@ -102,7 +103,10 @@ function dirwatch:check(change_callback, scan_time, wait_time) + elseif self.reverse_watched[id] then + change_callback(self.reverse_watched[id]) + end ++ end, function(err) ++ last_error = err + end) ++ if last_error ~= nil then error(last_error) end + local start_time = system.get_time() + for directory, old_modified in pairs(self.scanned) do + if old_modified then +diff --git a/docs/api/dirmonitor.lua b/docs/api/dirmonitor.lua +index 439e0ec4..a12b61f1 100644 +--- a/docs/api/dirmonitor.lua ++++ b/docs/api/dirmonitor.lua +@@ -45,10 +45,14 @@ function dirmonitor:unwatch(fd_or_path) end + ---edited, removed or added. A file descriptor will be passed to the + ---callback in "multiple" mode or a path in "single" mode. + --- ++---If an error occurred during the callback execution, the error callback will be called with the error object. ++---This callback should not manipulate coroutines to avoid deadlocks. ++--- + ---@param callback dirmonitor.callback ++---@param error_callback fun(error: any): nil + --- + ---@return boolean? changes True when changes were detected. +-function dirmonitor:check(callback) end ++function dirmonitor:check(callback, error_callback) end + + --- + ---Get the working mode for the current file system monitoring backend. +diff --git a/src/api/dirmonitor.c b/src/api/dirmonitor.c +index 1bccfd13..320235a0 100644 +--- a/src/api/dirmonitor.c ++++ b/src/api/dirmonitor.c +@@ -1,4 +1,5 @@ + #include "api.h" ++#include "lua.h" + #include + #include + #include +@@ -25,13 +26,16 @@ int get_mode_dirmonitor(); + + + static int f_check_dir_callback(int watch_id, const char* path, void* L) { +- lua_pushvalue(L, -1); ++ // using absolute indices from f_dirmonitor_check (2: callback, 3: error_callback) ++ lua_pushvalue(L, 2); + if (path) + lua_pushlstring(L, path, watch_id); + else + lua_pushnumber(L, watch_id); +- lua_call(L, 1, 1); +- int result = lua_toboolean(L, -1); ++ ++ int result = 0; ++ if (lua_pcall(L, 1, 1, 3) == LUA_OK) ++ result = lua_toboolean(L, -1); + lua_pop(L, 1); + return !result; + } +@@ -95,8 +99,20 @@ static int f_dirmonitor_unwatch(lua_State *L) { + } + + ++static int f_noop(lua_State *L) { return 0; } ++ ++ + static int f_dirmonitor_check(lua_State* L) { + struct dirmonitor* monitor = luaL_checkudata(L, 1, API_TYPE_DIRMONITOR); ++ luaL_checktype(L, 2, LUA_TFUNCTION); ++ if (!lua_isnoneornil(L, 3)) { ++ luaL_checktype(L, 3, LUA_TFUNCTION); ++ } else { ++ lua_settop(L, 2); ++ lua_pushcfunction(L, f_noop); ++ } ++ lua_settop(L, 3); ++ + SDL_LockMutex(monitor->mutex); + if (monitor->length < 0) + lua_pushnil(L); diff --git a/tasks/lite-xl__lite-xl-1647/tests/test.sh b/tasks/lite-xl__lite-xl-1647/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..42ae5bc991e784cd03107ae409d830b14f697483 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/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 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e > "$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/lite-xl__lite-xl-1647/tests/verifier.py b/tasks/lite-xl__lite-xl-1647/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1647/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/lite-xl__lite-xl-1648/environment/Dockerfile b/tasks/lite-xl__lite-xl-1648/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e312680c8fc448f0179d843c12862e7977fd678 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e \ + && 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/lite-xl__lite-xl-1648/instruction.md b/tasks/lite-xl__lite-xl-1648/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9548055bc2565e82b7d0ccc64b20d7ae9362c8ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** ci: fix diff files having "wrong" path separator + +## Description + +Apparently a recent update in the runner image uses `patch` from Strawberry Perl, and this version of `patch` does not support backslashes as path separators. This is stupid and should not happen. + +EDIT: Turns out the `patch` tool straight up don't work. We just use Git bash's `patch` instead. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c5475d1ef`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1648/solution/patch.diff b/tasks/lite-xl__lite-xl-1648/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9cc63ee62e78eaf27f96de0169fa5f6630cccfa0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/solution/patch.diff @@ -0,0 +1,88 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 398aae67..461a9d16 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -201,12 +201,13 @@ jobs: + "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV +- - name: Configure ++ - name: Download and patch subprojects ++ shell: bash + run: | +- # Download the subprojects first so we can patch it before configuring. +- # This avoids reconfiguring the subprojects when compiling. + meson subprojects download +- Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward ++ cat resources/windows/001-lua-unicode.diff | patch -Np1 -d "$LUA_SUBPROJECT_PATH" ++ - name: Configure ++ run: | + meson setup --wrap-mode=forcefallback build + - name: Build + run: | +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +index 31fec364..e6a2ae44 100644 +--- a/resources/windows/001-lua-unicode.diff ++++ b/resources/windows/001-lua-unicode.diff +@@ -1,6 +1,6 @@ +-diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build +---- lua-5.4.4\meson.build Wed Feb 22 18:16:56 2023 +-+++ lua-5.4.4-patched\meson.build Wed Feb 22 04:10:01 2023 ++diff -ruN lua-5.4.4/meson.build lua-5.4.4-patched/meson.build ++--- lua-5.4.4/meson.build Wed Feb 22 18:16:56 2023 +++++ lua-5.4.4-patched/meson.build Wed Feb 22 04:10:01 2023 + @@ -85,6 +85,7 @@ + 'src/lutf8lib.c', + 'src/lvm.c', +@@ -9,9 +9,9 @@ diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h +---- lua-5.4.4\src\luaconf.h Thu Jan 13 19:24:43 2022 +-+++ lua-5.4.4-patched\src\luaconf.h Wed Feb 22 04:10:02 2023 ++diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-patched/src/luaconf.h ++--- lua-5.4.4/src/luaconf.h Thu Jan 13 19:24:43 2022 +++++ lua-5.4.4-patched/src/luaconf.h Wed Feb 22 04:10:02 2023 + @@ -782,5 +782,15 @@ + + +@@ -28,9 +28,9 @@ diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h + + + #endif + +-diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile +---- lua-5.4.4\src\Makefile Thu Jul 15 22:01:52 2021 +-+++ lua-5.4.4-patched\src\Makefile Wed Feb 22 04:10:02 2023 ++diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-patched/src/Makefile ++--- lua-5.4.4/src/Makefile Thu Jul 15 22:01:52 2021 +++++ lua-5.4.4-patched/src/Makefile Wed Feb 22 04:10:02 2023 + @@ -33,7 +33,7 @@ + PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris + +@@ -40,9 +40,9 @@ diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile + LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o + BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) + +-diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c +---- lua-5.4.4\src\utf8_wrappers.c Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.4-patched\src\utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-patched/src/utf8_wrappers.c ++--- lua-5.4.4/src/utf8_wrappers.c Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched/src/utf8_wrappers.c Wed Feb 22 18:13:45 2023 + @@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -173,9 +173,9 @@ diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c + + return env_value; + +} + +#endif +-diff -ruN lua-5.4.4\src\utf8_wrappers.h lua-5.4.4-patched\src\utf8_wrappers.h +---- lua-5.4.4\src\utf8_wrappers.h Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.4-patched\src\utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-patched/src/utf8_wrappers.h ++--- lua-5.4.4/src/utf8_wrappers.h Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched/src/utf8_wrappers.h Wed Feb 22 18:09:48 2023 + @@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. diff --git a/tasks/lite-xl__lite-xl-1648/solution/solve.sh b/tasks/lite-xl__lite-xl-1648/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/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/lite-xl__lite-xl-1648/task.toml b/tasks/lite-xl__lite-xl-1648/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..21790feef3f82ea4a0793d19f8b1f32187b9ee8f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1648" +description = "ci: fix diff files having \"wrong\" path separator" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e" +reference = "https://github.com/lite-xl/lite-xl/pull/1648" +source_access = "auto" +built_at = "2026-11-16T16:09:56.227301+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:77a1b5eb199833c152b6684c9f05e83118f974f6b1cb2099dfa77991cba63f01" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-10-20T01:09:51Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + "resources/windows/001-lua-unicode.diff", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 39 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.291800+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b024b1b6f215005c574a1d1448b8dd93aba70e068aa244f3466a6c03f2b7873e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1648/tests/capture.py b/tasks/lite-xl__lite-xl-1648/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/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/lite-xl__lite-xl-1648/tests/instruction.md b/tasks/lite-xl__lite-xl-1648/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9548055bc2565e82b7d0ccc64b20d7ae9362c8ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** ci: fix diff files having "wrong" path separator + +## Description + +Apparently a recent update in the runner image uses `patch` from Strawberry Perl, and this version of `patch` does not support backslashes as path separators. This is stupid and should not happen. + +EDIT: Turns out the `patch` tool straight up don't work. We just use Git bash's `patch` instead. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9c6c5475d1ef`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1648/tests/oracle.patch b/tasks/lite-xl__lite-xl-1648/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9cc63ee62e78eaf27f96de0169fa5f6630cccfa0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/tests/oracle.patch @@ -0,0 +1,88 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 398aae67..461a9d16 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -201,12 +201,13 @@ jobs: + "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/lua-5.4.4" >> $env:GITHUB_ENV +- - name: Configure ++ - name: Download and patch subprojects ++ shell: bash + run: | +- # Download the subprojects first so we can patch it before configuring. +- # This avoids reconfiguring the subprojects when compiling. + meson subprojects download +- Get-Content -Path resources/windows/001-lua-unicode.diff -Raw | patch -d $env:LUA_SUBPROJECT_PATH -p1 --forward ++ cat resources/windows/001-lua-unicode.diff | patch -Np1 -d "$LUA_SUBPROJECT_PATH" ++ - name: Configure ++ run: | + meson setup --wrap-mode=forcefallback build + - name: Build + run: | +diff --git a/resources/windows/001-lua-unicode.diff b/resources/windows/001-lua-unicode.diff +index 31fec364..e6a2ae44 100644 +--- a/resources/windows/001-lua-unicode.diff ++++ b/resources/windows/001-lua-unicode.diff +@@ -1,6 +1,6 @@ +-diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build +---- lua-5.4.4\meson.build Wed Feb 22 18:16:56 2023 +-+++ lua-5.4.4-patched\meson.build Wed Feb 22 04:10:01 2023 ++diff -ruN lua-5.4.4/meson.build lua-5.4.4-patched/meson.build ++--- lua-5.4.4/meson.build Wed Feb 22 18:16:56 2023 +++++ lua-5.4.4-patched/meson.build Wed Feb 22 04:10:01 2023 + @@ -85,6 +85,7 @@ + 'src/lutf8lib.c', + 'src/lvm.c', +@@ -9,9 +9,9 @@ diff -ruN lua-5.4.4\meson.build lua-5.4.4-patched\meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h +---- lua-5.4.4\src\luaconf.h Thu Jan 13 19:24:43 2022 +-+++ lua-5.4.4-patched\src\luaconf.h Wed Feb 22 04:10:02 2023 ++diff -ruN lua-5.4.4/src/luaconf.h lua-5.4.4-patched/src/luaconf.h ++--- lua-5.4.4/src/luaconf.h Thu Jan 13 19:24:43 2022 +++++ lua-5.4.4-patched/src/luaconf.h Wed Feb 22 04:10:02 2023 + @@ -782,5 +782,15 @@ + + +@@ -28,9 +28,9 @@ diff -ruN lua-5.4.4\src\luaconf.h lua-5.4.4-patched\src\luaconf.h + + + #endif + +-diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile +---- lua-5.4.4\src\Makefile Thu Jul 15 22:01:52 2021 +-+++ lua-5.4.4-patched\src\Makefile Wed Feb 22 04:10:02 2023 ++diff -ruN lua-5.4.4/src/Makefile lua-5.4.4-patched/src/Makefile ++--- lua-5.4.4/src/Makefile Thu Jul 15 22:01:52 2021 +++++ lua-5.4.4-patched/src/Makefile Wed Feb 22 04:10:02 2023 + @@ -33,7 +33,7 @@ + PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris + +@@ -40,9 +40,9 @@ diff -ruN lua-5.4.4\src\Makefile lua-5.4.4-patched\src\Makefile + LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o + BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) + +-diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c +---- lua-5.4.4\src\utf8_wrappers.c Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.4-patched\src\utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++diff -ruN lua-5.4.4/src/utf8_wrappers.c lua-5.4.4-patched/src/utf8_wrappers.c ++--- lua-5.4.4/src/utf8_wrappers.c Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched/src/utf8_wrappers.c Wed Feb 22 18:13:45 2023 + @@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -173,9 +173,9 @@ diff -ruN lua-5.4.4\src\utf8_wrappers.c lua-5.4.4-patched\src\utf8_wrappers.c + + return env_value; + +} + +#endif +-diff -ruN lua-5.4.4\src\utf8_wrappers.h lua-5.4.4-patched\src\utf8_wrappers.h +---- lua-5.4.4\src\utf8_wrappers.h Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.4-patched\src\utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++diff -ruN lua-5.4.4/src/utf8_wrappers.h lua-5.4.4-patched/src/utf8_wrappers.h ++--- lua-5.4.4/src/utf8_wrappers.h Thu Jan 01 08:00:00 1970 +++++ lua-5.4.4-patched/src/utf8_wrappers.h Wed Feb 22 18:09:48 2023 + @@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. diff --git a/tasks/lite-xl__lite-xl-1648/tests/test.sh b/tasks/lite-xl__lite-xl-1648/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..42ae5bc991e784cd03107ae409d830b14f697483 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/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 9c6c5475d1efdbd14d65a7e34d5073e5b60ab85e > "$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/lite-xl__lite-xl-1648/tests/verifier.py b/tasks/lite-xl__lite-xl-1648/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1648/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/lite-xl__lite-xl-1653/environment/Dockerfile b/tasks/lite-xl__lite-xl-1653/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1653/instruction.md b/tasks/lite-xl__lite-xl-1653/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..066c8f30b2391a447d7329095bbe5386cce3910c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Allow writing to hidden files on Windows + +## Description + +. + +Sometimes Windows quirks are just beyond my understanding. + +# why + +You can't `fopen(path, "w")` if path is a hidden file. +Hidden files on Windows are actual file attributes and not dotfiles. + +This is likely because fopen() is implemented with `CreateFile()`, and `CreateFile()` requires specifying `FILE_ATTRIBUTE_HIDDEN` to open hidden files. There's an obvious problem with that - if the files don't exist, a hidden file will be created, which is certainly what people don't want. + +# Fix +To work around not being able to open hidden files on Windows, we open files with `r+b` (read write at beginning, no truncate). Why this works is beyond me, but afterwards we can call `ftruncate()` to truncate the file in order to emulate `w`. This file is now writable and hidden. Since opening file with `r+b` fails if file does not exist, we fall back to `wb`. + +# why not lua patch +obvious race condition with 2 `fopen()`, and I'd rather minimize that whenever necessary. + +# other possible ways +- Call CreateFile() directly: annoying to do, still needs to SetFileAttribute() so race condition still exists. +- Create temp file and move: Removes hidden attributes, but the best way. +- GetFileAttributes() + CreateFile(): now you have 2 race conditions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1653/solution/patch.diff b/tasks/lite-xl__lite-xl-1653/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..724ca45d7903f006b86ae92e992d8bc54d223b4c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/solution/patch.diff @@ -0,0 +1,98 @@ +diff --git a/data/core/doc/init.lua b/data/core/doc/init.lua +index 73342ca1..ec9d46bc 100644 +--- a/data/core/doc/init.lua ++++ b/data/core/doc/init.lua +@@ -103,7 +103,23 @@ function Doc:save(filename, abs_filename) + else + assert(self.filename or abs_filename, "calling save on unnamed doc without absolute path") + end +- local fp = assert(io.open(filename, "wb")) ++ ++ local fp ++ if PLATFORM == "Windows" then ++ -- On Windows, opening a hidden file with wb fails with a permission error. ++ -- To get around this, we must open the file as r+b and truncate. ++ -- Since r+b fails if file doesn't exist, fall back to wb. ++ fp = io.open(filename, "r+b") ++ if fp then ++ system.ftruncate(fp) ++ else ++ -- file probably doesn't exist, create one ++ fp = assert ( io.open(filename, "wb") ) ++ end ++ else ++ fp = assert ( io.open(filename, "wb") ) ++ end ++ + for _, line in ipairs(self.lines) do + if self.crlf then line = line:gsub("\n", "\r\n") end + fp:write(line) +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 55f79163..66af600f 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -190,6 +190,15 @@ function system.rmdir(path) end + ---@param path string + function system.chdir(path) end + ++--- ++---Truncates a file to a set length. ++--- ++---@param file file* A file handle returned by io.open(). ++---@param length integer? Number of bytes to truncate to. Defaults to 0. ++---@return boolean success True if the operation suceeded, false otherwise ++---@return string? message An error message if the operation failed. ++function system.ftruncate(file, length) end ++ + --- + ---Create a new directory, note that this function doesn't recursively + ---creates the directories on the given path. +diff --git a/src/api/system.c b/src/api/system.c +index 7baf3eab..ace17337 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -27,6 +27,9 @@ + #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) + #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) + #endif ++ ++ #define fileno _fileno ++ #define ftruncate _chsize + #else + + #include +@@ -847,6 +850,26 @@ static int f_get_fs_type(lua_State *L) { + } + + ++static int f_ftruncate(lua_State *L) { ++#if LUA_VERSION_NUM < 503 ++ // note: it is possible to support pre 5.3 and JIT ++ // since file handles are just FILE* wrapped in a userdata; ++ // but it is not standardized. YMMV. ++ #error luaL_Stream is not supported in this version of Lua. ++#endif ++ luaL_Stream *stream = luaL_checkudata(L, 1, LUA_FILEHANDLE); ++ lua_Integer len = luaL_optinteger(L, 2, 0); ++ if (ftruncate(fileno(stream->f), len) != 0) { ++ lua_pushboolean(L, 0); ++ lua_pushfstring(L, "ftruncate(): %s", strerror(errno)); ++ return 2; ++ } ++ ++ lua_pushboolean(L, 1); ++ return 1; ++} ++ ++ + static int f_mkdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + +@@ -1285,6 +1308,7 @@ static const luaL_Reg lib[] = { + { "get_fs_type", f_get_fs_type }, + { "text_input", f_text_input }, + { "setenv", f_setenv }, ++ { "ftruncate", f_ftruncate }, + { NULL, NULL } + }; + diff --git a/tasks/lite-xl__lite-xl-1653/solution/solve.sh b/tasks/lite-xl__lite-xl-1653/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/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/lite-xl__lite-xl-1653/task.toml b/tasks/lite-xl__lite-xl-1653/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f957b8b096ba1f33263cf4ef70be148852d87587 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1653" +description = "Allow writing to hidden files on Windows" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1653" +source_access = "auto" +built_at = "2026-11-16T16:09:56.337697+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9c5874c7949a697fc4db31b215e5da3731584500e5fe41be238f0be5a35e5b7f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T16:14:30Z" +diff_format = "unified" +context_files = [ + "data/core/doc/init.lua", + "docs/api/system.lua", + "src/api/system.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 51 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.292254+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1653/tests/capture.py b/tasks/lite-xl__lite-xl-1653/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/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/lite-xl__lite-xl-1653/tests/instruction.md b/tasks/lite-xl__lite-xl-1653/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..066c8f30b2391a447d7329095bbe5386cce3910c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** Allow writing to hidden files on Windows + +## Description + +. + +Sometimes Windows quirks are just beyond my understanding. + +# why + +You can't `fopen(path, "w")` if path is a hidden file. +Hidden files on Windows are actual file attributes and not dotfiles. + +This is likely because fopen() is implemented with `CreateFile()`, and `CreateFile()` requires specifying `FILE_ATTRIBUTE_HIDDEN` to open hidden files. There's an obvious problem with that - if the files don't exist, a hidden file will be created, which is certainly what people don't want. + +# Fix +To work around not being able to open hidden files on Windows, we open files with `r+b` (read write at beginning, no truncate). Why this works is beyond me, but afterwards we can call `ftruncate()` to truncate the file in order to emulate `w`. This file is now writable and hidden. Since opening file with `r+b` fails if file does not exist, we fall back to `wb`. + +# why not lua patch +obvious race condition with 2 `fopen()`, and I'd rather minimize that whenever necessary. + +# other possible ways +- Call CreateFile() directly: annoying to do, still needs to SetFileAttribute() so race condition still exists. +- Create temp file and move: Removes hidden attributes, but the best way. +- GetFileAttributes() + CreateFile(): now you have 2 race conditions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1653/tests/oracle.patch b/tasks/lite-xl__lite-xl-1653/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..724ca45d7903f006b86ae92e992d8bc54d223b4c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/tests/oracle.patch @@ -0,0 +1,98 @@ +diff --git a/data/core/doc/init.lua b/data/core/doc/init.lua +index 73342ca1..ec9d46bc 100644 +--- a/data/core/doc/init.lua ++++ b/data/core/doc/init.lua +@@ -103,7 +103,23 @@ function Doc:save(filename, abs_filename) + else + assert(self.filename or abs_filename, "calling save on unnamed doc without absolute path") + end +- local fp = assert(io.open(filename, "wb")) ++ ++ local fp ++ if PLATFORM == "Windows" then ++ -- On Windows, opening a hidden file with wb fails with a permission error. ++ -- To get around this, we must open the file as r+b and truncate. ++ -- Since r+b fails if file doesn't exist, fall back to wb. ++ fp = io.open(filename, "r+b") ++ if fp then ++ system.ftruncate(fp) ++ else ++ -- file probably doesn't exist, create one ++ fp = assert ( io.open(filename, "wb") ) ++ end ++ else ++ fp = assert ( io.open(filename, "wb") ) ++ end ++ + for _, line in ipairs(self.lines) do + if self.crlf then line = line:gsub("\n", "\r\n") end + fp:write(line) +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 55f79163..66af600f 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -190,6 +190,15 @@ function system.rmdir(path) end + ---@param path string + function system.chdir(path) end + ++--- ++---Truncates a file to a set length. ++--- ++---@param file file* A file handle returned by io.open(). ++---@param length integer? Number of bytes to truncate to. Defaults to 0. ++---@return boolean success True if the operation suceeded, false otherwise ++---@return string? message An error message if the operation failed. ++function system.ftruncate(file, length) end ++ + --- + ---Create a new directory, note that this function doesn't recursively + ---creates the directories on the given path. +diff --git a/src/api/system.c b/src/api/system.c +index 7baf3eab..ace17337 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -27,6 +27,9 @@ + #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) + #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) + #endif ++ ++ #define fileno _fileno ++ #define ftruncate _chsize + #else + + #include +@@ -847,6 +850,26 @@ static int f_get_fs_type(lua_State *L) { + } + + ++static int f_ftruncate(lua_State *L) { ++#if LUA_VERSION_NUM < 503 ++ // note: it is possible to support pre 5.3 and JIT ++ // since file handles are just FILE* wrapped in a userdata; ++ // but it is not standardized. YMMV. ++ #error luaL_Stream is not supported in this version of Lua. ++#endif ++ luaL_Stream *stream = luaL_checkudata(L, 1, LUA_FILEHANDLE); ++ lua_Integer len = luaL_optinteger(L, 2, 0); ++ if (ftruncate(fileno(stream->f), len) != 0) { ++ lua_pushboolean(L, 0); ++ lua_pushfstring(L, "ftruncate(): %s", strerror(errno)); ++ return 2; ++ } ++ ++ lua_pushboolean(L, 1); ++ return 1; ++} ++ ++ + static int f_mkdir(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + +@@ -1285,6 +1308,7 @@ static const luaL_Reg lib[] = { + { "get_fs_type", f_get_fs_type }, + { "text_input", f_text_input }, + { "setenv", f_setenv }, ++ { "ftruncate", f_ftruncate }, + { NULL, NULL } + }; + diff --git a/tasks/lite-xl__lite-xl-1653/tests/test.sh b/tasks/lite-xl__lite-xl-1653/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1653/tests/verifier.py b/tasks/lite-xl__lite-xl-1653/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1653/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/lite-xl__lite-xl-1656/environment/Dockerfile b/tasks/lite-xl__lite-xl-1656/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9d77266374eca7a902e6010cbbb781917a29de9d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e67ac2818ff316ececea6cb251ceb4b684aa297f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e67ac2818ff316ececea6cb251ceb4b684aa297f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e67ac2818ff316ececea6cb251ceb4b684aa297f \ + && 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/lite-xl__lite-xl-1656/instruction.md b/tasks/lite-xl__lite-xl-1656/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8bbe0c788c93f2d78c7ff9998b1a877e6d99a8c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** feat(package): ad-hoc sign macOS bundles + +## Description + +# Fuck you, Apple. + +This downgrades our application from "oh this app is damaged" to "oh this app is from an unknown developer". Why do we need to go through such hoops to do this? dunno. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e67ac2818ff3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1656/solution/patch.diff b/tasks/lite-xl__lite-xl-1656/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cac09baed4cdf85418516935bce4f40d20fd7805 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/README.md b/README.md +index 0bd00e48..05949e80 100644 +--- a/README.md ++++ b/README.md +@@ -95,7 +95,17 @@ Lite XL will load and store all your configurations and plugins in the folder. + We provide DMG files for macOS. Simply drag the program into your Applications folder. + + > **Important** +-> Since Lite XL is not signed, you **must** run this command before starting Lite XL: ++> Newer versions of Lite XL are signed with a self-signed certificate, ++> so you'll have to follow these steps when running Lite XL for the first time. ++> ++> 1. Find Lite XL in Finder (do not open it in Launchpad). ++> 2. Control-click Lite XL, then choose `Open` from the shortcut menu. ++> 3. Click `Open` in the popup menu. ++> ++> The correct steps may vary between macOS versions, so you should refer to ++> the [macOS User Guide](https://support.apple.com/en-my/guide/mac-help/mh40616/mac). ++> ++> On an older version of Lite XL, you will need to run these commands instead: + > + > ```sh + > # clears attributes from the directory +diff --git a/scripts/package.sh b/scripts/package.sh +index d2346b76..1faba509 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -264,6 +264,11 @@ main() { + $stripcmd "${exe_file}" + fi + ++ if [[ $bundle == true ]]; then ++ # https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ ++ codesign --force --deep -s - "${dest_dir}" ++ fi ++ + echo "Creating a compressed archive ${package_name}" + if [[ $binary == true ]]; then + rm -f "${package_name}".tar.gz diff --git a/tasks/lite-xl__lite-xl-1656/solution/solve.sh b/tasks/lite-xl__lite-xl-1656/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/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/lite-xl__lite-xl-1656/task.toml b/tasks/lite-xl__lite-xl-1656/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f7d462c185545a310591acab0f5d64d8421ef73 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1656" +description = "feat(package): ad-hoc sign macOS bundles" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e67ac2818ff316ececea6cb251ceb4b684aa297f" +reference = "https://github.com/lite-xl/lite-xl/pull/1656" +source_access = "auto" +built_at = "2026-11-16T16:09:56.220679+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e46dd36bfc907cf8d6b4d6c7c525d12379efcbbba31fc1f524d5c918bf8f2590" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-11-10T01:36:44Z" +diff_format = "unified" +context_files = [ + "README.md", + "scripts/package.sh", +] +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:01.292712+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:892aa53ac8b2ee89ac4ab4a06fb6617f813cc48fedb60333c8b3a5d24f17ae9f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1656/tests/capture.py b/tasks/lite-xl__lite-xl-1656/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/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/lite-xl__lite-xl-1656/tests/instruction.md b/tasks/lite-xl__lite-xl-1656/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8bbe0c788c93f2d78c7ff9998b1a877e6d99a8c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** feat(package): ad-hoc sign macOS bundles + +## Description + +# Fuck you, Apple. + +This downgrades our application from "oh this app is damaged" to "oh this app is from an unknown developer". Why do we need to go through such hoops to do this? dunno. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e67ac2818ff3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1656/tests/oracle.patch b/tasks/lite-xl__lite-xl-1656/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cac09baed4cdf85418516935bce4f40d20fd7805 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/README.md b/README.md +index 0bd00e48..05949e80 100644 +--- a/README.md ++++ b/README.md +@@ -95,7 +95,17 @@ Lite XL will load and store all your configurations and plugins in the folder. + We provide DMG files for macOS. Simply drag the program into your Applications folder. + + > **Important** +-> Since Lite XL is not signed, you **must** run this command before starting Lite XL: ++> Newer versions of Lite XL are signed with a self-signed certificate, ++> so you'll have to follow these steps when running Lite XL for the first time. ++> ++> 1. Find Lite XL in Finder (do not open it in Launchpad). ++> 2. Control-click Lite XL, then choose `Open` from the shortcut menu. ++> 3. Click `Open` in the popup menu. ++> ++> The correct steps may vary between macOS versions, so you should refer to ++> the [macOS User Guide](https://support.apple.com/en-my/guide/mac-help/mh40616/mac). ++> ++> On an older version of Lite XL, you will need to run these commands instead: + > + > ```sh + > # clears attributes from the directory +diff --git a/scripts/package.sh b/scripts/package.sh +index d2346b76..1faba509 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -264,6 +264,11 @@ main() { + $stripcmd "${exe_file}" + fi + ++ if [[ $bundle == true ]]; then ++ # https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ ++ codesign --force --deep -s - "${dest_dir}" ++ fi ++ + echo "Creating a compressed archive ${package_name}" + if [[ $binary == true ]]; then + rm -f "${package_name}".tar.gz diff --git a/tasks/lite-xl__lite-xl-1656/tests/test.sh b/tasks/lite-xl__lite-xl-1656/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ae522a928a9b8b3eef1933567fdff1d88401a4e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/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 e67ac2818ff316ececea6cb251ceb4b684aa297f > "$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/lite-xl__lite-xl-1656/tests/verifier.py b/tasks/lite-xl__lite-xl-1656/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1656/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/lite-xl__lite-xl-1710/environment/Dockerfile b/tasks/lite-xl__lite-xl-1710/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..50f815f980a3aad401fca7b5dfc5cdbf253e847f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c561eb78e623f21ba6e2c465c14543bbdfda2e96 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c561eb78e623f21ba6e2c465c14543bbdfda2e96 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c561eb78e623f21ba6e2c465c14543bbdfda2e96 \ + && 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/lite-xl__lite-xl-1710/instruction.md b/tasks/lite-xl__lite-xl-1710/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2680e0813781f97e953169449cfba8689616a2c9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** language_js: support binary and octal representation + +## Description + +Inspired by #1704, adds negative hex, bin and oct support to language_js. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c561eb78e623`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1710/solution/patch.diff b/tasks/lite-xl__lite-xl-1710/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1314bba4450486c66f032ceb463292f85ad6f52d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/data/plugins/language_js.lua b/data/plugins/language_js.lua +index 307aeecf..2eb38741 100644 +--- a/data/plugins/language_js.lua ++++ b/data/plugins/language_js.lua +@@ -57,18 +57,18 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, + { regex = regex_pattern, syntax = inner_regex_syntax, type = {"string", "string"} }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { pattern = { "`", "`", '\\' }, type = "string" }, +- { pattern = "0x[%da-fA-F_]+n?()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "-?%d+[%d%.eE_n]*()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "-?%.?%d+()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, +- { pattern = "[%a_][%w_]*%f[(]", type = "function" }, +- { pattern = "[%a_][%w_]*()%s*()/?", type = {"symbol", "normal", "operator"} }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { pattern = { "`", "`", '\\' }, type = "string" }, ++ { pattern = "-?0[xXbBoO][%da-fA-F_]+n?()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "-?%d+[%d%.eE_n]*()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "-?%.?%d+()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, ++ { pattern = "[%a_][%w_]*%f[(]", type = "function" }, ++ { pattern = "[%a_][%w_]*()%s*()/?", type = {"symbol", "normal", "operator"} }, + }, + symbols = { + ["async"] = "keyword", diff --git a/tasks/lite-xl__lite-xl-1710/solution/solve.sh b/tasks/lite-xl__lite-xl-1710/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/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/lite-xl__lite-xl-1710/task.toml b/tasks/lite-xl__lite-xl-1710/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4f8b28880fe8ee2e7122cceaca557e06685a061 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1710" +description = "language_js: support binary and octal representation" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c561eb78e623f21ba6e2c465c14543bbdfda2e96" +reference = "https://github.com/lite-xl/lite-xl/pull/1710" +source_access = "auto" +built_at = "2026-11-16T16:09:56.219479+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:947b0fd90989f7fe5a1654e3872fd05c1ba8078f71dea02f96bc91699834f54e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-01-21T02:18:13Z" +diff_format = "unified" +context_files = [ + "data/plugins/language_js.lua", +] +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:01.293157+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:023c5df7a861701df5caa20c142c5cfeeeb342029f00bedeaad850f959d868e2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1710/tests/capture.py b/tasks/lite-xl__lite-xl-1710/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/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/lite-xl__lite-xl-1710/tests/instruction.md b/tasks/lite-xl__lite-xl-1710/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2680e0813781f97e953169449cfba8689616a2c9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** language_js: support binary and octal representation + +## Description + +Inspired by #1704, adds negative hex, bin and oct support to language_js. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c561eb78e623`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1710/tests/oracle.patch b/tasks/lite-xl__lite-xl-1710/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1314bba4450486c66f032ceb463292f85ad6f52d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/data/plugins/language_js.lua b/data/plugins/language_js.lua +index 307aeecf..2eb38741 100644 +--- a/data/plugins/language_js.lua ++++ b/data/plugins/language_js.lua +@@ -57,18 +57,18 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, + { regex = regex_pattern, syntax = inner_regex_syntax, type = {"string", "string"} }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { pattern = { "`", "`", '\\' }, type = "string" }, +- { pattern = "0x[%da-fA-F_]+n?()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "-?%d+[%d%.eE_n]*()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "-?%.?%d+()%s*()/?", type = {"number", "normal", "operator"} }, +- { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, +- { pattern = "[%a_][%w_]*%f[(]", type = "function" }, +- { pattern = "[%a_][%w_]*()%s*()/?", type = {"symbol", "normal", "operator"} }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { pattern = { "`", "`", '\\' }, type = "string" }, ++ { pattern = "-?0[xXbBoO][%da-fA-F_]+n?()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "-?%d+[%d%.eE_n]*()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "-?%.?%d+()%s*()/?", type = {"number", "normal", "operator"} }, ++ { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, ++ { pattern = "[%a_][%w_]*%f[(]", type = "function" }, ++ { pattern = "[%a_][%w_]*()%s*()/?", type = {"symbol", "normal", "operator"} }, + }, + symbols = { + ["async"] = "keyword", diff --git a/tasks/lite-xl__lite-xl-1710/tests/test.sh b/tasks/lite-xl__lite-xl-1710/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0964907d709653b3e317d71f0a7bae69fa2bd0be --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/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 c561eb78e623f21ba6e2c465c14543bbdfda2e96 > "$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/lite-xl__lite-xl-1710/tests/verifier.py b/tasks/lite-xl__lite-xl-1710/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1710/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/lite-xl__lite-xl-1724/environment/Dockerfile b/tasks/lite-xl__lite-xl-1724/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8322df4e7d22fcc7d155305e488a877c040e1f5d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4d649ba92d309e7e905903666637f266812632a7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4d649ba92d309e7e905903666637f266812632a7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4d649ba92d309e7e905903666637f266812632a7 \ + && 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/lite-xl__lite-xl-1724/instruction.md b/tasks/lite-xl__lite-xl-1724/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e34b4675f24b8a2875ec9e99291635175f5ed4f2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Update action dependencies + +## Description + +This PR does a few things: + +1. Update the labeler action to remove warnings +2. Make `actions/setup-python` fetch Python 3.11 instead of any 3.x. +3. Update `actions/upload-artifact` and `actions/download-artifact` to v4, which requires some changes on artifact naming because you can no longer modify artifacts. +4. Upload other artifacts as well + +Is there any actual performance improvements from switching to v4? Not really, we don't upload alot of stuff anyway. I don't know if GitHub plans to deprecate v3 in the future, so I'm trying to future-proof this. It does make downloading artifacts better tho (now the zip files you downloaded won't be corrupt). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d649ba92d30`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1724/solution/patch.diff b/tasks/lite-xl__lite-xl-1724/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b4b7b9a865ff5ddb25886d762a219514e6f09c74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/solution/patch.diff @@ -0,0 +1,728 @@ +diff --git a/.github/workflows/auto_labeler_pr.yml b/.github/workflows/auto_labeler_pr.yml +index 48ea1eeb..99449911 100644 +--- a/.github/workflows/auto_labeler_pr.yml ++++ b/.github/workflows/auto_labeler_pr.yml +@@ -10,7 +10,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Apply Type Label +- uses: actions/labeler@v3 ++ uses: actions/labeler@v5 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" +- sync-labels: "" # works around actions/labeler#104 ++ sync-labels: false +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 21f3a8b4..2a8217c1 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -3,11 +3,11 @@ name: CI + on: + push: + branches: +- - '*' ++ - "*" + + pull_request: + branches: +- - '*' ++ - "*" + + workflow_dispatch: + +@@ -18,11 +18,12 @@ jobs: + strategy: + matrix: + config: +- - { name: "GCC", cc: gcc, cxx: g++ } +- - { name: "clang", cc: clang, cxx: clang++ } ++ - { name: "GCC", cc: gcc, cxx: g++ } ++ - { name: "clang", cc: clang, cxx: clang++ } + env: + CC: ${{ matrix.config.cc }} + CXX: ${{ matrix.config.cxx }} ++ + steps: + - name: Set Environment Variables + if: ${{ matrix.config.cc == 'gcc' }} +@@ -30,28 +31,37 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-linux-$(uname -m)-portable" >> "$GITHUB_ENV" +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Update Packages + run: sudo apt-get update ++ + - name: Install Dependencies + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --debug --forcefallback --portable ++ + - name: Package + if: ${{ matrix.config.cc == 'gcc' }} + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + if: ${{ matrix.config.cc == 'gcc' }} + with: + name: Linux Artifacts + path: ${{ env.INSTALL_NAME }}.tar.gz ++ compression-level: 0 + + build_macos: + name: macOS +@@ -61,7 +71,8 @@ jobs: + CXX: clang++ + strategy: + matrix: +- arch: ['x86_64', 'arm64'] ++ arch: ["x86_64", "arm64"] ++ + steps: + - name: System Information + run: | +@@ -69,36 +80,46 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ ++ # --lhelper will eliminate a warning with arm64 and libusb + - name: Install Dependencies +- # --lhelper will eliminate a warning with arm64 and libusb + run: bash scripts/install-dependencies.sh --debug --lhelper ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --bundle --debug --forcefallback $ARCH ++ + - name: Create DMG Image + run: bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg ++ + - name: Upload DMG Image +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images ++ name: macOS DMG Images (${{ matrix.arch }}) + path: ${{ env.INSTALL_NAME }}.dmg ++ compression-level: 0 + + build_macos_universal: + name: macOS (Universal) + runs-on: macos-11 + needs: build_macos ++ + steps: + - name: System Information + run: | +@@ -106,32 +127,42 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-universal" >> "$GITHUB_ENV" ++ + - name: Setup Python +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: '3.9' ++ python-version: "3.11" ++ + - name: Install dmgbuild + run: pip install dmgbuild +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Download artifacts +- uses: actions/download-artifact@v3 ++ uses: actions/download-artifact@v4 + id: download + with: +- name: macOS DMG Images ++ pattern: macOS DMG Images * ++ merge-multiple: true + path: dmgs-original ++ + - name: Make universal bundles + run: | + bash --version + bash scripts/make-universal-binaries.sh ${{ steps.download.outputs.download-path }} "${INSTALL_NAME}" ++ + - name: Upload DMG Image +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS Universal DMG Images ++ name: macOS DMG Images (Universal) + path: ${{ env.INSTALL_NAME }}.dmg ++ compression-level: 0 + + build_windows_msys2: + name: Windows +@@ -139,48 +170,58 @@ jobs: + strategy: + matrix: + config: +- - {msystem: MINGW32, arch: i686} +- - {msystem: MINGW64, arch: x86_64} ++ - { msystem: MINGW32, arch: i686 } ++ - { msystem: MINGW64, arch: x86_64 } + defaults: + run: + shell: msys2 {0} ++ + steps: +- - uses: actions/checkout@v3 +- - uses: msys2/setup-msys2@v2 +- with: +- msystem: ${{ matrix.config.msystem }} +- install: >- +- base-devel +- git +- zip +- mingw-w64-${{ matrix.config.arch }}-gcc +- mingw-w64-${{ matrix.config.arch }}-meson +- mingw-w64-${{ matrix.config.arch }}-ninja +- mingw-w64-${{ matrix.config.arch }}-ca-certificates +- mingw-w64-${{ matrix.config.arch }}-ntldd +- - name: Set Environment Variables +- run: | +- echo "$HOME/.local/bin" >> "$GITHUB_PATH" +- echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" +- if [[ "${MSYSTEM}" == "MINGW64" ]]; then +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-x86_64" >> "$GITHUB_ENV" +- else +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" +- fi +- - name: Install Dependencies +- if: false +- run: bash scripts/install-dependencies.sh --debug +- - name: Build +- run: | +- bash --version +- bash scripts/build.sh -U --debug --forcefallback +- - name: Package +- run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary +- - name: Upload Artifacts +- uses: actions/upload-artifact@v3 +- with: +- name: Windows Artifacts +- path: ${{ env.INSTALL_NAME }}.zip ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSYS2 ++ uses: msys2/setup-msys2@v2 ++ with: ++ msystem: ${{ matrix.config.msystem }} ++ install: >- ++ base-devel ++ git ++ zip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd ++ ++ - name: Set Environment Variables ++ run: | ++ echo "$HOME/.local/bin" >> "$GITHUB_PATH" ++ echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" ++ if [[ "${MSYSTEM}" == "MINGW64" ]]; then ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-x86_64" >> "$GITHUB_ENV" ++ else ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" ++ fi ++ ++ - name: Install Dependencies ++ if: false ++ run: bash scripts/install-dependencies.sh --debug ++ ++ - name: Build ++ run: | ++ bash --version ++ bash scripts/build.sh -U --debug --forcefallback ++ ++ - name: Package ++ run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 ++ with: ++ name: Windows Artifacts (${{ matrix.config.msystem }}) ++ path: ${{ env.INSTALL_NAME }}.zip ++ compression-level: 0 + + build_windows_msvc: + name: Windows (MSVC) +@@ -190,38 +231,52 @@ jobs: + arch: + - { target: x86, name: i686 } + - { target: x64, name: x86_64 } ++ + steps: +- - uses: actions/checkout@v3 +- - uses: ilammy/msvc-dev-cmd@v1 ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSVC ++ uses: ilammy/msvc-dev-cmd@v1 + with: + arch: ${{ matrix.arch.target }} +- - uses: actions/setup-python@v4 ++ ++ - name: Setup Python ++ uses: actions/setup-python@v5 + with: +- python-version: '3.x' ++ python-version: "3.11" ++ + - name: Install meson and ninja + run: pip install meson ninja ++ + - name: Set up environment variables + run: | + "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/$(awk -F ' *= *' '/directory/ { printf $2 }' subprojects/lua.wrap)" >> $env:GITHUB_ENV ++ + - name: Download and patch subprojects + shell: bash + run: | + meson subprojects download + cat resources/windows/001-lua-unicode.diff | patch -Np1 -d "$LUA_SUBPROJECT_PATH" ++ + - name: Configure + run: | + meson setup --wrap-mode=forcefallback build ++ + - name: Build + run: | + meson install -C build --destdir="../lite-xl" ++ + - name: Package + run: | + Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" + Compress-Archive -Path lite-xl -DestinationPath "$env:INSTALL_NAME.zip" ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: Windows Artifacts (MSVC) ++ name: Windows Artifacts (MSVC ${{ matrix.arch.target }}) + path: ${{ env.INSTALL_NAME }}.zip ++ compression-level: 0 +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index a1786c9d..f14a90ca 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -21,57 +21,64 @@ jobs: + outputs: + upload_url: ${{ steps.create_release.outputs.upload_url }} + version: ${{ steps.tag.outputs.version }} ++ + steps: + - name: Checkout code +- uses: actions/checkout@v3 ++ uses: actions/checkout@v4 + with: + fetch-depth: 0 ++ + - name: Fetch Version + id: tag + run: | + if [[ "${{ github.event.inputs.version }}" != "" ]]; then +- echo ::set-output name=version::${{ github.event.inputs.version }} ++ echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT + else +- echo ::set-output name=version::${GITHUB_REF/refs\/tags\//} ++ echo "version=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT + fi ++ + - name: Update Tag + uses: richardsimko/update-tag@v1 + with: + tag_name: ${{ steps.tag.outputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ + - name: Generate Release Notes + run: bash scripts/generate-release-notes.sh --version ${{ steps.tag.outputs.version }} ++ + - name: Create Release + id: create_release +- uses: softprops/action-gh-release@v1 ++ uses: ncipollo/release-action@v1 + with: +- tag_name: ${{ steps.tag.outputs.version }} + name: Lite XL ${{ steps.tag.outputs.version }} ++ tag: ${{ steps.tag.outputs.version }} + draft: true +- body_path: release-notes.md ++ bodyFile: release-notes.md ++ generateReleaseNotes: true ++ allowUpdates: true + + build_linux: + name: Linux + needs: release + runs-on: ubuntu-latest +- container: ghcr.io/lite-xl/lite-xl-build-box:latest +- env: +- CC: gcc +- CXX: g++ ++ + steps: + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v3 ++ echo "CCACHE_DIR=$PWD/.ccache" >> $GITHUB_ENV ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 + + # disabled because this will break our own Python install + - name: Python Setup + if: false +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" + + # disabled because the container has up-to-date packages + - name: Update Packages +@@ -86,23 +93,34 @@ jobs: + sudo apt-get install -y ccache + + - name: Build Portable +- run: | +- bash --version +- bash scripts/build.sh --debug --forcefallback --portable --release ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ with: ++ entrypoint: /entrypoint.sh ++ args: | ++ bash --version ++ bash scripts/build.sh --debug --forcefallback --portable --release ++ + - name: Package Portables +- run: | +- bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release +- bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ with: ++ entrypoint: /entrypoint.sh ++ args: | ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ + - name: Build AppImages +- run: | +- bash scripts/appimage.sh --debug --static --version ${INSTALL_REF} --release +- bash scripts/appimage.sh --debug --nobuild --addons --version ${INSTALL_REF} +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ entrypoint: /entrypoint.sh ++ args: | ++ bash scripts/appimage.sh --debug --static --version ${INSTALL_REF} --release ++ bash scripts/appimage.sh --debug --nobuild --addons --version ${INSTALL_REF} ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 ++ with: ++ name: Linux Artifacts ++ path: | + lite-xl-${{ env.INSTALL_REF }}-linux-x86_64-portable.tar.gz + lite-xl-${{ env.INSTALL_REF }}-addons-linux-x86_64-portable.tar.gz + LiteXL-${{ env.INSTALL_REF }}-x86_64.AppImage +@@ -118,6 +136,7 @@ jobs: + env: + CC: clang + CXX: clang++ ++ + steps: + - name: System Information + run: | +@@ -125,6 +144,7 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" +@@ -132,41 +152,41 @@ jobs: + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Install Dependencies + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --bundle --debug --forcefallback --release $ARCH ++ + - name: Create DMG Image + run: | + bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg --release + bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --addons --dmg --release ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images ++ name: macOS DMG Images (${{ matrix.arch }}) + path: | + ${{ env.INSTALL_NAME }}.dmg + ${{ env.INSTALL_NAME_ADDONS }}.dmg +- - name: Upload Files +- uses: softprops/action-gh-release@v1 +- with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | +- ${{ env.INSTALL_NAME }}.dmg +- ${{ env.INSTALL_NAME_ADDONS }}.dmg + + build_macos_universal: + name: macOS (Universal) + needs: [release, build_macos] + runs-on: macos-11 ++ + steps: + - name: System Information + run: | +@@ -174,40 +194,48 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_BASE=lite-xl-${{ needs.release.outputs.version }}-macos" >> "$GITHUB_ENV" + echo "INSTALL_BASE_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ ++ - uses: actions/checkout@v4 ++ + - name: Download Artifacts +- uses: actions/download-artifact@v3 ++ uses: actions/download-artifact@v4 + id: download + with: +- name: macOS DMG Images ++ pattern: macOS DMG Images * ++ merge-multiple: true + path: dmgs-original ++ + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Install dmgbuild + run: pip install dmgbuild ++ + - name: Prepare DMG Images + run: | + mkdir -p dmgs-addons dmgs-normal + mv -v "${{ steps.download.outputs.download-path }}/$INSTALL_BASE-"{x86_64,arm64}.dmg dmgs-normal + mv -v "${{ steps.download.outputs.download-path }}/$INSTALL_BASE_ADDONS-"{x86_64,arm64}.dmg dmgs-addons ++ + - name: Create Universal DMGs + run: | + bash --version + bash scripts/make-universal-binaries.sh dmgs-normal "$INSTALL_BASE-universal" + bash scripts/make-universal-binaries.sh dmgs-addons "$INSTALL_BASE_ADDONS-universal" +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ name: macOS DMG Images (Universal) ++ path: | + ${{ env.INSTALL_BASE }}-universal.dmg + ${{ env.INSTALL_BASE_ADDONS }}-universal.dmg + +@@ -217,54 +245,95 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- msystem: [MINGW32, MINGW64] ++ config: ++ - { msystem: MINGW32, arch: i686 } ++ - { msystem: MINGW64, arch: x86_64 } + defaults: + run: + shell: msys2 {0} ++ + steps: +- - uses: actions/checkout@v3 +- - uses: msys2/setup-msys2@v2 ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSYS2 ++ uses: msys2/setup-msys2@v2 + with: +- msystem: ${{ matrix.msystem }} ++ msystem: ${{ matrix.config.msystem }} + update: true + install: >- + base-devel + git + zip ++ unzip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + if [[ "${MSYSTEM}" == "MINGW64" ]]; then +- echo "BUILD_ARCH=x86_64" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-windows-x86_64" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-windows-x86_64" >> "$GITHUB_ENV" + else +- echo "BUILD_ARCH=i686" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-windows-i686" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-windows-i686" >> "$GITHUB_ENV" + fi ++ + - name: Install Dependencies ++ if: false + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh -U --debug --forcefallback --release ++ + - name: Package + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release ++ + - name: Build Installer + run: bash scripts/innosetup/innosetup.sh --debug --version ${INSTALL_REF} ++ + - name: Package With Addons + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ + - name: Build Installer With Addons + run: bash scripts/innosetup/innosetup.sh --debug --version ${INSTALL_REF} --addons +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ name: Windows Builds (${{ matrix.config.msystem }}) ++ path: | + ${{ env.INSTALL_NAME }}.zip + ${{ env.INSTALL_NAME_ADDONS }}.zip +- LiteXL-${{ env.INSTALL_REF }}-${{ env.BUILD_ARCH }}-setup.exe +- LiteXL-${{ env.INSTALL_REF }}-addons-${{ env.BUILD_ARCH }}-setup.exe ++ LiteXL-${{ env.INSTALL_REF }}-${{ matrix.config.arch }}-setup.exe ++ LiteXL-${{ env.INSTALL_REF }}-addons-${{ matrix.config.arch }}-setup.exe ++ ++ upload_artifacts: ++ name: Upload Release Artifacts ++ runs-on: ubuntu-latest ++ needs: ++ [release, build_linux, build_macos, build_macos_universal, build_windows_msys2] ++ ++ steps: ++ - name: Download Artifacts ++ uses: actions/download-artifact@v4 ++ with: ++ merge-multiple: true ++ ++ - name: Update Release ++ uses: ncipollo/release-action@v1 ++ with: ++ tag: ${{ needs.release.outputs.version }} ++ omitBodyDuringUpdate: true ++ omitDraftDuringUpdate: true ++ omitNameDuringUpdate: true ++ omitPrereleaseDuringUpdate: true ++ allowUpdates: true ++ artifacts: "*.exe,*.zip,*.tar.gz,*.dmg,*.AppImage" diff --git a/tasks/lite-xl__lite-xl-1724/solution/solve.sh b/tasks/lite-xl__lite-xl-1724/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/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/lite-xl__lite-xl-1724/task.toml b/tasks/lite-xl__lite-xl-1724/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a64f6e4719e5b644489cab93613aa16bc9c9e257 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1724" +description = "Update action dependencies" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "4d649ba92d309e7e905903666637f266812632a7" +reference = "https://github.com/lite-xl/lite-xl/pull/1724" +source_access = "auto" +built_at = "2026-11-16T16:09:56.225580+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0a364083261ba2b099864b028fcecd4dafdebd941679f7c3cb718835f64c0c4d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-07T02:08:13Z" +diff_format = "unified" +context_files = [ + ".github/workflows/auto_labeler_pr.yml", + ".github/workflows/build.yml", + ".github/workflows/release.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 386 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.293604+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:02cf4aab33f8bd1b2cca7c315c5f4c65b3c79b1c18204552389e9338485839c6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1724/tests/capture.py b/tasks/lite-xl__lite-xl-1724/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/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/lite-xl__lite-xl-1724/tests/instruction.md b/tasks/lite-xl__lite-xl-1724/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e34b4675f24b8a2875ec9e99291635175f5ed4f2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Update action dependencies + +## Description + +This PR does a few things: + +1. Update the labeler action to remove warnings +2. Make `actions/setup-python` fetch Python 3.11 instead of any 3.x. +3. Update `actions/upload-artifact` and `actions/download-artifact` to v4, which requires some changes on artifact naming because you can no longer modify artifacts. +4. Upload other artifacts as well + +Is there any actual performance improvements from switching to v4? Not really, we don't upload alot of stuff anyway. I don't know if GitHub plans to deprecate v3 in the future, so I'm trying to future-proof this. It does make downloading artifacts better tho (now the zip files you downloaded won't be corrupt). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d649ba92d30`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1724/tests/oracle.patch b/tasks/lite-xl__lite-xl-1724/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b4b7b9a865ff5ddb25886d762a219514e6f09c74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/tests/oracle.patch @@ -0,0 +1,728 @@ +diff --git a/.github/workflows/auto_labeler_pr.yml b/.github/workflows/auto_labeler_pr.yml +index 48ea1eeb..99449911 100644 +--- a/.github/workflows/auto_labeler_pr.yml ++++ b/.github/workflows/auto_labeler_pr.yml +@@ -10,7 +10,7 @@ jobs: + runs-on: ubuntu-latest + steps: + - name: Apply Type Label +- uses: actions/labeler@v3 ++ uses: actions/labeler@v5 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" +- sync-labels: "" # works around actions/labeler#104 ++ sync-labels: false +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 21f3a8b4..2a8217c1 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -3,11 +3,11 @@ name: CI + on: + push: + branches: +- - '*' ++ - "*" + + pull_request: + branches: +- - '*' ++ - "*" + + workflow_dispatch: + +@@ -18,11 +18,12 @@ jobs: + strategy: + matrix: + config: +- - { name: "GCC", cc: gcc, cxx: g++ } +- - { name: "clang", cc: clang, cxx: clang++ } ++ - { name: "GCC", cc: gcc, cxx: g++ } ++ - { name: "clang", cc: clang, cxx: clang++ } + env: + CC: ${{ matrix.config.cc }} + CXX: ${{ matrix.config.cxx }} ++ + steps: + - name: Set Environment Variables + if: ${{ matrix.config.cc == 'gcc' }} +@@ -30,28 +31,37 @@ jobs: + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-linux-$(uname -m)-portable" >> "$GITHUB_ENV" +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Update Packages + run: sudo apt-get update ++ + - name: Install Dependencies + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --debug --forcefallback --portable ++ + - name: Package + if: ${{ matrix.config.cc == 'gcc' }} + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + if: ${{ matrix.config.cc == 'gcc' }} + with: + name: Linux Artifacts + path: ${{ env.INSTALL_NAME }}.tar.gz ++ compression-level: 0 + + build_macos: + name: macOS +@@ -61,7 +71,8 @@ jobs: + CXX: clang++ + strategy: + matrix: +- arch: ['x86_64', 'arm64'] ++ arch: ["x86_64", "arm64"] ++ + steps: + - name: System Information + run: | +@@ -69,36 +80,46 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ ++ # --lhelper will eliminate a warning with arm64 and libusb + - name: Install Dependencies +- # --lhelper will eliminate a warning with arm64 and libusb + run: bash scripts/install-dependencies.sh --debug --lhelper ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --bundle --debug --forcefallback $ARCH ++ + - name: Create DMG Image + run: bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg ++ + - name: Upload DMG Image +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images ++ name: macOS DMG Images (${{ matrix.arch }}) + path: ${{ env.INSTALL_NAME }}.dmg ++ compression-level: 0 + + build_macos_universal: + name: macOS (Universal) + runs-on: macos-11 + needs: build_macos ++ + steps: + - name: System Information + run: | +@@ -106,32 +127,42 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-universal" >> "$GITHUB_ENV" ++ + - name: Setup Python +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: '3.9' ++ python-version: "3.11" ++ + - name: Install dmgbuild + run: pip install dmgbuild +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Download artifacts +- uses: actions/download-artifact@v3 ++ uses: actions/download-artifact@v4 + id: download + with: +- name: macOS DMG Images ++ pattern: macOS DMG Images * ++ merge-multiple: true + path: dmgs-original ++ + - name: Make universal bundles + run: | + bash --version + bash scripts/make-universal-binaries.sh ${{ steps.download.outputs.download-path }} "${INSTALL_NAME}" ++ + - name: Upload DMG Image +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS Universal DMG Images ++ name: macOS DMG Images (Universal) + path: ${{ env.INSTALL_NAME }}.dmg ++ compression-level: 0 + + build_windows_msys2: + name: Windows +@@ -139,48 +170,58 @@ jobs: + strategy: + matrix: + config: +- - {msystem: MINGW32, arch: i686} +- - {msystem: MINGW64, arch: x86_64} ++ - { msystem: MINGW32, arch: i686 } ++ - { msystem: MINGW64, arch: x86_64 } + defaults: + run: + shell: msys2 {0} ++ + steps: +- - uses: actions/checkout@v3 +- - uses: msys2/setup-msys2@v2 +- with: +- msystem: ${{ matrix.config.msystem }} +- install: >- +- base-devel +- git +- zip +- mingw-w64-${{ matrix.config.arch }}-gcc +- mingw-w64-${{ matrix.config.arch }}-meson +- mingw-w64-${{ matrix.config.arch }}-ninja +- mingw-w64-${{ matrix.config.arch }}-ca-certificates +- mingw-w64-${{ matrix.config.arch }}-ntldd +- - name: Set Environment Variables +- run: | +- echo "$HOME/.local/bin" >> "$GITHUB_PATH" +- echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" +- if [[ "${MSYSTEM}" == "MINGW64" ]]; then +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-x86_64" >> "$GITHUB_ENV" +- else +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" +- fi +- - name: Install Dependencies +- if: false +- run: bash scripts/install-dependencies.sh --debug +- - name: Build +- run: | +- bash --version +- bash scripts/build.sh -U --debug --forcefallback +- - name: Package +- run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary +- - name: Upload Artifacts +- uses: actions/upload-artifact@v3 +- with: +- name: Windows Artifacts +- path: ${{ env.INSTALL_NAME }}.zip ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSYS2 ++ uses: msys2/setup-msys2@v2 ++ with: ++ msystem: ${{ matrix.config.msystem }} ++ install: >- ++ base-devel ++ git ++ zip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd ++ ++ - name: Set Environment Variables ++ run: | ++ echo "$HOME/.local/bin" >> "$GITHUB_PATH" ++ echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" ++ if [[ "${MSYSTEM}" == "MINGW64" ]]; then ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-x86_64" >> "$GITHUB_ENV" ++ else ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-windows-i686" >> "$GITHUB_ENV" ++ fi ++ ++ - name: Install Dependencies ++ if: false ++ run: bash scripts/install-dependencies.sh --debug ++ ++ - name: Build ++ run: | ++ bash --version ++ bash scripts/build.sh -U --debug --forcefallback ++ ++ - name: Package ++ run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 ++ with: ++ name: Windows Artifacts (${{ matrix.config.msystem }}) ++ path: ${{ env.INSTALL_NAME }}.zip ++ compression-level: 0 + + build_windows_msvc: + name: Windows (MSVC) +@@ -190,38 +231,52 @@ jobs: + arch: + - { target: x86, name: i686 } + - { target: x64, name: x86_64 } ++ + steps: +- - uses: actions/checkout@v3 +- - uses: ilammy/msvc-dev-cmd@v1 ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSVC ++ uses: ilammy/msvc-dev-cmd@v1 + with: + arch: ${{ matrix.arch.target }} +- - uses: actions/setup-python@v4 ++ ++ - name: Setup Python ++ uses: actions/setup-python@v5 + with: +- python-version: '3.x' ++ python-version: "3.11" ++ + - name: Install meson and ninja + run: pip install meson ninja ++ + - name: Set up environment variables + run: | + "INSTALL_NAME=lite-xl-$($env:GITHUB_REF -replace ".*/")-windows-msvc-${{ matrix.arch.name }}" >> $env:GITHUB_ENV + "INSTALL_REF=$($env:GITHUB_REF -replace ".*/")" >> $env:GITHUB_ENV + "LUA_SUBPROJECT_PATH=subprojects/$(awk -F ' *= *' '/directory/ { printf $2 }' subprojects/lua.wrap)" >> $env:GITHUB_ENV ++ + - name: Download and patch subprojects + shell: bash + run: | + meson subprojects download + cat resources/windows/001-lua-unicode.diff | patch -Np1 -d "$LUA_SUBPROJECT_PATH" ++ + - name: Configure + run: | + meson setup --wrap-mode=forcefallback build ++ + - name: Build + run: | + meson install -C build --destdir="../lite-xl" ++ + - name: Package + run: | + Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" + Compress-Archive -Path lite-xl -DestinationPath "$env:INSTALL_NAME.zip" ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: Windows Artifacts (MSVC) ++ name: Windows Artifacts (MSVC ${{ matrix.arch.target }}) + path: ${{ env.INSTALL_NAME }}.zip ++ compression-level: 0 +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index a1786c9d..f14a90ca 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -21,57 +21,64 @@ jobs: + outputs: + upload_url: ${{ steps.create_release.outputs.upload_url }} + version: ${{ steps.tag.outputs.version }} ++ + steps: + - name: Checkout code +- uses: actions/checkout@v3 ++ uses: actions/checkout@v4 + with: + fetch-depth: 0 ++ + - name: Fetch Version + id: tag + run: | + if [[ "${{ github.event.inputs.version }}" != "" ]]; then +- echo ::set-output name=version::${{ github.event.inputs.version }} ++ echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT + else +- echo ::set-output name=version::${GITHUB_REF/refs\/tags\//} ++ echo "version=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_OUTPUT + fi ++ + - name: Update Tag + uses: richardsimko/update-tag@v1 + with: + tag_name: ${{ steps.tag.outputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ + - name: Generate Release Notes + run: bash scripts/generate-release-notes.sh --version ${{ steps.tag.outputs.version }} ++ + - name: Create Release + id: create_release +- uses: softprops/action-gh-release@v1 ++ uses: ncipollo/release-action@v1 + with: +- tag_name: ${{ steps.tag.outputs.version }} + name: Lite XL ${{ steps.tag.outputs.version }} ++ tag: ${{ steps.tag.outputs.version }} + draft: true +- body_path: release-notes.md ++ bodyFile: release-notes.md ++ generateReleaseNotes: true ++ allowUpdates: true + + build_linux: + name: Linux + needs: release + runs-on: ubuntu-latest +- container: ghcr.io/lite-xl/lite-xl-build-box:latest +- env: +- CC: gcc +- CXX: g++ ++ + steps: + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- - uses: actions/checkout@v3 ++ echo "CCACHE_DIR=$PWD/.ccache" >> $GITHUB_ENV ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 + + # disabled because this will break our own Python install + - name: Python Setup + if: false +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" + + # disabled because the container has up-to-date packages + - name: Update Packages +@@ -86,23 +93,34 @@ jobs: + sudo apt-get install -y ccache + + - name: Build Portable +- run: | +- bash --version +- bash scripts/build.sh --debug --forcefallback --portable --release ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ with: ++ entrypoint: /entrypoint.sh ++ args: | ++ bash --version ++ bash scripts/build.sh --debug --forcefallback --portable --release ++ + - name: Package Portables +- run: | +- bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release +- bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ with: ++ entrypoint: /entrypoint.sh ++ args: | ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ + - name: Build AppImages +- run: | +- bash scripts/appimage.sh --debug --static --version ${INSTALL_REF} --release +- bash scripts/appimage.sh --debug --nobuild --addons --version ${INSTALL_REF} +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ entrypoint: /entrypoint.sh ++ args: | ++ bash scripts/appimage.sh --debug --static --version ${INSTALL_REF} --release ++ bash scripts/appimage.sh --debug --nobuild --addons --version ${INSTALL_REF} ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 ++ with: ++ name: Linux Artifacts ++ path: | + lite-xl-${{ env.INSTALL_REF }}-linux-x86_64-portable.tar.gz + lite-xl-${{ env.INSTALL_REF }}-addons-linux-x86_64-portable.tar.gz + LiteXL-${{ env.INSTALL_REF }}-x86_64.AppImage +@@ -118,6 +136,7 @@ jobs: + env: + CC: clang + CXX: clang++ ++ + steps: + - name: System Information + run: | +@@ -125,6 +144,7 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" +@@ -132,41 +152,41 @@ jobs: + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" + if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi +- - uses: actions/checkout@v3 ++ ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ + - name: Python Setup +- uses: actions/setup-python@v4 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Install Dependencies + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh --bundle --debug --forcefallback --release $ARCH ++ + - name: Create DMG Image + run: | + bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg --release + bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --addons --dmg --release ++ + - name: Upload Artifacts +- uses: actions/upload-artifact@v3 ++ uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images ++ name: macOS DMG Images (${{ matrix.arch }}) + path: | + ${{ env.INSTALL_NAME }}.dmg + ${{ env.INSTALL_NAME_ADDONS }}.dmg +- - name: Upload Files +- uses: softprops/action-gh-release@v1 +- with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | +- ${{ env.INSTALL_NAME }}.dmg +- ${{ env.INSTALL_NAME_ADDONS }}.dmg + + build_macos_universal: + name: macOS (Universal) + needs: [release, build_macos] + runs-on: macos-11 ++ + steps: + - name: System Information + run: | +@@ -174,40 +194,48 @@ jobs: + bash --version + gcc -v + xcodebuild -version ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_BASE=lite-xl-${{ needs.release.outputs.version }}-macos" >> "$GITHUB_ENV" + echo "INSTALL_BASE_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos" >> "$GITHUB_ENV" +- - uses: actions/checkout@v2 ++ ++ - uses: actions/checkout@v4 ++ + - name: Download Artifacts +- uses: actions/download-artifact@v3 ++ uses: actions/download-artifact@v4 + id: download + with: +- name: macOS DMG Images ++ pattern: macOS DMG Images * ++ merge-multiple: true + path: dmgs-original ++ + - name: Python Setup +- uses: actions/setup-python@v2 ++ uses: actions/setup-python@v5 + with: +- python-version: 3.9 ++ python-version: "3.11" ++ + - name: Install dmgbuild + run: pip install dmgbuild ++ + - name: Prepare DMG Images + run: | + mkdir -p dmgs-addons dmgs-normal + mv -v "${{ steps.download.outputs.download-path }}/$INSTALL_BASE-"{x86_64,arm64}.dmg dmgs-normal + mv -v "${{ steps.download.outputs.download-path }}/$INSTALL_BASE_ADDONS-"{x86_64,arm64}.dmg dmgs-addons ++ + - name: Create Universal DMGs + run: | + bash --version + bash scripts/make-universal-binaries.sh dmgs-normal "$INSTALL_BASE-universal" + bash scripts/make-universal-binaries.sh dmgs-addons "$INSTALL_BASE_ADDONS-universal" +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ name: macOS DMG Images (Universal) ++ path: | + ${{ env.INSTALL_BASE }}-universal.dmg + ${{ env.INSTALL_BASE_ADDONS }}-universal.dmg + +@@ -217,54 +245,95 @@ jobs: + runs-on: windows-2019 + strategy: + matrix: +- msystem: [MINGW32, MINGW64] ++ config: ++ - { msystem: MINGW32, arch: i686 } ++ - { msystem: MINGW64, arch: x86_64 } + defaults: + run: + shell: msys2 {0} ++ + steps: +- - uses: actions/checkout@v3 +- - uses: msys2/setup-msys2@v2 ++ - name: Checkout code ++ uses: actions/checkout@v4 ++ ++ - name: Setup MSYS2 ++ uses: msys2/setup-msys2@v2 + with: +- msystem: ${{ matrix.msystem }} ++ msystem: ${{ matrix.config.msystem }} + update: true + install: >- + base-devel + git + zip ++ unzip ++ mingw-w64-${{ matrix.config.arch }}-gcc ++ mingw-w64-${{ matrix.config.arch }}-meson ++ mingw-w64-${{ matrix.config.arch }}-ninja ++ mingw-w64-${{ matrix.config.arch }}-ca-certificates ++ mingw-w64-${{ matrix.config.arch }}-ntldd ++ + - name: Set Environment Variables + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" + if [[ "${MSYSTEM}" == "MINGW64" ]]; then +- echo "BUILD_ARCH=x86_64" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-windows-x86_64" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-windows-x86_64" >> "$GITHUB_ENV" + else +- echo "BUILD_ARCH=i686" >> "$GITHUB_ENV" + echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-windows-i686" >> "$GITHUB_ENV" + echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-windows-i686" >> "$GITHUB_ENV" + fi ++ + - name: Install Dependencies ++ if: false + run: bash scripts/install-dependencies.sh --debug ++ + - name: Build + run: | + bash --version + bash scripts/build.sh -U --debug --forcefallback --release ++ + - name: Package + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --binary --release ++ + - name: Build Installer + run: bash scripts/innosetup/innosetup.sh --debug --version ${INSTALL_REF} ++ + - name: Package With Addons + run: bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release ++ + - name: Build Installer With Addons + run: bash scripts/innosetup/innosetup.sh --debug --version ${INSTALL_REF} --addons +- - name: Upload Files +- uses: softprops/action-gh-release@v1 ++ ++ - name: Upload Artifacts ++ uses: actions/upload-artifact@v4 + with: +- tag_name: ${{ needs.release.outputs.version }} +- draft: true +- files: | ++ name: Windows Builds (${{ matrix.config.msystem }}) ++ path: | + ${{ env.INSTALL_NAME }}.zip + ${{ env.INSTALL_NAME_ADDONS }}.zip +- LiteXL-${{ env.INSTALL_REF }}-${{ env.BUILD_ARCH }}-setup.exe +- LiteXL-${{ env.INSTALL_REF }}-addons-${{ env.BUILD_ARCH }}-setup.exe ++ LiteXL-${{ env.INSTALL_REF }}-${{ matrix.config.arch }}-setup.exe ++ LiteXL-${{ env.INSTALL_REF }}-addons-${{ matrix.config.arch }}-setup.exe ++ ++ upload_artifacts: ++ name: Upload Release Artifacts ++ runs-on: ubuntu-latest ++ needs: ++ [release, build_linux, build_macos, build_macos_universal, build_windows_msys2] ++ ++ steps: ++ - name: Download Artifacts ++ uses: actions/download-artifact@v4 ++ with: ++ merge-multiple: true ++ ++ - name: Update Release ++ uses: ncipollo/release-action@v1 ++ with: ++ tag: ${{ needs.release.outputs.version }} ++ omitBodyDuringUpdate: true ++ omitDraftDuringUpdate: true ++ omitNameDuringUpdate: true ++ omitPrereleaseDuringUpdate: true ++ allowUpdates: true ++ artifacts: "*.exe,*.zip,*.tar.gz,*.dmg,*.AppImage" diff --git a/tasks/lite-xl__lite-xl-1724/tests/test.sh b/tasks/lite-xl__lite-xl-1724/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3e9842ed6489270cd462ec9617a6ee7ed43e14ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/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 4d649ba92d309e7e905903666637f266812632a7 > "$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/lite-xl__lite-xl-1724/tests/verifier.py b/tasks/lite-xl__lite-xl-1724/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1724/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/lite-xl__lite-xl-1729/environment/Dockerfile b/tasks/lite-xl__lite-xl-1729/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb62dcb42253049c69d4bd224d4a05faeba43800 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 03b8c239dcac7134d5d142f22e79874d3cd9d87e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 03b8c239dcac7134d5d142f22e79874d3cd9d87e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 03b8c239dcac7134d5d142f22e79874d3cd9d87e \ + && 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/lite-xl__lite-xl-1729/instruction.md b/tasks/lite-xl__lite-xl-1729/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4bc7f655952469d8e902d09a343b78bc03a1bbb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Add primary selection support + +## Description + +For now this is only added for semi-explicit user actions, so plugins setting selections will not update the primary selection. +This is useful for cases like the type-ahead of the command palette, where we actually don't want to set the primary selection to the selected part. + +Let me know if I missed some actions. + +This is semi-disabled for Windows, as primary selection isn't supported there. +Does macOS support it? + +Testing on Windows and macOS is welcome. + +Testing the behavior with multi-selections is also welcome. + +This supersedes the `primary_selection` plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03b8c239dcac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1729/solution/patch.diff b/tasks/lite-xl__lite-xl-1729/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c2fd9effae0e58b4f886678c55138f0ab4a7cc8d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/solution/patch.diff @@ -0,0 +1,231 @@ +diff --git a/data/core/commands/doc.lua b/data/core/commands/doc.lua +index 65c92e28..66e88eea 100644 +--- a/data/core/commands/doc.lua ++++ b/data/core/commands/doc.lua +@@ -93,6 +93,13 @@ local function cut_or_copy(delete) + system.set_clipboard(full_text) + end + ++local function set_primary_selection(doc) ++ -- Doesn't work on Windows, so avoid spending time getting the text ++ if PLATFORM ~= "Windows" then ++ system.set_primary_selection(doc:get_selection_text()) ++ end ++end ++ + local function split_cursor(dv, direction) + local new_cursors = {} + local dv_translate = direction < 0 +@@ -297,6 +304,15 @@ local commands = { + end + end, + ++ ["doc:paste-primary-selection"] = function(dv, x, y) ++ if type(x) == "number" and type(y) == "number" then ++ set_cursor(dv, x, y, "set") ++ -- Workaround to avoid that a middle mouse drag starts selecting ++ dv.mouse_selecting = nil ++ end ++ dv.doc:text_input(system.get_primary_selection() or "") ++ end, ++ + ["doc:newline"] = function(dv) + for idx, line, col in dv.doc:get_selections(false, true) do + local indent = dv.doc.lines[line]:match("^[\t ]*") +@@ -353,6 +369,7 @@ local commands = { + + ["doc:select-all"] = function(dv) + dv.doc:set_selection(1, 1, math.huge, math.huge) ++ set_primary_selection(dv.doc) + -- avoid triggering DocView:scroll_to_make_visible + dv.last_line1 = 1 + dv.last_col1 = 1 +@@ -365,6 +382,7 @@ local commands = { + append_line_if_last_line(line2) + dv.doc:set_selections(idx, line2 + 1, 1, line1, 1) + end ++ set_primary_selection(dv.doc) + end, + + ["doc:select-word"] = function(dv) +@@ -373,6 +391,7 @@ local commands = { + local line2, col2 = translate.end_of_word(dv.doc, line1, col1) + dv.doc:set_selections(idx, line2, col2, line1, col1) + end ++ set_primary_selection(dv.doc) + end, + + ["doc:join-lines"] = function(dv) +@@ -626,6 +645,7 @@ local commands = { + local line2, col2 = dv:resolve_screen_position(x, y) + dv.mouse_selecting = { line1, col1, nil } + dv.doc:set_selection(line2, col2, line1, col1) ++ set_primary_selection(dv.doc) + end, + + ["doc:create-cursor-previous-line"] = function(dv) +@@ -696,9 +716,16 @@ local translations = { + } + + for name, obj in pairs(translations) do +- commands["doc:move-to-" .. name] = function(dv) dv.doc:move_to(obj[name:gsub("-", "_")], dv) end +- commands["doc:select-to-" .. name] = function(dv) dv.doc:select_to(obj[name:gsub("-", "_")], dv) end +- commands["doc:delete-to-" .. name] = function(dv) dv.doc:delete_to(obj[name:gsub("-", "_")], dv) end ++ commands["doc:move-to-" .. name] = function(dv) ++ dv.doc:move_to(obj[name:gsub("-", "_")], dv) ++ end ++ commands["doc:select-to-" .. name] = function(dv) ++ dv.doc:select_to(obj[name:gsub("-", "_")], dv) ++ set_primary_selection(dv.doc) ++ end ++ commands["doc:delete-to-" .. name] = function(dv) ++ dv.doc:delete_to(obj[name:gsub("-", "_")], dv) ++ end + end + + commands["doc:move-to-previous-char"] = function(dv) +diff --git a/data/core/keymap.lua b/data/core/keymap.lua +index 9f19cfb7..844a97e9 100644 +--- a/data/core/keymap.lua ++++ b/data/core/keymap.lua +@@ -393,6 +393,7 @@ keymap.add_direct { + ["1lclick"] = "doc:set-cursor", + ["2lclick"] = { "doc:set-cursor-word", "emptyview:new-doc", "tabbar:new-doc" }, + ["3lclick"] = "doc:set-cursor-line", ++ ["mclick"] = "doc:paste-primary-selection", + ["shift+left"] = "doc:select-to-previous-char", + ["shift+right"] = "doc:select-to-next-char", + ["shift+up"] = "doc:select-to-previous-line", +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 792fa623..8894a795 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -255,6 +255,18 @@ function system.get_clipboard() end + ---@param text string + function system.set_clipboard(text) end + ++--- ++---Retrieve the text currently stored in the primary selection. ++--- ++---@return string ++function system.get_primary_selection() end ++ ++--- ++---Set the content of the primary selection. ++--- ++---@param text string ++function system.set_primary_selection(text) end ++ + --- + ---Get the process id of lite-xl itself. + --- +diff --git a/src/api/system.c b/src/api/system.c +index b13a7754..b5aa4126 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -843,6 +843,28 @@ static int f_set_clipboard(lua_State *L) { + } + + ++static int f_get_primary_selection(lua_State *L) { ++#if SDL_VERSION_ATLEAST(2, 26, 0) ++ char *text = SDL_GetPrimarySelectionText(); ++ if (!text) { return 0; } ++ lua_pushstring(L, text); ++ SDL_free(text); ++ return 1; ++#else ++ return 0; ++#endif ++} ++ ++ ++static int f_set_primary_selection(lua_State *L) { ++#if SDL_VERSION_ATLEAST(2, 26, 0) ++ const char *text = luaL_checkstring(L, 1); ++ SDL_SetPrimarySelectionText(text); ++#endif ++ return 0; ++} ++ ++ + static int f_get_process_id(lua_State *L) { + #ifdef _WIN32 + lua_pushinteger(L, GetCurrentProcessId()); +@@ -1172,40 +1194,42 @@ static int f_setenv(lua_State* L) { + + + static const luaL_Reg lib[] = { +- { "poll_event", f_poll_event }, +- { "wait_event", f_wait_event }, +- { "set_cursor", f_set_cursor }, +- { "set_window_title", f_set_window_title }, +- { "set_window_mode", f_set_window_mode }, +- { "get_window_mode", f_get_window_mode }, +- { "set_window_bordered", f_set_window_bordered }, +- { "set_window_hit_test", f_set_window_hit_test }, +- { "get_window_size", f_get_window_size }, +- { "set_window_size", f_set_window_size }, +- { "set_text_input_rect", f_set_text_input_rect }, +- { "clear_ime", f_clear_ime }, +- { "window_has_focus", f_window_has_focus }, +- { "raise_window", f_raise_window }, +- { "show_fatal_error", f_show_fatal_error }, +- { "rmdir", f_rmdir }, +- { "chdir", f_chdir }, +- { "mkdir", f_mkdir }, +- { "list_dir", f_list_dir }, +- { "absolute_path", f_absolute_path }, +- { "get_file_info", f_get_file_info }, +- { "get_clipboard", f_get_clipboard }, +- { "set_clipboard", f_set_clipboard }, +- { "get_process_id", f_get_process_id }, +- { "get_time", f_get_time }, +- { "sleep", f_sleep }, +- { "exec", f_exec }, +- { "fuzzy_match", f_fuzzy_match }, +- { "set_window_opacity", f_set_window_opacity }, +- { "load_native_plugin", f_load_native_plugin }, +- { "path_compare", f_path_compare }, +- { "get_fs_type", f_get_fs_type }, +- { "text_input", f_text_input }, +- { "setenv", f_setenv }, ++ { "poll_event", f_poll_event }, ++ { "wait_event", f_wait_event }, ++ { "set_cursor", f_set_cursor }, ++ { "set_window_title", f_set_window_title }, ++ { "set_window_mode", f_set_window_mode }, ++ { "get_window_mode", f_get_window_mode }, ++ { "set_window_bordered", f_set_window_bordered }, ++ { "set_window_hit_test", f_set_window_hit_test }, ++ { "get_window_size", f_get_window_size }, ++ { "set_window_size", f_set_window_size }, ++ { "set_text_input_rect", f_set_text_input_rect }, ++ { "clear_ime", f_clear_ime }, ++ { "window_has_focus", f_window_has_focus }, ++ { "raise_window", f_raise_window }, ++ { "show_fatal_error", f_show_fatal_error }, ++ { "rmdir", f_rmdir }, ++ { "chdir", f_chdir }, ++ { "mkdir", f_mkdir }, ++ { "list_dir", f_list_dir }, ++ { "absolute_path", f_absolute_path }, ++ { "get_file_info", f_get_file_info }, ++ { "get_clipboard", f_get_clipboard }, ++ { "set_clipboard", f_set_clipboard }, ++ { "get_primary_selection", f_get_primary_selection }, ++ { "set_primary_selection", f_set_primary_selection }, ++ { "get_process_id", f_get_process_id }, ++ { "get_time", f_get_time }, ++ { "sleep", f_sleep }, ++ { "exec", f_exec }, ++ { "fuzzy_match", f_fuzzy_match }, ++ { "set_window_opacity", f_set_window_opacity }, ++ { "load_native_plugin", f_load_native_plugin }, ++ { "path_compare", f_path_compare }, ++ { "get_fs_type", f_get_fs_type }, ++ { "text_input", f_text_input }, ++ { "setenv", f_setenv }, + { NULL, NULL } + }; + diff --git a/tasks/lite-xl__lite-xl-1729/solution/solve.sh b/tasks/lite-xl__lite-xl-1729/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/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/lite-xl__lite-xl-1729/task.toml b/tasks/lite-xl__lite-xl-1729/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3aa73e7c28dfb0f3cbdec180a64d5774d26a2606 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1729" +description = "Add primary selection support" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "03b8c239dcac7134d5d142f22e79874d3cd9d87e" +reference = "https://github.com/lite-xl/lite-xl/pull/1729" +source_access = "auto" +built_at = "2026-11-16T16:09:56.346178+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5cbb1dae9afbac510a4c2e7d5bc7f0681f451fc4ea526338a80792e57050385a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-09-13T17:31:15Z" +diff_format = "unified" +context_files = [ + "data/core/commands/doc.lua", + "data/core/keymap.lua", + "docs/api/system.lua", + "src/api/system.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 138 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.294059+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f35f43933162ef3d93393fff59818484adf3c2864c90fc8c1740c7833a331cd6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1729/tests/capture.py b/tasks/lite-xl__lite-xl-1729/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/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/lite-xl__lite-xl-1729/tests/instruction.md b/tasks/lite-xl__lite-xl-1729/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4bc7f655952469d8e902d09a343b78bc03a1bbb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Add primary selection support + +## Description + +For now this is only added for semi-explicit user actions, so plugins setting selections will not update the primary selection. +This is useful for cases like the type-ahead of the command palette, where we actually don't want to set the primary selection to the selected part. + +Let me know if I missed some actions. + +This is semi-disabled for Windows, as primary selection isn't supported there. +Does macOS support it? + +Testing on Windows and macOS is welcome. + +Testing the behavior with multi-selections is also welcome. + +This supersedes the `primary_selection` plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03b8c239dcac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1729/tests/oracle.patch b/tasks/lite-xl__lite-xl-1729/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c2fd9effae0e58b4f886678c55138f0ab4a7cc8d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/tests/oracle.patch @@ -0,0 +1,231 @@ +diff --git a/data/core/commands/doc.lua b/data/core/commands/doc.lua +index 65c92e28..66e88eea 100644 +--- a/data/core/commands/doc.lua ++++ b/data/core/commands/doc.lua +@@ -93,6 +93,13 @@ local function cut_or_copy(delete) + system.set_clipboard(full_text) + end + ++local function set_primary_selection(doc) ++ -- Doesn't work on Windows, so avoid spending time getting the text ++ if PLATFORM ~= "Windows" then ++ system.set_primary_selection(doc:get_selection_text()) ++ end ++end ++ + local function split_cursor(dv, direction) + local new_cursors = {} + local dv_translate = direction < 0 +@@ -297,6 +304,15 @@ local commands = { + end + end, + ++ ["doc:paste-primary-selection"] = function(dv, x, y) ++ if type(x) == "number" and type(y) == "number" then ++ set_cursor(dv, x, y, "set") ++ -- Workaround to avoid that a middle mouse drag starts selecting ++ dv.mouse_selecting = nil ++ end ++ dv.doc:text_input(system.get_primary_selection() or "") ++ end, ++ + ["doc:newline"] = function(dv) + for idx, line, col in dv.doc:get_selections(false, true) do + local indent = dv.doc.lines[line]:match("^[\t ]*") +@@ -353,6 +369,7 @@ local commands = { + + ["doc:select-all"] = function(dv) + dv.doc:set_selection(1, 1, math.huge, math.huge) ++ set_primary_selection(dv.doc) + -- avoid triggering DocView:scroll_to_make_visible + dv.last_line1 = 1 + dv.last_col1 = 1 +@@ -365,6 +382,7 @@ local commands = { + append_line_if_last_line(line2) + dv.doc:set_selections(idx, line2 + 1, 1, line1, 1) + end ++ set_primary_selection(dv.doc) + end, + + ["doc:select-word"] = function(dv) +@@ -373,6 +391,7 @@ local commands = { + local line2, col2 = translate.end_of_word(dv.doc, line1, col1) + dv.doc:set_selections(idx, line2, col2, line1, col1) + end ++ set_primary_selection(dv.doc) + end, + + ["doc:join-lines"] = function(dv) +@@ -626,6 +645,7 @@ local commands = { + local line2, col2 = dv:resolve_screen_position(x, y) + dv.mouse_selecting = { line1, col1, nil } + dv.doc:set_selection(line2, col2, line1, col1) ++ set_primary_selection(dv.doc) + end, + + ["doc:create-cursor-previous-line"] = function(dv) +@@ -696,9 +716,16 @@ local translations = { + } + + for name, obj in pairs(translations) do +- commands["doc:move-to-" .. name] = function(dv) dv.doc:move_to(obj[name:gsub("-", "_")], dv) end +- commands["doc:select-to-" .. name] = function(dv) dv.doc:select_to(obj[name:gsub("-", "_")], dv) end +- commands["doc:delete-to-" .. name] = function(dv) dv.doc:delete_to(obj[name:gsub("-", "_")], dv) end ++ commands["doc:move-to-" .. name] = function(dv) ++ dv.doc:move_to(obj[name:gsub("-", "_")], dv) ++ end ++ commands["doc:select-to-" .. name] = function(dv) ++ dv.doc:select_to(obj[name:gsub("-", "_")], dv) ++ set_primary_selection(dv.doc) ++ end ++ commands["doc:delete-to-" .. name] = function(dv) ++ dv.doc:delete_to(obj[name:gsub("-", "_")], dv) ++ end + end + + commands["doc:move-to-previous-char"] = function(dv) +diff --git a/data/core/keymap.lua b/data/core/keymap.lua +index 9f19cfb7..844a97e9 100644 +--- a/data/core/keymap.lua ++++ b/data/core/keymap.lua +@@ -393,6 +393,7 @@ keymap.add_direct { + ["1lclick"] = "doc:set-cursor", + ["2lclick"] = { "doc:set-cursor-word", "emptyview:new-doc", "tabbar:new-doc" }, + ["3lclick"] = "doc:set-cursor-line", ++ ["mclick"] = "doc:paste-primary-selection", + ["shift+left"] = "doc:select-to-previous-char", + ["shift+right"] = "doc:select-to-next-char", + ["shift+up"] = "doc:select-to-previous-line", +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 792fa623..8894a795 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -255,6 +255,18 @@ function system.get_clipboard() end + ---@param text string + function system.set_clipboard(text) end + ++--- ++---Retrieve the text currently stored in the primary selection. ++--- ++---@return string ++function system.get_primary_selection() end ++ ++--- ++---Set the content of the primary selection. ++--- ++---@param text string ++function system.set_primary_selection(text) end ++ + --- + ---Get the process id of lite-xl itself. + --- +diff --git a/src/api/system.c b/src/api/system.c +index b13a7754..b5aa4126 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -843,6 +843,28 @@ static int f_set_clipboard(lua_State *L) { + } + + ++static int f_get_primary_selection(lua_State *L) { ++#if SDL_VERSION_ATLEAST(2, 26, 0) ++ char *text = SDL_GetPrimarySelectionText(); ++ if (!text) { return 0; } ++ lua_pushstring(L, text); ++ SDL_free(text); ++ return 1; ++#else ++ return 0; ++#endif ++} ++ ++ ++static int f_set_primary_selection(lua_State *L) { ++#if SDL_VERSION_ATLEAST(2, 26, 0) ++ const char *text = luaL_checkstring(L, 1); ++ SDL_SetPrimarySelectionText(text); ++#endif ++ return 0; ++} ++ ++ + static int f_get_process_id(lua_State *L) { + #ifdef _WIN32 + lua_pushinteger(L, GetCurrentProcessId()); +@@ -1172,40 +1194,42 @@ static int f_setenv(lua_State* L) { + + + static const luaL_Reg lib[] = { +- { "poll_event", f_poll_event }, +- { "wait_event", f_wait_event }, +- { "set_cursor", f_set_cursor }, +- { "set_window_title", f_set_window_title }, +- { "set_window_mode", f_set_window_mode }, +- { "get_window_mode", f_get_window_mode }, +- { "set_window_bordered", f_set_window_bordered }, +- { "set_window_hit_test", f_set_window_hit_test }, +- { "get_window_size", f_get_window_size }, +- { "set_window_size", f_set_window_size }, +- { "set_text_input_rect", f_set_text_input_rect }, +- { "clear_ime", f_clear_ime }, +- { "window_has_focus", f_window_has_focus }, +- { "raise_window", f_raise_window }, +- { "show_fatal_error", f_show_fatal_error }, +- { "rmdir", f_rmdir }, +- { "chdir", f_chdir }, +- { "mkdir", f_mkdir }, +- { "list_dir", f_list_dir }, +- { "absolute_path", f_absolute_path }, +- { "get_file_info", f_get_file_info }, +- { "get_clipboard", f_get_clipboard }, +- { "set_clipboard", f_set_clipboard }, +- { "get_process_id", f_get_process_id }, +- { "get_time", f_get_time }, +- { "sleep", f_sleep }, +- { "exec", f_exec }, +- { "fuzzy_match", f_fuzzy_match }, +- { "set_window_opacity", f_set_window_opacity }, +- { "load_native_plugin", f_load_native_plugin }, +- { "path_compare", f_path_compare }, +- { "get_fs_type", f_get_fs_type }, +- { "text_input", f_text_input }, +- { "setenv", f_setenv }, ++ { "poll_event", f_poll_event }, ++ { "wait_event", f_wait_event }, ++ { "set_cursor", f_set_cursor }, ++ { "set_window_title", f_set_window_title }, ++ { "set_window_mode", f_set_window_mode }, ++ { "get_window_mode", f_get_window_mode }, ++ { "set_window_bordered", f_set_window_bordered }, ++ { "set_window_hit_test", f_set_window_hit_test }, ++ { "get_window_size", f_get_window_size }, ++ { "set_window_size", f_set_window_size }, ++ { "set_text_input_rect", f_set_text_input_rect }, ++ { "clear_ime", f_clear_ime }, ++ { "window_has_focus", f_window_has_focus }, ++ { "raise_window", f_raise_window }, ++ { "show_fatal_error", f_show_fatal_error }, ++ { "rmdir", f_rmdir }, ++ { "chdir", f_chdir }, ++ { "mkdir", f_mkdir }, ++ { "list_dir", f_list_dir }, ++ { "absolute_path", f_absolute_path }, ++ { "get_file_info", f_get_file_info }, ++ { "get_clipboard", f_get_clipboard }, ++ { "set_clipboard", f_set_clipboard }, ++ { "get_primary_selection", f_get_primary_selection }, ++ { "set_primary_selection", f_set_primary_selection }, ++ { "get_process_id", f_get_process_id }, ++ { "get_time", f_get_time }, ++ { "sleep", f_sleep }, ++ { "exec", f_exec }, ++ { "fuzzy_match", f_fuzzy_match }, ++ { "set_window_opacity", f_set_window_opacity }, ++ { "load_native_plugin", f_load_native_plugin }, ++ { "path_compare", f_path_compare }, ++ { "get_fs_type", f_get_fs_type }, ++ { "text_input", f_text_input }, ++ { "setenv", f_setenv }, + { NULL, NULL } + }; + diff --git a/tasks/lite-xl__lite-xl-1729/tests/test.sh b/tasks/lite-xl__lite-xl-1729/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9212de34fdc3fb387402f2eb9f0f3b863112c7f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/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 03b8c239dcac7134d5d142f22e79874d3cd9d87e > "$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/lite-xl__lite-xl-1729/tests/verifier.py b/tasks/lite-xl__lite-xl-1729/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1729/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/lite-xl__lite-xl-1739/environment/Dockerfile b/tasks/lite-xl__lite-xl-1739/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6d1debd4f9eb2489ef89384b1db04030db64d37d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2c1dc93d9d201f06bb5311eb3b4a981a10c7ed0e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2c1dc93d9d201f06bb5311eb3b4a981a10c7ed0e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2c1dc93d9d201f06bb5311eb3b4a981a10c7ed0e \ + && 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/lite-xl__lite-xl-1739/instruction.md b/tasks/lite-xl__lite-xl-1739/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6292db09e25a8a4739eb28d2e769d946372c5ae --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** scripts: not hardcode MSYSTEM + +## Description + +Various parts of the script hardcodes `MSYSTEM`. This means once you switched MINGW64 out for something like UCRT64 hell breaks loose. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c1dc93d9d20`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1739/solution/patch.diff b/tasks/lite-xl__lite-xl-1739/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a5ced01b4ad14b641742fcbff4b030830cf8c5bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/scripts/common.sh b/scripts/common.sh +index 14402138..831fee1b 100644 +--- a/scripts/common.sh ++++ b/scripts/common.sh +@@ -77,11 +77,17 @@ get_platform_arch() { + platform=$(get_platform_name) + arch=${CROSS_ARCH:-$(uname -m)} + if [[ $MSYSTEM != "" ]]; then +- if [[ $MSYSTEM == "MINGW64" ]]; then ++ case "$MSYSTEM" in ++ MINGW64|UCRT64|CLANG64) + arch=x86_64 +- else ++ ;; ++ MINGW32|CLANG32) + arch=i686 +- fi ++ ;; ++ CLANGARM64) ++ arch=aarch64 ++ ;; ++ esac + fi + echo "$arch" + } +diff --git a/scripts/innosetup/innosetup.iss.in b/scripts/innosetup/innosetup.iss.in +index c1300793..e15d9631 100644 +--- a/scripts/innosetup/innosetup.iss.in ++++ b/scripts/innosetup/innosetup.iss.in +@@ -26,12 +26,16 @@ AppPublisherURL={#MyAppURL} + AppSupportURL={#MyAppURL} + AppUpdatesURL={#MyAppURL} + +-#if Arch=="x64" +- ArchitecturesAllowed=x64 +- ArchitecturesInstallIn64BitMode=x64 +- #define ArchInternal "x86_64" +-#else ++#if Arch=="x86" + #define ArchInternal "i686" ++#else ++ ArchitecturesAllowed={#Arch} ++ ArchitecturesInstallIn64BitMode={#Arch} ++ #if Arch=="x64" ++ #define ArchInternal "x86_64" ++ #elif Arch=="arm64" ++ #define ArchInternal "aarch64" ++ #endif + #endif + + AllowNoIcons=yes +diff --git a/scripts/innosetup/innosetup.sh b/scripts/innosetup/innosetup.sh +index a37a2836..86ab89d1 100644 +--- a/scripts/innosetup/innosetup.sh ++++ b/scripts/innosetup/innosetup.sh +@@ -29,13 +29,24 @@ main() { + local version + local output + +- if [[ $MSYSTEM == "MINGW64" ]]; then ++ case "$MSYSTEM" in ++ MINGW64|UCRT64|CLANG64) + arch=x64 + arch_file=x86_64 +- else +- arch=i686; ++ ;; ++ MINGW32|CLANG32) ++ arch=x86 + arch_file=i686 +- fi ++ ;; ++ CLANGARM64) ++ arch=arm64 ++ arch_file=aarch64 ++ ;; ++ *) ++ echo "error: unsupported MSYSTEM type: $MSYSTEM" ++ exit 1 ++ ;; ++ esac + + initial_arg_count=$# + +diff --git a/scripts/package.sh b/scripts/package.sh +index d9a9c14c..46d6c231 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -213,14 +213,18 @@ main() { + if [[ $platform == "windows" ]]; then + exe_file="${exe_file}.exe" + stripcmd="strip --strip-all" +- # Copy MinGW libraries dependencies. +- # MSYS2 ldd command seems to be only 64bit, so use ntldd +- # see https://github.com/msys2/MINGW-packages/issues/4164 +- ntldd -R "${exe_file}" \ +- | grep mingw \ +- | awk '{print $3}' \ +- | sed 's#\\#/#g' \ +- | xargs -I '{}' cp -v '{}' "$(pwd)/${dest_dir}/" ++ if command -v ntldd >/dev/null 2>&1; then ++ # Copy MinGW libraries dependencies. ++ # MSYS2 ldd command seems to be only 64bit, so use ntldd ++ # see https://github.com/msys2/MINGW-packages/issues/4164 ++ ntldd -R "${exe_file}" \ ++ | grep mingw \ ++ | awk '{print $3}' \ ++ | sed 's#\\#/#g' \ ++ | xargs -I '{}' cp -v '{}' "$(pwd)/${dest_dir}/" ++ else ++ echo "WARNING: ntldd not found; assuming program is static" ++ fi + else + # Windows archive is always portable + package_name+="-portable" diff --git a/tasks/lite-xl__lite-xl-1739/solution/solve.sh b/tasks/lite-xl__lite-xl-1739/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/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/lite-xl__lite-xl-1739/task.toml b/tasks/lite-xl__lite-xl-1739/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0d3700fb16ad8fddfd4e5d2873963255cddc48de --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1739" +description = "scripts: not hardcode MSYSTEM" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "2c1dc93d9d201f06bb5311eb3b4a981a10c7ed0e" +reference = "https://github.com/lite-xl/lite-xl/pull/1739" +source_access = "auto" +built_at = "2026-11-16T16:09:56.208402+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ae94a5dc1678d469bdec3b39cb918b6574bad37fc73fbe158255e91eb2e5463d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-03-07T00:21:46Z" +diff_format = "unified" +context_files = [ + "scripts/common.sh", + "scripts/innosetup/innosetup.iss.in", + "scripts/innosetup/innosetup.sh", + "scripts/package.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 65 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.294516+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9cc5e4b1f5f000455190e3360a23ced9fc1fc6f700dd32134769a01e93ebb1fa" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1739/tests/capture.py b/tasks/lite-xl__lite-xl-1739/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/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/lite-xl__lite-xl-1739/tests/instruction.md b/tasks/lite-xl__lite-xl-1739/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6292db09e25a8a4739eb28d2e769d946372c5ae --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** scripts: not hardcode MSYSTEM + +## Description + +Various parts of the script hardcodes `MSYSTEM`. This means once you switched MINGW64 out for something like UCRT64 hell breaks loose. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c1dc93d9d20`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1739/tests/oracle.patch b/tasks/lite-xl__lite-xl-1739/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a5ced01b4ad14b641742fcbff4b030830cf8c5bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/scripts/common.sh b/scripts/common.sh +index 14402138..831fee1b 100644 +--- a/scripts/common.sh ++++ b/scripts/common.sh +@@ -77,11 +77,17 @@ get_platform_arch() { + platform=$(get_platform_name) + arch=${CROSS_ARCH:-$(uname -m)} + if [[ $MSYSTEM != "" ]]; then +- if [[ $MSYSTEM == "MINGW64" ]]; then ++ case "$MSYSTEM" in ++ MINGW64|UCRT64|CLANG64) + arch=x86_64 +- else ++ ;; ++ MINGW32|CLANG32) + arch=i686 +- fi ++ ;; ++ CLANGARM64) ++ arch=aarch64 ++ ;; ++ esac + fi + echo "$arch" + } +diff --git a/scripts/innosetup/innosetup.iss.in b/scripts/innosetup/innosetup.iss.in +index c1300793..e15d9631 100644 +--- a/scripts/innosetup/innosetup.iss.in ++++ b/scripts/innosetup/innosetup.iss.in +@@ -26,12 +26,16 @@ AppPublisherURL={#MyAppURL} + AppSupportURL={#MyAppURL} + AppUpdatesURL={#MyAppURL} + +-#if Arch=="x64" +- ArchitecturesAllowed=x64 +- ArchitecturesInstallIn64BitMode=x64 +- #define ArchInternal "x86_64" +-#else ++#if Arch=="x86" + #define ArchInternal "i686" ++#else ++ ArchitecturesAllowed={#Arch} ++ ArchitecturesInstallIn64BitMode={#Arch} ++ #if Arch=="x64" ++ #define ArchInternal "x86_64" ++ #elif Arch=="arm64" ++ #define ArchInternal "aarch64" ++ #endif + #endif + + AllowNoIcons=yes +diff --git a/scripts/innosetup/innosetup.sh b/scripts/innosetup/innosetup.sh +index a37a2836..86ab89d1 100644 +--- a/scripts/innosetup/innosetup.sh ++++ b/scripts/innosetup/innosetup.sh +@@ -29,13 +29,24 @@ main() { + local version + local output + +- if [[ $MSYSTEM == "MINGW64" ]]; then ++ case "$MSYSTEM" in ++ MINGW64|UCRT64|CLANG64) + arch=x64 + arch_file=x86_64 +- else +- arch=i686; ++ ;; ++ MINGW32|CLANG32) ++ arch=x86 + arch_file=i686 +- fi ++ ;; ++ CLANGARM64) ++ arch=arm64 ++ arch_file=aarch64 ++ ;; ++ *) ++ echo "error: unsupported MSYSTEM type: $MSYSTEM" ++ exit 1 ++ ;; ++ esac + + initial_arg_count=$# + +diff --git a/scripts/package.sh b/scripts/package.sh +index d9a9c14c..46d6c231 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -213,14 +213,18 @@ main() { + if [[ $platform == "windows" ]]; then + exe_file="${exe_file}.exe" + stripcmd="strip --strip-all" +- # Copy MinGW libraries dependencies. +- # MSYS2 ldd command seems to be only 64bit, so use ntldd +- # see https://github.com/msys2/MINGW-packages/issues/4164 +- ntldd -R "${exe_file}" \ +- | grep mingw \ +- | awk '{print $3}' \ +- | sed 's#\\#/#g' \ +- | xargs -I '{}' cp -v '{}' "$(pwd)/${dest_dir}/" ++ if command -v ntldd >/dev/null 2>&1; then ++ # Copy MinGW libraries dependencies. ++ # MSYS2 ldd command seems to be only 64bit, so use ntldd ++ # see https://github.com/msys2/MINGW-packages/issues/4164 ++ ntldd -R "${exe_file}" \ ++ | grep mingw \ ++ | awk '{print $3}' \ ++ | sed 's#\\#/#g' \ ++ | xargs -I '{}' cp -v '{}' "$(pwd)/${dest_dir}/" ++ else ++ echo "WARNING: ntldd not found; assuming program is static" ++ fi + else + # Windows archive is always portable + package_name+="-portable" diff --git a/tasks/lite-xl__lite-xl-1739/tests/test.sh b/tasks/lite-xl__lite-xl-1739/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec1078a795d557f29850748a6b1ffd970ef73902 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/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 2c1dc93d9d201f06bb5311eb3b4a981a10c7ed0e > "$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/lite-xl__lite-xl-1739/tests/verifier.py b/tasks/lite-xl__lite-xl-1739/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1739/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/lite-xl__lite-xl-1740/environment/Dockerfile b/tasks/lite-xl__lite-xl-1740/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1740/instruction.md b/tasks/lite-xl__lite-xl-1740/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa1517be971c01fb3cc63e3662dd6f75243bc2a7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix multi-type usage in delimited patterns + +## Description + +In the "end" pattern we weren't considering the multiple types. + +~~Creating as draft as I need to check some more cases.~~ + +Example: +Using +```lua +local syntax = require "core.syntax" +syntax.add({ + name = "test", + files = { "%.TEST$" }, + patterns = { + { pattern = { "hello()", "world()123" }, type = { "string", "number" } }, + { pattern = "[^h]+", type = "comment" } + }, + symbols = {} +}) +``` + +Before: +![Schermata del 2024-04-15 10-03-23](https://github.com/lite-xl/lite-xl/assets/2798487/39b930ba-d572-47fc-925c-88e2df199344) + +After: +![Schermata del 2024-04-15 10-02-50](https://github.com/lite-xl/lite-xl/assets/2798487/05987c83-0695-4be4-bdc2-e4a9f840714e) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1740/solution/patch.diff b/tasks/lite-xl__lite-xl-1740/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7ceabfdfda6f77594ac7c0c44a4efdd6395fa10c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/data/core/tokenizer.lua b/data/core/tokenizer.lua +index 7e83249f..76ebe72c 100644 +--- a/data/core/tokenizer.lua ++++ b/data/core/tokenizer.lua +@@ -282,7 +282,8 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + -- continue trying to match the end pattern of a pair if we have a state set + if current_pattern_idx > 0 then + local p = current_syntax.patterns[current_pattern_idx] +- local s, e = find_text(text, p, i, false, true) ++ local find_results = { find_text(text, p, i, false, true) } ++ local s, e = find_results[1], find_results[2] + -- Use the first token type specified in the type table for the "middle" + -- part of the subsyntax. + local token_type = type(p.type) == "table" and p.type[1] or p.type +@@ -307,7 +308,12 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + -- continue on as normal. + if cont then + if s then +- push_token(res, token_type, text:usub(i, e)) ++ -- Push remaining token before the end delimiter ++ if s > i then ++ push_token(res, token_type, text:usub(i, s - 1)) ++ end ++ -- Push the end delimiter ++ push_tokens(res, current_syntax, p, text, find_results) + set_subsyntax_pattern_idx(0) + i = e + 1 + else diff --git a/tasks/lite-xl__lite-xl-1740/solution/solve.sh b/tasks/lite-xl__lite-xl-1740/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/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/lite-xl__lite-xl-1740/task.toml b/tasks/lite-xl__lite-xl-1740/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3534482ddfc55d2c908ab0f7aea565fc50c20867 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1740" +description = "Fix multi-type usage in delimited patterns" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1740" +source_access = "auto" +built_at = "2026-11-16T16:09:56.334720+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:286f7e974850bed80abb462f79ef87f4bf8dc5e4af0b4610a517ad51d2b07d25" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T16:33:01Z" +diff_format = "unified" +context_files = [ + "data/core/tokenizer.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.294964+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1740/tests/capture.py b/tasks/lite-xl__lite-xl-1740/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/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/lite-xl__lite-xl-1740/tests/instruction.md b/tasks/lite-xl__lite-xl-1740/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa1517be971c01fb3cc63e3662dd6f75243bc2a7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** Fix multi-type usage in delimited patterns + +## Description + +In the "end" pattern we weren't considering the multiple types. + +~~Creating as draft as I need to check some more cases.~~ + +Example: +Using +```lua +local syntax = require "core.syntax" +syntax.add({ + name = "test", + files = { "%.TEST$" }, + patterns = { + { pattern = { "hello()", "world()123" }, type = { "string", "number" } }, + { pattern = "[^h]+", type = "comment" } + }, + symbols = {} +}) +``` + +Before: +![Schermata del 2024-04-15 10-03-23](https://github.com/lite-xl/lite-xl/assets/2798487/39b930ba-d572-47fc-925c-88e2df199344) + +After: +![Schermata del 2024-04-15 10-02-50](https://github.com/lite-xl/lite-xl/assets/2798487/05987c83-0695-4be4-bdc2-e4a9f840714e) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1740/tests/oracle.patch b/tasks/lite-xl__lite-xl-1740/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7ceabfdfda6f77594ac7c0c44a4efdd6395fa10c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/data/core/tokenizer.lua b/data/core/tokenizer.lua +index 7e83249f..76ebe72c 100644 +--- a/data/core/tokenizer.lua ++++ b/data/core/tokenizer.lua +@@ -282,7 +282,8 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + -- continue trying to match the end pattern of a pair if we have a state set + if current_pattern_idx > 0 then + local p = current_syntax.patterns[current_pattern_idx] +- local s, e = find_text(text, p, i, false, true) ++ local find_results = { find_text(text, p, i, false, true) } ++ local s, e = find_results[1], find_results[2] + -- Use the first token type specified in the type table for the "middle" + -- part of the subsyntax. + local token_type = type(p.type) == "table" and p.type[1] or p.type +@@ -307,7 +308,12 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + -- continue on as normal. + if cont then + if s then +- push_token(res, token_type, text:usub(i, e)) ++ -- Push remaining token before the end delimiter ++ if s > i then ++ push_token(res, token_type, text:usub(i, s - 1)) ++ end ++ -- Push the end delimiter ++ push_tokens(res, current_syntax, p, text, find_results) + set_subsyntax_pattern_idx(0) + i = e + 1 + else diff --git a/tasks/lite-xl__lite-xl-1740/tests/test.sh b/tasks/lite-xl__lite-xl-1740/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1740/tests/verifier.py b/tasks/lite-xl__lite-xl-1740/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1740/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/lite-xl__lite-xl-1774/environment/Dockerfile b/tasks/lite-xl__lite-xl-1774/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..99bb27380a7e4fa257641a52f1d481de822df8d8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7fdb35ac465e3433721722143ca2eb556cdd0252 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7fdb35ac465e3433721722143ca2eb556cdd0252 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7fdb35ac465e3433721722143ca2eb556cdd0252 \ + && 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/lite-xl__lite-xl-1774/instruction.md b/tasks/lite-xl__lite-xl-1774/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39cf9e713e35274957955eead79f70e7aa9534ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Generate release notes + +## Description + +I know we probably don't do this as often, but it helps to have a template to keep the release notes consistent. + +This PR autogenerates a release notes based on the current tag. Some info needs to be filled up manually, such as the description and changelogs, but it fills up the version tags automatically. +This will make it ever more easier to create consistent release notes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fdb35ac465e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1774/solution/patch.diff b/tasks/lite-xl__lite-xl-1774/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..40a963c2fe6a78a7bd0c00c7ee5416635ea6cb9c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/solution/patch.diff @@ -0,0 +1,190 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 4a276bf5..a1786c9d 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -24,6 +24,8 @@ jobs: + steps: + - name: Checkout code + uses: actions/checkout@v3 ++ with: ++ fetch-depth: 0 + - name: Fetch Version + id: tag + run: | +@@ -38,6 +40,8 @@ jobs: + tag_name: ${{ steps.tag.outputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ - name: Generate Release Notes ++ run: bash scripts/generate-release-notes.sh --version ${{ steps.tag.outputs.version }} + - name: Create Release + id: create_release + uses: softprops/action-gh-release@v1 +@@ -45,8 +49,7 @@ jobs: + tag_name: ${{ steps.tag.outputs.version }} + name: Lite XL ${{ steps.tag.outputs.version }} + draft: true +- body_path: changelog.md +- generate_release_notes: true ++ body_path: release-notes.md + + build_linux: + name: Linux +diff --git a/resources/README.md b/resources/README.md +index d6d80eec..07969749 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -8,6 +8,7 @@ This folder contains resources that is used for building or packaging the projec + + ### Packaging + ++- `release-notes.md`: lite-xl release note template, used with `envsubst`. + - `icons/icon.{icns,ico,inl,rc,svg}`: lite-xl icon in various formats. + - `linux/com.lite_xl.LiteXL.appdata.xml`: AppStream metadata. + - `linux/com.lite_xl.LiteXL.desktop`: Desktop file for Linux desktops. +diff --git a/resources/release-notes.md b/resources/release-notes.md +new file mode 100644 +index 00000000..a1690b4b +--- /dev/null ++++ b/resources/release-notes.md +@@ -0,0 +1,39 @@ ++ ++ ++## Downloads ++ ++- Windows (Setup): [32-bit][win32-setup], [64-bit][win64-setup] ++- Linux (64-bit): [AppImage][linux64-appimage], [tarball][linux64-tarball] ++- macOS: [Universal][mac-dmg], [Intel][macintel-dmg], [Apple Silicon][macarm-dmg] ++ ++Other downloads such as ZIP files for Windows and lightweight releases are available below. ++ ++For OS requirements, please refer to the relevant section in the [README]. ++ ++## New Features ++ ++ ++ ++### Fixes ++ ++ ++ ++### Other Changes ++ ++ ++ ++Please go to [changelog.md] for detailed description of all the changes. ++ ++ ++**Commits since last version**: https://github.com/lite-xl/lite-xl/compare/v2.1.3...${RELEASE_TAG} ++ ++ ++[win32-setup]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-i686-setup.exe ++[win64-setup]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-x86_64-setup.exe ++[linux64-appimage]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-x86_64.AppImage ++[linux64-tarball]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-addons-linux-x86_64-portable.tar.gz ++[mac-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-universal.dmg ++[macintel-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-x86_64.dmg ++[macarm-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-arm64.dmg ++[README]: https://github.com/lite-xl/lite-xl?tab=readme-ov-file#installing-prebuilt ++[changelog]: https://github.com/lite-xl/lite-xl/blob/${RELEASE_TAG}/changelog.md +diff --git a/scripts/README.md b/scripts/README.md +index 5910931c..36e35479 100644 +--- a/scripts/README.md ++++ b/scripts/README.md +@@ -17,13 +17,14 @@ Various scripts and configurations used to configure, build, and package Lite XL + + ### Utility + +-- **common.sh**: Common functions used by other scripts. +-- **install-dependencies.sh**: Installs required applications to build, package +- and run Lite XL, mainly useful for CI and documentation purpose. +- Preferably not to be used in user systems. +-- **fontello-config.json**: Used by the icons generator. +-- **generate_header.sh**: Generates a header file for native plugin API +-- **keymap-generator**: Generates a JSON file containing the keymap ++- **common.sh**: Common functions used by other scripts. ++- **install-dependencies.sh**: Installs required applications to build, package ++ and run Lite XL, mainly useful for CI and documentation purpose. ++ Preferably not to be used in user systems. ++- **fontello-config.json**: Used by the icons generator. ++- **generate_header.sh**: Generates a header file for native plugin API ++- **keymap-generator**: Generates a JSON file containing the keymap ++- **generate-release-notes.sh**: Generates a release note for Lite XL releases. + + [1]: https://github.com/dmgbuild/dmgbuild + [2]: https://docs.appimage.org/ +diff --git a/scripts/generate-release-notes.sh b/scripts/generate-release-notes.sh +new file mode 100755 +index 00000000..da98a63b +--- /dev/null ++++ b/scripts/generate-release-notes.sh +@@ -0,0 +1,69 @@ ++#!/usr/bin/env bash ++ ++if [ ! -e "src/api/api.h" ]; then ++ echo "Please run this script from the root directory of Lite XL."; exit 1 ++fi ++ ++show_help() { ++ echo ++ echo "Release notes generator for lite-xl releases." ++ echo "USE IT AT YOUR OWN RISK!" ++ echo ++ echo "Usage: $0 " ++ echo ++ echo "Available options:" ++ echo ++ echo "--version Use this version instead of git tags or GitHub outputs." ++ echo "--debug Debug this script." ++ echo "--help Show this message." ++ echo ++} ++ ++main() { ++ local version ++ ++ for i in "$@"; do ++ case $i in ++ --debug) ++ set -x ++ shift ++ ;; ++ --help) ++ show_help ++ exit 0 ++ ;; ++ --version) ++ version="$2" ++ shift ++ shift ++ ;; ++ *) ++ # unknown option ++ ;; ++ esac ++ done ++ ++ if [[ -n $1 ]]; then ++ show_help ++ exit 0 ++ fi ++ ++ if [[ -z "$version" ]]; then ++ if [[ "$GITHUB_REF" == "refs/tags/"* ]]; then ++ version="${GITHUB_REF##*/}" ++ else ++ version="$(git describe --tags $(git rev-list --tags --max-count=1))" ++ if [[ $? -ne 0 ]]; then version=""; fi ++ fi ++ fi ++ ++ if [[ -z "$version" ]]; then ++ echo "error: cannot get latest git tag" ++ exit 1 ++ fi ++ ++ export RELEASE_TAG="$version" ++ envsubst '$RELEASE_TAG' > release-notes.md < resources/release-notes.md ++} ++ ++main "$@" diff --git a/tasks/lite-xl__lite-xl-1774/solution/solve.sh b/tasks/lite-xl__lite-xl-1774/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/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/lite-xl__lite-xl-1774/task.toml b/tasks/lite-xl__lite-xl-1774/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..63a2593c8755475115cc934cc99b7fc1243681fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1774" +description = "Generate release notes" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7fdb35ac465e3433721722143ca2eb556cdd0252" +reference = "https://github.com/lite-xl/lite-xl/pull/1774" +source_access = "auto" +built_at = "2026-11-16T16:09:56.223702+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:42dc8443a84ef5366609ab393b76d7d842195ee1b19f693cfe8290024b784cbd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-05-17T23:12:04Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.yml", + "resources/README.md", + "resources/release-notes.md", + "scripts/README.md", + "scripts/generate-release-notes.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 131 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.295445+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f91d2f61f495288fbe6bdf577ce1ebbcba48d6f5f82a2bdcd40228203c26ea93" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1774/tests/capture.py b/tasks/lite-xl__lite-xl-1774/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/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/lite-xl__lite-xl-1774/tests/instruction.md b/tasks/lite-xl__lite-xl-1774/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39cf9e713e35274957955eead79f70e7aa9534ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** Generate release notes + +## Description + +I know we probably don't do this as often, but it helps to have a template to keep the release notes consistent. + +This PR autogenerates a release notes based on the current tag. Some info needs to be filled up manually, such as the description and changelogs, but it fills up the version tags automatically. +This will make it ever more easier to create consistent release notes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fdb35ac465e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1774/tests/oracle.patch b/tasks/lite-xl__lite-xl-1774/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..40a963c2fe6a78a7bd0c00c7ee5416635ea6cb9c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/tests/oracle.patch @@ -0,0 +1,190 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 4a276bf5..a1786c9d 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -24,6 +24,8 @@ jobs: + steps: + - name: Checkout code + uses: actions/checkout@v3 ++ with: ++ fetch-depth: 0 + - name: Fetch Version + id: tag + run: | +@@ -38,6 +40,8 @@ jobs: + tag_name: ${{ steps.tag.outputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ - name: Generate Release Notes ++ run: bash scripts/generate-release-notes.sh --version ${{ steps.tag.outputs.version }} + - name: Create Release + id: create_release + uses: softprops/action-gh-release@v1 +@@ -45,8 +49,7 @@ jobs: + tag_name: ${{ steps.tag.outputs.version }} + name: Lite XL ${{ steps.tag.outputs.version }} + draft: true +- body_path: changelog.md +- generate_release_notes: true ++ body_path: release-notes.md + + build_linux: + name: Linux +diff --git a/resources/README.md b/resources/README.md +index d6d80eec..07969749 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -8,6 +8,7 @@ This folder contains resources that is used for building or packaging the projec + + ### Packaging + ++- `release-notes.md`: lite-xl release note template, used with `envsubst`. + - `icons/icon.{icns,ico,inl,rc,svg}`: lite-xl icon in various formats. + - `linux/com.lite_xl.LiteXL.appdata.xml`: AppStream metadata. + - `linux/com.lite_xl.LiteXL.desktop`: Desktop file for Linux desktops. +diff --git a/resources/release-notes.md b/resources/release-notes.md +new file mode 100644 +index 00000000..a1690b4b +--- /dev/null ++++ b/resources/release-notes.md +@@ -0,0 +1,39 @@ ++ ++ ++## Downloads ++ ++- Windows (Setup): [32-bit][win32-setup], [64-bit][win64-setup] ++- Linux (64-bit): [AppImage][linux64-appimage], [tarball][linux64-tarball] ++- macOS: [Universal][mac-dmg], [Intel][macintel-dmg], [Apple Silicon][macarm-dmg] ++ ++Other downloads such as ZIP files for Windows and lightweight releases are available below. ++ ++For OS requirements, please refer to the relevant section in the [README]. ++ ++## New Features ++ ++ ++ ++### Fixes ++ ++ ++ ++### Other Changes ++ ++ ++ ++Please go to [changelog.md] for detailed description of all the changes. ++ ++ ++**Commits since last version**: https://github.com/lite-xl/lite-xl/compare/v2.1.3...${RELEASE_TAG} ++ ++ ++[win32-setup]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-i686-setup.exe ++[win64-setup]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-x86_64-setup.exe ++[linux64-appimage]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/LiteXL-${RELEASE_TAG}-addons-x86_64.AppImage ++[linux64-tarball]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-addons-linux-x86_64-portable.tar.gz ++[mac-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-universal.dmg ++[macintel-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-x86_64.dmg ++[macarm-dmg]: https://github.com/lite-xl/lite-xl/releases/download/${RELEASE_TAG}/lite-xl-${RELEASE_TAG}-macos-arm64.dmg ++[README]: https://github.com/lite-xl/lite-xl?tab=readme-ov-file#installing-prebuilt ++[changelog]: https://github.com/lite-xl/lite-xl/blob/${RELEASE_TAG}/changelog.md +diff --git a/scripts/README.md b/scripts/README.md +index 5910931c..36e35479 100644 +--- a/scripts/README.md ++++ b/scripts/README.md +@@ -17,13 +17,14 @@ Various scripts and configurations used to configure, build, and package Lite XL + + ### Utility + +-- **common.sh**: Common functions used by other scripts. +-- **install-dependencies.sh**: Installs required applications to build, package +- and run Lite XL, mainly useful for CI and documentation purpose. +- Preferably not to be used in user systems. +-- **fontello-config.json**: Used by the icons generator. +-- **generate_header.sh**: Generates a header file for native plugin API +-- **keymap-generator**: Generates a JSON file containing the keymap ++- **common.sh**: Common functions used by other scripts. ++- **install-dependencies.sh**: Installs required applications to build, package ++ and run Lite XL, mainly useful for CI and documentation purpose. ++ Preferably not to be used in user systems. ++- **fontello-config.json**: Used by the icons generator. ++- **generate_header.sh**: Generates a header file for native plugin API ++- **keymap-generator**: Generates a JSON file containing the keymap ++- **generate-release-notes.sh**: Generates a release note for Lite XL releases. + + [1]: https://github.com/dmgbuild/dmgbuild + [2]: https://docs.appimage.org/ +diff --git a/scripts/generate-release-notes.sh b/scripts/generate-release-notes.sh +new file mode 100755 +index 00000000..da98a63b +--- /dev/null ++++ b/scripts/generate-release-notes.sh +@@ -0,0 +1,69 @@ ++#!/usr/bin/env bash ++ ++if [ ! -e "src/api/api.h" ]; then ++ echo "Please run this script from the root directory of Lite XL."; exit 1 ++fi ++ ++show_help() { ++ echo ++ echo "Release notes generator for lite-xl releases." ++ echo "USE IT AT YOUR OWN RISK!" ++ echo ++ echo "Usage: $0 " ++ echo ++ echo "Available options:" ++ echo ++ echo "--version Use this version instead of git tags or GitHub outputs." ++ echo "--debug Debug this script." ++ echo "--help Show this message." ++ echo ++} ++ ++main() { ++ local version ++ ++ for i in "$@"; do ++ case $i in ++ --debug) ++ set -x ++ shift ++ ;; ++ --help) ++ show_help ++ exit 0 ++ ;; ++ --version) ++ version="$2" ++ shift ++ shift ++ ;; ++ *) ++ # unknown option ++ ;; ++ esac ++ done ++ ++ if [[ -n $1 ]]; then ++ show_help ++ exit 0 ++ fi ++ ++ if [[ -z "$version" ]]; then ++ if [[ "$GITHUB_REF" == "refs/tags/"* ]]; then ++ version="${GITHUB_REF##*/}" ++ else ++ version="$(git describe --tags $(git rev-list --tags --max-count=1))" ++ if [[ $? -ne 0 ]]; then version=""; fi ++ fi ++ fi ++ ++ if [[ -z "$version" ]]; then ++ echo "error: cannot get latest git tag" ++ exit 1 ++ fi ++ ++ export RELEASE_TAG="$version" ++ envsubst '$RELEASE_TAG' > release-notes.md < resources/release-notes.md ++} ++ ++main "$@" diff --git a/tasks/lite-xl__lite-xl-1774/tests/test.sh b/tasks/lite-xl__lite-xl-1774/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2cad2d119a773f7be1231ed8a2852f8182beda79 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/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 7fdb35ac465e3433721722143ca2eb556cdd0252 > "$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/lite-xl__lite-xl-1774/tests/verifier.py b/tasks/lite-xl__lite-xl-1774/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1774/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/lite-xl__lite-xl-1779/environment/Dockerfile b/tasks/lite-xl__lite-xl-1779/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9b5e9fe0a51e81345b600b10d48674638157e5a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efa257ddbdd9ade1cad588918c62f091493ccb1b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && 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/lite-xl__lite-xl-1779/instruction.md b/tasks/lite-xl__lite-xl-1779/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bce4a221eefa88f3064cc5858794749f938422ad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Better wasm support again + +## Description + +This PR makes wasm actually easy to set up. + +There are a few caveats: start.lua will not be templated by meson because of the bundle workaround, but other things do work. + +Also fixed PCRE2 wrap not using meson `feature` properly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1779/solution/patch.diff b/tasks/lite-xl__lite-xl-1779/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e424e0a16f2518d53fe9e358f907a193cd469ca9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/solution/patch.diff @@ -0,0 +1,194 @@ +diff --git a/resources/README.md b/resources/README.md +index 0e675d86..38429e6d 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -40,5 +40,9 @@ sips -s dpiWidth 144 -s dpiHeight 144 macos/background@2x.png + + `sips` and `tiffutil` are available by default on macOS. + ++### Other Files ++ ++- `shell.html`: A shell file for use with WASM builds. ++ + + [1]: https://mesonbuild.com/Cross-compilation.html +diff --git a/resources/cross/unknown-wasm32.txt b/resources/cross/unknown-wasm32.txt +index 7309d7bf..9c34b6d4 100644 +--- a/resources/cross/unknown-wasm32.txt ++++ b/resources/cross/unknown-wasm32.txt +@@ -1,15 +1,19 @@ +-# cross file for WASM. +-# use this file by running meson setup --cross-file resources/cross/wasm.txt ++# Cross file for WASM. ++# Use this file by running meson setup --cross-file resources/cross/wasm.txt ++# You can import other cross files after this one to override the options. + + [constants] + +-# a list of functions that can run without being asyncified; proceed with caution ++# A list of functions that can run without being asyncified; proceed with caution + asyncify_ignores = '["SDL_BlitScaled","SDL_UpperBlitScaled","SDL_MapRGB*","SDL_FillRect","SDL_FreeSurface","SDL_CreateRGBSurface","SDL_GetWindowSurface","SDL_PollEvent","SDL_CreateSystemCursor","SDL_SetWindowTitle","SDL_SetCursor","SDL_GetWindowSize","SDL_GetWindowPosition","lua_push*","lua_rawget*","luaL_check*","pcre2*","FT_*","Bezier_*","g_*","FT_*","ft_*","TT_*","tt_*","__*","*printf","gray_*","fopen","fclose","fread","fflush","qsort","sift"]' + +-# enable advising for optimizing the list above; disable this to prevent flooding logs ++# Enable advising for optimizing the list above; disable this to prevent flooding logs + asyncify_advise = '0' + +-# initial heap size in bytes; make sure it is not too low (around 64mb - 250mb) ++# Stack size for asyncify; increase this if you have problems with asyncify-induced crashes ++asyncify_stack_size = '6144' ++ ++# Initial heap size in bytes; make sure it is not too low (around 64mb - 250mb) + initial_heap = '104857600' + + # Emscripten is not always added to PATH. +@@ -17,6 +21,32 @@ initial_heap = '104857600' + # or supply a second machine file that defines this variable. + toolchain = '' + ++# The memory allocator to use. You shouldn't need to change this, ++# but other allocator might offer more performance at the cost of binary size. ++malloc_impl = 'emmalloc' ++ ++# Functions exported by the main module. ++# This is needed if you plan to load shared libraries which need symbols from the main binary. ++# e.g. stdout, stderr, fopen, etc. Use another cross file to override this value. ++exported_functions = '_main' ++ ++# Exported Filesystem modules. ++# For example, you can put '-lidbfs.js' to export IDBFS for later use. ++exported_filesystems = [] ++ ++# Exported JS values in Module. ++# This is needed to preserve symbols after tree shaking. ++exported_js_values = '[]' ++ ++# Extra link options passed to the linker. ++extra_link_options = [] ++ ++# In order to run Lite XL, you will also need to bundle the /data directory. ++# The following option is added to the linking process to bundle the /data directory. ++# If you want to do this manually or the automatic bundling process does not work, ++# comment out the following line. ++bundle_paths = ['--preload-file', '../data@/usr/share/lite-xl/'] ++ + + [binaries] + c = toolchain / 'emcc' +@@ -34,9 +64,9 @@ needs_exe_wrapper = true + + + [built-in options] +-c_args = [] ++c_args = ['-fPIC'] + c_link_args = [] +-cpp_args = [] ++cpp_args = ['-fPIC'] + cpp_link_args = [] + + +@@ -46,8 +76,11 @@ portable = true + arch_tuple = 'wasm32-unknown' + wrap_mode = 'nofallback' + force_fallback_for = 'lua,pcre2,freetype2' +-c_link_args = ['-s', 'ALLOW_MEMORY_GROWTH=1', '-s', 'INITIAL_MEMORY=' + initial_heap, '-s', 'ASYNCIFY=1', '-s', 'ASYNCIFY_ADVISE=' + asyncify_advise, '-s', 'ASYNCIFY_STACK_SIZE=6144', '-s', 'ASYNCIFY_REMOVE=' + asyncify_ignores, '-s', 'FORCE_FILESYSTEM=1', '-lidbfs.js'] ++c_link_args = ['-sALLOW_MEMORY_GROWTH=1', '-sINITIAL_MEMORY=' + initial_heap, '-sASYNCIFY', '-sASYNCIFY_ADVISE=' + asyncify_advise, '-sASYNCIFY_STACK_SIZE=' + asyncify_stack_size, '-sASYNCIFY_REMOVE=' + asyncify_ignores, '-sFORCE_FILESYSTEM=1', '-sEXIT_RUNTIME=1', '-sMALLOC=' + malloc_impl, '-sMAIN_MODULE=1', '-sEXPORTED_FUNCTIONS=' + exported_functions, '-sEXPORTED_RUNTIME_METHODS=' + exported_js_values] + extra_link_options + bundle_paths + exported_filesystems + ++[pcre2:project options] ++jit = 'disabled' ++jit_sealloc = 'disabled' + + [host_machine] + system = 'emscripten' +diff --git a/resources/shell.html b/resources/shell.html +new file mode 100644 +index 00000000..22c0c414 +--- /dev/null ++++ b/resources/shell.html +@@ -0,0 +1,87 @@ ++ ++ ++ ++ ++ ++ ++ ++ Lite XL ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ diff --git a/tasks/lite-xl__lite-xl-1779/solution/solve.sh b/tasks/lite-xl__lite-xl-1779/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/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/lite-xl__lite-xl-1779/task.toml b/tasks/lite-xl__lite-xl-1779/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..711ee8ace8b7ab74bb8fe126a8665c002053e84e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1779" +description = "Better wasm support again" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "efa257ddbdd9ade1cad588918c62f091493ccb1b" +reference = "https://github.com/lite-xl/lite-xl/pull/1779" +source_access = "auto" +built_at = "2026-11-16T16:09:56.207003+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:58c8ac101de6241d16450c7a1f9d03c447d68e81e3a635c95d1b6dd40cc16f77" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T14:35:56Z" +diff_format = "unified" +context_files = [ + "resources/README.md", + "resources/cross/unknown-wasm32.txt", + "resources/shell.html", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 140 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.295904+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e471019fc62f655a2609323e51e42ae2bc2456a7a8e3dcf0a0d756b495639e90" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1779/tests/capture.py b/tasks/lite-xl__lite-xl-1779/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/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/lite-xl__lite-xl-1779/tests/instruction.md b/tasks/lite-xl__lite-xl-1779/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bce4a221eefa88f3064cc5858794749f938422ad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Better wasm support again + +## Description + +This PR makes wasm actually easy to set up. + +There are a few caveats: start.lua will not be templated by meson because of the bundle workaround, but other things do work. + +Also fixed PCRE2 wrap not using meson `feature` properly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1779/tests/oracle.patch b/tasks/lite-xl__lite-xl-1779/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e424e0a16f2518d53fe9e358f907a193cd469ca9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/tests/oracle.patch @@ -0,0 +1,194 @@ +diff --git a/resources/README.md b/resources/README.md +index 0e675d86..38429e6d 100644 +--- a/resources/README.md ++++ b/resources/README.md +@@ -40,5 +40,9 @@ sips -s dpiWidth 144 -s dpiHeight 144 macos/background@2x.png + + `sips` and `tiffutil` are available by default on macOS. + ++### Other Files ++ ++- `shell.html`: A shell file for use with WASM builds. ++ + + [1]: https://mesonbuild.com/Cross-compilation.html +diff --git a/resources/cross/unknown-wasm32.txt b/resources/cross/unknown-wasm32.txt +index 7309d7bf..9c34b6d4 100644 +--- a/resources/cross/unknown-wasm32.txt ++++ b/resources/cross/unknown-wasm32.txt +@@ -1,15 +1,19 @@ +-# cross file for WASM. +-# use this file by running meson setup --cross-file resources/cross/wasm.txt ++# Cross file for WASM. ++# Use this file by running meson setup --cross-file resources/cross/wasm.txt ++# You can import other cross files after this one to override the options. + + [constants] + +-# a list of functions that can run without being asyncified; proceed with caution ++# A list of functions that can run without being asyncified; proceed with caution + asyncify_ignores = '["SDL_BlitScaled","SDL_UpperBlitScaled","SDL_MapRGB*","SDL_FillRect","SDL_FreeSurface","SDL_CreateRGBSurface","SDL_GetWindowSurface","SDL_PollEvent","SDL_CreateSystemCursor","SDL_SetWindowTitle","SDL_SetCursor","SDL_GetWindowSize","SDL_GetWindowPosition","lua_push*","lua_rawget*","luaL_check*","pcre2*","FT_*","Bezier_*","g_*","FT_*","ft_*","TT_*","tt_*","__*","*printf","gray_*","fopen","fclose","fread","fflush","qsort","sift"]' + +-# enable advising for optimizing the list above; disable this to prevent flooding logs ++# Enable advising for optimizing the list above; disable this to prevent flooding logs + asyncify_advise = '0' + +-# initial heap size in bytes; make sure it is not too low (around 64mb - 250mb) ++# Stack size for asyncify; increase this if you have problems with asyncify-induced crashes ++asyncify_stack_size = '6144' ++ ++# Initial heap size in bytes; make sure it is not too low (around 64mb - 250mb) + initial_heap = '104857600' + + # Emscripten is not always added to PATH. +@@ -17,6 +21,32 @@ initial_heap = '104857600' + # or supply a second machine file that defines this variable. + toolchain = '' + ++# The memory allocator to use. You shouldn't need to change this, ++# but other allocator might offer more performance at the cost of binary size. ++malloc_impl = 'emmalloc' ++ ++# Functions exported by the main module. ++# This is needed if you plan to load shared libraries which need symbols from the main binary. ++# e.g. stdout, stderr, fopen, etc. Use another cross file to override this value. ++exported_functions = '_main' ++ ++# Exported Filesystem modules. ++# For example, you can put '-lidbfs.js' to export IDBFS for later use. ++exported_filesystems = [] ++ ++# Exported JS values in Module. ++# This is needed to preserve symbols after tree shaking. ++exported_js_values = '[]' ++ ++# Extra link options passed to the linker. ++extra_link_options = [] ++ ++# In order to run Lite XL, you will also need to bundle the /data directory. ++# The following option is added to the linking process to bundle the /data directory. ++# If you want to do this manually or the automatic bundling process does not work, ++# comment out the following line. ++bundle_paths = ['--preload-file', '../data@/usr/share/lite-xl/'] ++ + + [binaries] + c = toolchain / 'emcc' +@@ -34,9 +64,9 @@ needs_exe_wrapper = true + + + [built-in options] +-c_args = [] ++c_args = ['-fPIC'] + c_link_args = [] +-cpp_args = [] ++cpp_args = ['-fPIC'] + cpp_link_args = [] + + +@@ -46,8 +76,11 @@ portable = true + arch_tuple = 'wasm32-unknown' + wrap_mode = 'nofallback' + force_fallback_for = 'lua,pcre2,freetype2' +-c_link_args = ['-s', 'ALLOW_MEMORY_GROWTH=1', '-s', 'INITIAL_MEMORY=' + initial_heap, '-s', 'ASYNCIFY=1', '-s', 'ASYNCIFY_ADVISE=' + asyncify_advise, '-s', 'ASYNCIFY_STACK_SIZE=6144', '-s', 'ASYNCIFY_REMOVE=' + asyncify_ignores, '-s', 'FORCE_FILESYSTEM=1', '-lidbfs.js'] ++c_link_args = ['-sALLOW_MEMORY_GROWTH=1', '-sINITIAL_MEMORY=' + initial_heap, '-sASYNCIFY', '-sASYNCIFY_ADVISE=' + asyncify_advise, '-sASYNCIFY_STACK_SIZE=' + asyncify_stack_size, '-sASYNCIFY_REMOVE=' + asyncify_ignores, '-sFORCE_FILESYSTEM=1', '-sEXIT_RUNTIME=1', '-sMALLOC=' + malloc_impl, '-sMAIN_MODULE=1', '-sEXPORTED_FUNCTIONS=' + exported_functions, '-sEXPORTED_RUNTIME_METHODS=' + exported_js_values] + extra_link_options + bundle_paths + exported_filesystems + ++[pcre2:project options] ++jit = 'disabled' ++jit_sealloc = 'disabled' + + [host_machine] + system = 'emscripten' +diff --git a/resources/shell.html b/resources/shell.html +new file mode 100644 +index 00000000..22c0c414 +--- /dev/null ++++ b/resources/shell.html +@@ -0,0 +1,87 @@ ++ ++ ++ ++ ++ ++ ++ ++ Lite XL ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ diff --git a/tasks/lite-xl__lite-xl-1779/tests/test.sh b/tasks/lite-xl__lite-xl-1779/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a86f795051b02c6b6d05fc262010882539f3b57f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/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 efa257ddbdd9ade1cad588918c62f091493ccb1b > "$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/lite-xl__lite-xl-1779/tests/verifier.py b/tasks/lite-xl__lite-xl-1779/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1779/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/lite-xl__lite-xl-1788/environment/Dockerfile b/tasks/lite-xl__lite-xl-1788/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..99bb27380a7e4fa257641a52f1d481de822df8d8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7fdb35ac465e3433721722143ca2eb556cdd0252 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7fdb35ac465e3433721722143ca2eb556cdd0252 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7fdb35ac465e3433721722143ca2eb556cdd0252 \ + && 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/lite-xl__lite-xl-1788/instruction.md b/tasks/lite-xl__lite-xl-1788/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1904d056d13145f059ed460870a4c89e1cf32e20 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** api/system: fix newlines returned by get_clipboard + +## Description + +https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats + +stupid windows + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fdb35ac465e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1788/solution/patch.diff b/tasks/lite-xl__lite-xl-1788/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..56ed127b4a95855c265560362337a7488acb2f97 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/src/api/system.c b/src/api/system.c +index b13a7754..f599e800 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -830,7 +830,14 @@ static int f_mkdir(lua_State *L) { + static int f_get_clipboard(lua_State *L) { + char *text = SDL_GetClipboardText(); + if (!text) { return 0; } ++#ifdef _WIN32 ++ // on windows, text-based clipboard formats must terminate with \r\n ++ // we need to convert it to \n for Lite XL to read them properly ++ // https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats ++ luaL_gsub(L, text, "\r\n", "\n"); ++#else + lua_pushstring(L, text); ++#endif + SDL_free(text); + return 1; + } diff --git a/tasks/lite-xl__lite-xl-1788/solution/solve.sh b/tasks/lite-xl__lite-xl-1788/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/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/lite-xl__lite-xl-1788/task.toml b/tasks/lite-xl__lite-xl-1788/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..73913a544de633241a4aa5307e10c7c368772aa1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1788" +description = "api/system: fix newlines returned by get_clipboard" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7fdb35ac465e3433721722143ca2eb556cdd0252" +reference = "https://github.com/lite-xl/lite-xl/pull/1788" +source_access = "auto" +built_at = "2026-11-16T16:09:56.213987+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:02a88cebaf4d5f0d75535bb773e8195e86c2e3ad636b7eb26be5a586897409a9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-05-23T20:19:15Z" +diff_format = "unified" +context_files = [ + "src/api/system.c", +] +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:01.296369+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f91d2f61f495288fbe6bdf577ce1ebbcba48d6f5f82a2bdcd40228203c26ea93" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1788/tests/capture.py b/tasks/lite-xl__lite-xl-1788/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/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/lite-xl__lite-xl-1788/tests/instruction.md b/tasks/lite-xl__lite-xl-1788/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1904d056d13145f059ed460870a4c89e1cf32e20 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** api/system: fix newlines returned by get_clipboard + +## Description + +https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats + +stupid windows + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7fdb35ac465e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1788/tests/oracle.patch b/tasks/lite-xl__lite-xl-1788/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..56ed127b4a95855c265560362337a7488acb2f97 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/src/api/system.c b/src/api/system.c +index b13a7754..f599e800 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -830,7 +830,14 @@ static int f_mkdir(lua_State *L) { + static int f_get_clipboard(lua_State *L) { + char *text = SDL_GetClipboardText(); + if (!text) { return 0; } ++#ifdef _WIN32 ++ // on windows, text-based clipboard formats must terminate with \r\n ++ // we need to convert it to \n for Lite XL to read them properly ++ // https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats ++ luaL_gsub(L, text, "\r\n", "\n"); ++#else + lua_pushstring(L, text); ++#endif + SDL_free(text); + return 1; + } diff --git a/tasks/lite-xl__lite-xl-1788/tests/test.sh b/tasks/lite-xl__lite-xl-1788/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2cad2d119a773f7be1231ed8a2852f8182beda79 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/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 7fdb35ac465e3433721722143ca2eb556cdd0252 > "$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/lite-xl__lite-xl-1788/tests/verifier.py b/tasks/lite-xl__lite-xl-1788/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1788/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/lite-xl__lite-xl-1804/environment/Dockerfile b/tasks/lite-xl__lite-xl-1804/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a5da7d1507693a83611d305991f26776a1bed7d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 39ba8606451db00f1b151020995fdad47f9c5d8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && 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/lite-xl__lite-xl-1804/instruction.md b/tasks/lite-xl__lite-xl-1804/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4d58f035505410525282d4faf08f741f7d2333e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** ci: use latest macos images + +## Description + +I didn't know the macos-11 image is getting deprecated late June. This would break CI. + +![image](https://github.com/lite-xl/lite-xl/assets/20792268/3ab124b2-7b6a-44ec-93b0-0385fbf0cedf) + +Aside from updating the macOS images, I also removed cross-compilation for Apple M1, since M1-based runners are now available. I also removed the dependency from `install-dependencies.sh`. + +This change resulted in a significant improvement in CI time, since M1 runners are currently faster than the Intel runners, and the CI uses images that has brew prebuilts, so no more compiling bash from source. + +Comparison: + +CI: + +| Before | After | +| ------ | ----- | +| ![image](https://github.com/lite-xl/lite-xl/assets/20792268/2483caac-10ba-438c-b946-9759b1a97108) | ![image](https://github.com/lite-xl/lite-xl/assets/20792268/5d15b4e4-6a7e-469d-b5b0-00901516e506) | + +Release: + +| Before | After | +| ------ | ----- | +| ![image](https://github.com/lite-xl/lite-xl/assets/20792268/78a6357b-ce05-47dc-b8f3-75d1de37d86c) | ![image](https://github.com/lite-xl/lite-xl/assets/20792268/30943393-134b-484e-b980-33eb0054b54c) | + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1804/solution/patch.diff b/tasks/lite-xl__lite-xl-1804/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e21e2300789dc8bd1934b6b3ae834c97cc86fa3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/solution/patch.diff @@ -0,0 +1,192 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 2a8217c1..d6e7d1a6 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -65,13 +65,16 @@ jobs: + + build_macos: + name: macOS +- runs-on: macos-11 ++ strategy: ++ matrix: ++ config: ++ - { arch: x86_64, runner: macos-13 } # macos-13 uses x86_64 ++ - { arch: arm64, runner: macos-14 } # macos-14 / latest uses M1 ++ ++ runs-on: ${{ matrix.config.runner }} + env: + CC: clang + CXX: clang++ +- strategy: +- matrix: +- arch: ["x86_64", "arm64"] + + steps: + - name: System Information +@@ -85,8 +88,7 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" + + - name: Checkout code + uses: actions/checkout@v4 +@@ -96,28 +98,30 @@ jobs: + with: + python-version: "3.11" + +- # --lhelper will eliminate a warning with arm64 and libusb ++ # installing md5sha1sum will eliminate a warning with arm64 and libusb + - name: Install Dependencies +- run: bash scripts/install-dependencies.sh --debug --lhelper ++ run: | ++ brew install bash md5sha1sum ++ pip install meson ninja dmgbuild + + - name: Build + run: | + bash --version +- bash scripts/build.sh --bundle --debug --forcefallback $ARCH ++ bash scripts/build.sh --bundle --debug --forcefallback + + - name: Create DMG Image +- run: bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg ++ run: bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg + + - name: Upload DMG Image + uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images (${{ matrix.arch }}) ++ name: macOS DMG Images (${{ matrix.config.arch }}) + path: ${{ env.INSTALL_NAME }}.dmg + compression-level: 0 + + build_macos_universal: + name: macOS (Universal) +- runs-on: macos-11 ++ runs-on: macos-14 + needs: build_macos + + steps: +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index f14a90ca..83507b28 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -129,10 +129,13 @@ jobs: + build_macos: + name: macOS + needs: release +- runs-on: macos-11 + strategy: + matrix: +- arch: [x86_64, arm64] ++ config: ++ - { arch: x86_64, runner: macos-13 } # macos-13 uses x86_64 ++ - { arch: arm64, runner: macos-14 } # macos-14 / latest uses M1 ++ ++ runs-on: ${{ matrix.config.runner }} + env: + CC: clang + CXX: clang++ +@@ -149,9 +152,8 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi ++ echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" ++ echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" + + - name: Checkout code + uses: actions/checkout@v4 +@@ -162,22 +164,24 @@ jobs: + python-version: "3.11" + + - name: Install Dependencies +- run: bash scripts/install-dependencies.sh --debug ++ run: | ++ brew install bash md5sha1sum ++ pip install meson ninja dmgbuild + + - name: Build + run: | + bash --version +- bash scripts/build.sh --bundle --debug --forcefallback --release $ARCH ++ bash scripts/build.sh --bundle --debug --forcefallback --release + + - name: Create DMG Image + run: | +- bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg --release +- bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --addons --dmg --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --dmg --release + + - name: Upload Artifacts + uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images (${{ matrix.arch }}) ++ name: macOS DMG Images (${{ matrix.config.arch }}) + path: | + ${{ env.INSTALL_NAME }}.dmg + ${{ env.INSTALL_NAME_ADDONS }}.dmg +@@ -185,7 +189,7 @@ jobs: + build_macos_universal: + name: macOS (Universal) + needs: [release, build_macos] +- runs-on: macos-11 ++ runs-on: macos-14 + + steps: + - name: System Information +diff --git a/meson.build b/meson.build +index be995302..fc43e20e 100644 +--- a/meson.build ++++ b/meson.build +@@ -123,7 +123,6 @@ if not get_option('source-only') + sdl_options += 'use_atomic=enabled' + sdl_options += 'use_threads=enabled' + sdl_options += 'use_timers=enabled' +- sdl_options += 'with_main=true' + # investigate if this is truly needed + # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released + sdl_options += 'use_events=enabled' +@@ -150,6 +149,7 @@ if not get_option('source-only') + sdl_options += 'test=false' + sdl_options += 'use_sensor=disabled' + sdl_options += 'use_haptic=disabled' ++ sdl_options += 'use_hidapi=disabled' + sdl_options += 'use_audio=disabled' + sdl_options += 'use_cpuinfo=disabled' + sdl_options += 'use_joystick=disabled' +diff --git a/scripts/make-universal-binaries.sh b/scripts/make-universal-binaries.sh +index e3f2d373..76989144 100644 +--- a/scripts/make-universal-binaries.sh ++++ b/scripts/make-universal-binaries.sh +@@ -30,4 +30,9 @@ done + + lipo -create -output "Lite XL.app/Contents/MacOS/lite-xl" "$WORKDIR/"*-lite-xl + ++# https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ ++# https://wiki.lazarus.freepascal.org/Code_Signing_for_macOS#Big_Sur_and_later_on_Apple_M1_ARM64_processors ++# codesign all the files again, hopefully this would fix signature validation ++codesign --force --deep --digest-algorithm=sha1,sha256 -s - "Lite XL.app" ++ + source scripts/appdmg.sh "$2" +\ No newline at end of file +diff --git a/scripts/package.sh b/scripts/package.sh +index 46d6c231..d4f47fdc 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -270,7 +270,8 @@ main() { + + if [[ $bundle == true ]]; then + # https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ +- codesign --force --deep -s - "${dest_dir}" ++ # https://wiki.lazarus.freepascal.org/Code_Signing_for_macOS#Big_Sur_and_later_on_Apple_M1_ARM64_processors ++ codesign --force --deep --digest-algorithm=sha1,sha256 -s - "${dest_dir}" + fi + + echo "Creating a compressed archive ${package_name}" diff --git a/tasks/lite-xl__lite-xl-1804/solution/solve.sh b/tasks/lite-xl__lite-xl-1804/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/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/lite-xl__lite-xl-1804/task.toml b/tasks/lite-xl__lite-xl-1804/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..31e311d95804685c96832e6553c2a01031ae84a5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1804" +description = "ci: use latest macos images" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "39ba8606451db00f1b151020995fdad47f9c5d8b" +reference = "https://github.com/lite-xl/lite-xl/pull/1804" +source_access = "auto" +built_at = "2026-11-16T16:09:56.212434+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1b5dca1e586517274cb0773b62cb9d0dd93e3e5ff753272c8f43eecd29ad0a27" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-18T03:38:41Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + ".github/workflows/release.yml", + "meson.build", + "scripts/make-universal-binaries.sh", + "scripts/package.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 64 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.296827+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3977f0f62a5786c7e7a672d506ee3c66c8dc8f3708d03885035bf0bc45af5726" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1804/tests/capture.py b/tasks/lite-xl__lite-xl-1804/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/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/lite-xl__lite-xl-1804/tests/instruction.md b/tasks/lite-xl__lite-xl-1804/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4d58f035505410525282d4faf08f741f7d2333e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** ci: use latest macos images + +## Description + +I didn't know the macos-11 image is getting deprecated late June. This would break CI. + +![image](https://github.com/lite-xl/lite-xl/assets/20792268/3ab124b2-7b6a-44ec-93b0-0385fbf0cedf) + +Aside from updating the macOS images, I also removed cross-compilation for Apple M1, since M1-based runners are now available. I also removed the dependency from `install-dependencies.sh`. + +This change resulted in a significant improvement in CI time, since M1 runners are currently faster than the Intel runners, and the CI uses images that has brew prebuilts, so no more compiling bash from source. + +Comparison: + +CI: + +| Before | After | +| ------ | ----- | +| ![image](https://github.com/lite-xl/lite-xl/assets/20792268/2483caac-10ba-438c-b946-9759b1a97108) | ![image](https://github.com/lite-xl/lite-xl/assets/20792268/5d15b4e4-6a7e-469d-b5b0-00901516e506) | + +Release: + +| Before | After | +| ------ | ----- | +| ![image](https://github.com/lite-xl/lite-xl/assets/20792268/78a6357b-ce05-47dc-b8f3-75d1de37d86c) | ![image](https://github.com/lite-xl/lite-xl/assets/20792268/30943393-134b-484e-b980-33eb0054b54c) | + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1804/tests/oracle.patch b/tasks/lite-xl__lite-xl-1804/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e21e2300789dc8bd1934b6b3ae834c97cc86fa3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/tests/oracle.patch @@ -0,0 +1,192 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 2a8217c1..d6e7d1a6 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -65,13 +65,16 @@ jobs: + + build_macos: + name: macOS +- runs-on: macos-11 ++ strategy: ++ matrix: ++ config: ++ - { arch: x86_64, runner: macos-13 } # macos-13 uses x86_64 ++ - { arch: arm64, runner: macos-14 } # macos-14 / latest uses M1 ++ ++ runs-on: ${{ matrix.config.runner }} + env: + CC: clang + CXX: clang++ +- strategy: +- matrix: +- arch: ["x86_64", "arm64"] + + steps: + - name: System Information +@@ -85,8 +88,7 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${GITHUB_REF##*/}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi ++ echo "INSTALL_NAME=lite-xl-${GITHUB_REF##*/}-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" + + - name: Checkout code + uses: actions/checkout@v4 +@@ -96,28 +98,30 @@ jobs: + with: + python-version: "3.11" + +- # --lhelper will eliminate a warning with arm64 and libusb ++ # installing md5sha1sum will eliminate a warning with arm64 and libusb + - name: Install Dependencies +- run: bash scripts/install-dependencies.sh --debug --lhelper ++ run: | ++ brew install bash md5sha1sum ++ pip install meson ninja dmgbuild + + - name: Build + run: | + bash --version +- bash scripts/build.sh --bundle --debug --forcefallback $ARCH ++ bash scripts/build.sh --bundle --debug --forcefallback + + - name: Create DMG Image +- run: bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg ++ run: bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg + + - name: Upload DMG Image + uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images (${{ matrix.arch }}) ++ name: macOS DMG Images (${{ matrix.config.arch }}) + path: ${{ env.INSTALL_NAME }}.dmg + compression-level: 0 + + build_macos_universal: + name: macOS (Universal) +- runs-on: macos-11 ++ runs-on: macos-14 + needs: build_macos + + steps: +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index f14a90ca..83507b28 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -129,10 +129,13 @@ jobs: + build_macos: + name: macOS + needs: release +- runs-on: macos-11 + strategy: + matrix: +- arch: [x86_64, arm64] ++ config: ++ - { arch: x86_64, runner: macos-13 } # macos-13 uses x86_64 ++ - { arch: arm64, runner: macos-14 } # macos-14 / latest uses M1 ++ ++ runs-on: ${{ matrix.config.runner }} + env: + CC: clang + CXX: clang++ +@@ -149,9 +152,8 @@ jobs: + run: | + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + echo "INSTALL_REF=${{ needs.release.outputs.version }}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.arch }}" >> "$GITHUB_ENV" +- if [[ $(uname -m) != ${{ matrix.arch }} ]]; then echo "ARCH=--cross-arch ${{ matrix.arch }}" >> "$GITHUB_ENV"; fi ++ echo "INSTALL_NAME=lite-xl-${{ needs.release.outputs.version }}-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" ++ echo "INSTALL_NAME_ADDONS=lite-xl-${{ needs.release.outputs.version }}-addons-macos-${{ matrix.config.arch }}" >> "$GITHUB_ENV" + + - name: Checkout code + uses: actions/checkout@v4 +@@ -162,22 +164,24 @@ jobs: + python-version: "3.11" + + - name: Install Dependencies +- run: bash scripts/install-dependencies.sh --debug ++ run: | ++ brew install bash md5sha1sum ++ pip install meson ninja dmgbuild + + - name: Build + run: | + bash --version +- bash scripts/build.sh --bundle --debug --forcefallback --release $ARCH ++ bash scripts/build.sh --bundle --debug --forcefallback --release + + - name: Create DMG Image + run: | +- bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --dmg --release +- bash scripts/package.sh --version ${INSTALL_REF} $ARCH --debug --addons --dmg --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --dmg --release ++ bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --dmg --release + + - name: Upload Artifacts + uses: actions/upload-artifact@v4 + with: +- name: macOS DMG Images (${{ matrix.arch }}) ++ name: macOS DMG Images (${{ matrix.config.arch }}) + path: | + ${{ env.INSTALL_NAME }}.dmg + ${{ env.INSTALL_NAME_ADDONS }}.dmg +@@ -185,7 +189,7 @@ jobs: + build_macos_universal: + name: macOS (Universal) + needs: [release, build_macos] +- runs-on: macos-11 ++ runs-on: macos-14 + + steps: + - name: System Information +diff --git a/meson.build b/meson.build +index be995302..fc43e20e 100644 +--- a/meson.build ++++ b/meson.build +@@ -123,7 +123,6 @@ if not get_option('source-only') + sdl_options += 'use_atomic=enabled' + sdl_options += 'use_threads=enabled' + sdl_options += 'use_timers=enabled' +- sdl_options += 'with_main=true' + # investigate if this is truly needed + # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released + sdl_options += 'use_events=enabled' +@@ -150,6 +149,7 @@ if not get_option('source-only') + sdl_options += 'test=false' + sdl_options += 'use_sensor=disabled' + sdl_options += 'use_haptic=disabled' ++ sdl_options += 'use_hidapi=disabled' + sdl_options += 'use_audio=disabled' + sdl_options += 'use_cpuinfo=disabled' + sdl_options += 'use_joystick=disabled' +diff --git a/scripts/make-universal-binaries.sh b/scripts/make-universal-binaries.sh +index e3f2d373..76989144 100644 +--- a/scripts/make-universal-binaries.sh ++++ b/scripts/make-universal-binaries.sh +@@ -30,4 +30,9 @@ done + + lipo -create -output "Lite XL.app/Contents/MacOS/lite-xl" "$WORKDIR/"*-lite-xl + ++# https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ ++# https://wiki.lazarus.freepascal.org/Code_Signing_for_macOS#Big_Sur_and_later_on_Apple_M1_ARM64_processors ++# codesign all the files again, hopefully this would fix signature validation ++codesign --force --deep --digest-algorithm=sha1,sha256 -s - "Lite XL.app" ++ + source scripts/appdmg.sh "$2" +\ No newline at end of file +diff --git a/scripts/package.sh b/scripts/package.sh +index 46d6c231..d4f47fdc 100644 +--- a/scripts/package.sh ++++ b/scripts/package.sh +@@ -270,7 +270,8 @@ main() { + + if [[ $bundle == true ]]; then + # https://eclecticlight.co/2019/01/17/code-signing-for-the-concerned-3-signing-an-app/ +- codesign --force --deep -s - "${dest_dir}" ++ # https://wiki.lazarus.freepascal.org/Code_Signing_for_macOS#Big_Sur_and_later_on_Apple_M1_ARM64_processors ++ codesign --force --deep --digest-algorithm=sha1,sha256 -s - "${dest_dir}" + fi + + echo "Creating a compressed archive ${package_name}" diff --git a/tasks/lite-xl__lite-xl-1804/tests/test.sh b/tasks/lite-xl__lite-xl-1804/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8acb957d2675975b38e177042cf5eb6ff8679fd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/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 39ba8606451db00f1b151020995fdad47f9c5d8b > "$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/lite-xl__lite-xl-1804/tests/verifier.py b/tasks/lite-xl__lite-xl-1804/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1804/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/lite-xl__lite-xl-1812/environment/Dockerfile b/tasks/lite-xl__lite-xl-1812/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a5da7d1507693a83611d305991f26776a1bed7d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 39ba8606451db00f1b151020995fdad47f9c5d8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && 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/lite-xl__lite-xl-1812/instruction.md b/tasks/lite-xl__lite-xl-1812/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90587ada11fcd5fb5e76b4c1ba6d614bbabb3710 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/instruction.md @@ -0,0 +1,275 @@ +# Issue + +**Title:** subprojects: update lua,pcre2,sdl2 + +## Description + +Lua: + +``` +lua: Make library install by default + +The lua library wasn't set to be installed which would result in the corresponding shared library being missing in the install directory. This would cause the linker being unable to find the library when using a dependent project unless the SO was manually copied out from the build directory. +``` + +PCRE2: +``` +Version 10.45 xx-xxx-2024 +------------------------- + +1. Change 6 of 10.44 broke 32-bit compiles because pcre2test's reporting of +memory size was changed to the entire compiled data block, instead of just the +pattern and tables data, so as to align with the new length restriction. +Because the block's header contains pointers, this meant the pcre2test output +was different in 32-bit mode. A patch by Carlo reverts to the preevious state +and makes sure that any limit set by pcre2_set_max_pattern_compiled_length() +also avoids the internal struct overhead. + + +Version 10.44 07-June-2024 +-------------------------- + +1. If a pattern contained a variable-length lookbehind in which the first +branch was not the one with the shortest minimum length, and the lookbehind +contained a capturing group, and elsewhere in the pattern there was another +lookbehind that referenced that group, the pattern was incorrectly compiled, +leading to unpredictable results, including crashes in JIT compiling. An +example pattern is: /(((?<=123?456456|ABC)))(?<=\2)/ + +2. Further updates to the oss-fuzz support: + + (a) Limit quantifiers for groups and classes to be no more than 10. This + avoids very long JIT compile times that happen in some cases when groups + are replicated for quantification, and very long match times when + classes contain a lot of non-ascii characters. + + (b) Added PCRE2_EXTENDED_MORE to the list of allowed options. + + (c) Arranged for text error messages to be shown in 16-bit and 32-bit modes. + + (d) Made the output in standalone mode more readable. + + (e) General code tidies. + + (f) Limit the size of compiled patterns to 10MB (see 6 below). + + (g) Do not run JIT on patterns whose compiled length is greater than 200K + bytes because this takes a long time, causing oss-fuzz to time out. + + (h) Avoid compiling or matching twice with the same options (this could + happen if the input didn't set any options). + +3. Increase the maximum length of a name for a group from 32 to 128 because +there is a user for whom 32 is too small. + +4. Cause pcre2test to output a message when pcre2_jit_compile() gives an error +return if either jitverify or info is specified. + +5. Some auxiliary files for building under OpenVMS that were contributed by +Alexey Chupahin have been installed. + +6. Added pcre2_set_max_pattern_compiled_length() to limit the size of compiled +patterns. + +7. There was a bug in the implementation of \X caused by my (PH) misreading or +misunderstanding one of the grapheme sequence breaking rules in Unicode Annex +#29. A break should occur between two characters with the Extended Pictographic +break property unless a zero-width joiner intervenes. PCRE2 was not insisting +on the ZWJ, causing \X to match more than it should. See GitHub issue #410. + +8. Avoid compilation issues with proprietary compilers in UNIX since 10.43. + + +Version 10.43 16-February-2024 +------------------------------ + +1. The test program added by change 2 of 10.42 didn't work when the default +newline setting didn't include \n as a newline. One test needed (*LF) to ensure +that it worked. + +2. Added the new freestanding POSIX test program to the ManyConfigTests script +in the maint directory (overlooked in 2 below). Also improved the selection +facilities in that script, and added a test with JIT in a non-source directory, +fixing an oversight that would have made such a test fail before. + +3. Added pcre2_get_match_data_heapframes_size() and related pcre2test flags +to allow for finer control of the heap used when pcre2_match() without JIT is +used and the match_data might be reused. This began as PR #191, but has had +further refinement and documentation edits. + +4. Applied PR #181, which tidies some casts in pcre2_valid_utf.c. + +5. Applied PR #184, which avoids overflow issues with the heap limit +(introduced in 10.41/9). + +6. Applied PR #192, which changes the timing units for pcre2test from +milliseconds to microseconds. This is more useful for modern CPUs. + +7. Applied PR #193, which makes the requirement for C99 explicit in +configure.ac and CMakeLists.txt. + +8. Fixed a bug in pcre2test when a ridiculously large string repeat required a +stupid amount of memory. It now gives a clean realloc() failure error. + +9. Updates to restrict the interaction between ASCII and non-ASCII characters +for caseless matching and items like \d: + + (a) Added PCRE2_EXTRA_CASELESS_RESTRICT to lock out mixing of ASCII and + non-ASCII when matching caselessly. This is also /r in pcre2test and + (?r) within patterns. + + (b) Added PCRE2_EXTRA_ASCII_{BSD,BSS,BSW,POSIX} and corresponding (?aD) etc + in patterns and /a in pcre2test. + + (c) Corresponding updates to pcre2test. + +10. Unicode has been updated to 15.0.0. + +11. The Python scripts and ucptest.c in maint have been updated (a) a minor +change needed for 9(a) above; (b) fix bugs in ucptest, + +12. Integer overflow testing is now centralized in a new function. + +13. Made PCRE2_UCP the default in UTF mode in pcre2grep, and added new options +--case-restrict and --no-ucp. + +14. In the debugging printint module (which is normally only linked into +pcre2test), avoid the use of a variable called "not" because that's deprecated +in C and forbidden in C++. Also rewrite some code to avoid a goto into a block +that bypassed its initialization (though it didn't actually matter). + +15. More minor code adjustments to avoid using reserved C++ words as variable +names ("new" and "typename") and another jump that bypassed an (irrelevant) +initialization. + +16. Merged a pull request that removed pcre2_ucptables.c from the list of files +to compile in NON-AUTOTOOLS-BUILD because it is #included in pcre2_tables.c. +Also adjusted the BUILD.bazel and build.zig files, which had the same issue. At +the same time, fixed a typo in the Bazel file. + +17. Add PCRE2_EXTRA_ASCII_DIGIT to allow [:digit:] to be kept on sync with \d +even in UCP mode. + +18. Fix an invalid match of ascii word classes when invalid utf is enabled. + +19. Add a --posix-digit to pcre2grep for compatibility with GNU grep, and +other tools that prefer the POSIX compatible unicode definition for \d. + +20. Report the bit width of the library in use by pcre2test for usability. + +21. A pathological pattern conversion test could result in a string longer than +the available input buffer. Cause such a test to fail. + +22. Add a check that forces a compiler error if PCRE2_CODE_UNIT_WIDTH is not 8, +16, or 32 when compiling any of the library modules. + +23. Update pcre2_compile() to treat a NULL pattern with zero length as an empty +string. + +24. Add support for limited-length variable-length lookbehind assertions, with +default maximum length 255 characters (same as Perl) but with a function to +adjust the limit. + +25. Applied pull request #262, which updates the zig configuration, and #278 +which fixes a bug with out-of-source-tree CMake build testing. + +26. Add support for LoongArch to JIT. + +27. Fixed a bug in pcre2_match() in the code for handling the vector of +backtracking frames on the heap, which caused a heap overflow if *LIMIT_HEAP +restricted an attempt to extend to less than the frame size. Generally tidy up +the code for extending the heap frames vector. This fixes GitHub issue #275. + +28. Update pcre2_fuzzsupport.c to avoid clang sanitize complaint about shifting +left by 16 when there are non-zeros in the top 16 bits. + +29. Perl 5.34.0 changed the meaning of (for example) {,3} which did not used to +be treated as a quantifier. Now it is interpreted as {0,3} and PCRE2 has +changed to match. Note that {,} is still not a quantifier. + +30. Perl allows spaces and/or horizontal tabs after { or before } in all items +that use braces, and also before or after the comma in quantifiers. PCRE2 now +does the same, except for \u{...}, which is recognized only when +PCRE2_EXTRA_ALT_BSUX is set. This an ECMAScript, non-Perl compatible, +extension, so PCRE2 follows ECMAScript rather than Perl. + +31. Applied pull request #300 by Carlo, which . The bug was that +pcre2_match() was not fully resetting all captures that had been set within a +(possibly recursive) subroutine call such as (?3). + +32. Changed the meaning of \w (and its synonyms) in UCP mode to match Perl. It +now matches characters whose general categories are L or N or whose particular +categories are Mn (non-spacing mark) or Pc (combining punctuation). The latter +includes underscore. + +33. Changed the meaning of [:xdigit:] in UCP mode to match Perl. It now also +matches the "fullwidth" versions of the hex digits. Just like it is done for +[:digit:], PCRE2_EXTRA_ASCII_DIGIT can be used to keep this class ASCII only +without affecting other POSIX classes. + +34. GitHub PR305 fixes a potential integer overflow in pcre2_dfa_match(). + +35. Updated handling of \b and \B in UCP mode to match the changes to \w in 32 +above because \b and \B are defined in terms of \w. + +36. Within a pattern (?aT) and (?-aT) set and reset the PCRE2_EXTRA_ASCII_DIGIT +option, and (?aP) also sets (?aT) so that (?-aP) disables all ASCII +restrictions on POSIX classes. + +37. If PCRE2_FIRSTLINE was set on an anchored pattern, pcre2_match() and +pcre2_dfa_match() misbehaved. PCRE2_FIRSTLINE is now ignored for anchored +patterns. + +38. Add a test for ridiculous ovector offset values to the substring extraction +functions. + +39. Make OP_REVERSE use IMM2_SIZE for its data instead of LINK_SIZE, for +consistency with OP_VREVERSE. + +40. In some legacy environments with a pre C99 snprintf, pcre2_regerror could +return an incorrect value when the provided buffer was too small. + +41. Applied pull request #342 which adds sanity checks for ctype functions and +locks out any accidental sign-extension. + +42. In the 32-bit library, in non-UTF mode, a quantifier that followed a +literal character with a value greater than or equal to 0x80000000u caused +undefined behaviour. + +43. \z was misbehaving when matching fragments inside invalid UTF strings. + +44. Implement --group-separator and --no-group-separator for pcre2grep. + +45. Fix \X matching in 32 bit mode without UTF in JIT. + +46. Fix backref iterators when PCRE2_MATCH_UNSET_BACKREF is set in JIT. + +47. Refactor the handling of whole-pattern recursion (?0) in pcre2_match() so +that its end is handled similarly to other recursions. This has altered the +behaviour of /|(?0)./endanchored which was previously not right. + +48. Improved the test for looping recursion by checking the last referenced +character as well as the current character. This allows some patterns that +previously triggered the check to run to completion instead of giving the loop +error. + +49. In 32-bit mode, the compiler looped for the pattern /[\x{ffffffff}]/ when +PCRE2_CASELESS and PCRE2_UCP (but not PCRE2_UTF) were set. Fixed by not trying +to look for other cases for characters above the Unicode range. + +50. In caseless 32-bit mode with UCP (but not UTF) set, the character +0xffffffff incorrectly matched any character that has more than one other case, +in particular k and s. + +51. Fix accept and endanchored interaction in JIT. + +52. Fix backreferences with unset backref and non-greedy iterators in JIT. + +53. Improve the logic that checks for a list of starting code units -- positive +lookahead assertions are now ignored if the immediately following item is one +that sets a mandatory starting character. For example, /a?(?=bc|)d/ used to set +all of a, b, and d as possible + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1812/solution/patch.diff b/tasks/lite-xl__lite-xl-1812/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..738888cca06b72422e84124cf3600d6e02377b3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/solution/patch.diff @@ -0,0 +1,99 @@ +diff --git a/meson.build b/meson.build +index be995302..c8f3aeb9 100644 +--- a/meson.build ++++ b/meson.build +@@ -123,7 +123,6 @@ if not get_option('source-only') + sdl_options += 'use_atomic=enabled' + sdl_options += 'use_threads=enabled' + sdl_options += 'use_timers=enabled' +- sdl_options += 'with_main=true' + # investigate if this is truly needed + # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released + sdl_options += 'use_events=enabled' +@@ -150,9 +149,11 @@ if not get_option('source-only') + sdl_options += 'test=false' + sdl_options += 'use_sensor=disabled' + sdl_options += 'use_haptic=disabled' ++ sdl_options += 'use_hidapi=disabled' + sdl_options += 'use_audio=disabled' + sdl_options += 'use_cpuinfo=disabled' + sdl_options += 'use_joystick=disabled' ++ sdl_options += 'use_joystick_xinput=disabled' + sdl_options += 'use_video_vulkan=disabled' + sdl_options += 'use_video_offscreen=disabled' + sdl_options += 'use_power=disabled' +diff --git a/subprojects/lua.wrap b/subprojects/lua.wrap +index 16502616..a1ffdaf3 100644 +--- a/subprojects/lua.wrap ++++ b/subprojects/lua.wrap +@@ -3,11 +3,11 @@ directory = lua-5.4.6 + source_url = https://www.lua.org/ftp/lua-5.4.6.tar.gz + source_filename = lua-5.4.6.tar.gz + source_hash = 7d5ea1b9cb6aa0b59ca3dde1c6adcb57ef83a1ba8e5432c0ecd06bf439b3ad88 +-patch_filename = lua_5.4.6-3_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-3/get_patch +-patch_hash = 9b72a95422fd47f79f969d9abdb589ee95712d5512a5246f94e7e4f63d2cb7b7 +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-3/lua-5.4.6.tar.gz +-wrapdb_version = 5.4.6-3 ++patch_filename = lua_5.4.6-4_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-4/get_patch ++patch_hash = b5a8c9b3673fbe58afaf842041bc9551f1f742c363fd3be8d47db2e6a483b54c ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-4/lua-5.4.6.tar.gz ++wrapdb_version = 5.4.6-4 + + [provide] + lua-5.4 = lua_dep +diff --git a/subprojects/pcre2.wrap b/subprojects/pcre2.wrap +index 6bfef6f3..73b727ec 100644 +--- a/subprojects/pcre2.wrap ++++ b/subprojects/pcre2.wrap +@@ -1,13 +1,13 @@ + [wrap-file] +-directory = pcre2-10.42 +-source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.42/pcre2-10.42.tar.bz2 +-source_filename = pcre2-10.42.tar.bz2 +-source_hash = 8d36cd8cb6ea2a4c2bb358ff6411b0c788633a2a45dabbf1aeb4b701d1b5e840 +-patch_filename = pcre2_10.42-5_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.42-5/get_patch +-patch_hash = 7ba1730a3786c46f41735658a9884b09bc592af3840716e0ccc552e7ddf5630c +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.42-5/pcre2-10.42.tar.bz2 +-wrapdb_version = 10.42-5 ++directory = pcre2-10.44 ++source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.bz2 ++source_filename = pcre2-10.44.tar.bz2 ++source_hash = d34f02e113cf7193a1ebf2770d3ac527088d485d4e047ed10e5d217c6ef5de96 ++patch_filename = pcre2_10.44-1_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-1/get_patch ++patch_hash = 947ee4d309302024f780a5839e779674309c94c05bb5a0618d201979b424002f ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-1/pcre2-10.44.tar.bz2 ++wrapdb_version = 10.44-1 + + [provide] + libpcre2-8 = libpcre2_8 +diff --git a/subprojects/sdl2.wrap b/subprojects/sdl2.wrap +index 14c18533..ae308d73 100644 +--- a/subprojects/sdl2.wrap ++++ b/subprojects/sdl2.wrap +@@ -1,13 +1,13 @@ + [wrap-file] +-directory = SDL2-2.28.1 +-source_url = https://github.com/libsdl-org/SDL/releases/download/release-2.28.1/SDL2-2.28.1.tar.gz +-source_filename = SDL2-2.28.1.tar.gz +-source_hash = 4977ceba5c0054dbe6c2f114641aced43ce3bf2b41ea64b6a372d6ba129cb15d +-patch_filename = sdl2_2.28.1-2_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/sdl2_2.28.1-2/get_patch +-patch_hash = 2dd332226ba2a4373c6d4eb29fa915e9d5414cf7bb9fa2e4a5ef3b16a06e2736 +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sdl2_2.28.1-2/SDL2-2.28.1.tar.gz +-wrapdb_version = 2.28.1-2 ++directory = SDL2-2.30.3 ++source_url = https://github.com/libsdl-org/SDL/releases/download/release-2.30.3/SDL2-2.30.3.tar.gz ++source_filename = SDL2-2.30.3.tar.gz ++source_hash = 820440072f8f5b50188c1dae104f2ad25984de268785be40c41a099a510f0aec ++patch_filename = sdl2_2.30.3-2_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/sdl2_2.30.3-2/get_patch ++patch_hash = 2c08bde67b3896db88e01481c379322625ea6c928cdb68ead91d0e3749863bc2 ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sdl2_2.30.3-2/SDL2-2.30.3.tar.gz ++wrapdb_version = 2.30.3-2 + + [provide] + sdl2 = sdl2_dep diff --git a/tasks/lite-xl__lite-xl-1812/solution/solve.sh b/tasks/lite-xl__lite-xl-1812/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/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/lite-xl__lite-xl-1812/task.toml b/tasks/lite-xl__lite-xl-1812/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f822303b9d81df24a370bed3522bad75350cee89 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1812" +description = "subprojects: update lua,pcre2,sdl2" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "39ba8606451db00f1b151020995fdad47f9c5d8b" +reference = "https://github.com/lite-xl/lite-xl/pull/1812" +source_access = "auto" +built_at = "2026-11-16T16:09:56.204589+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c482fff803a8291069fe0e54167312d4b552591da89ef51bf1c2237649d7bf6d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-18T13:19:38Z" +diff_format = "unified" +context_files = [ + "meson.build", + "subprojects/lua.wrap", + "subprojects/pcre2.wrap", + "subprojects/sdl2.wrap", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.297282+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3977f0f62a5786c7e7a672d506ee3c66c8dc8f3708d03885035bf0bc45af5726" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1812/tests/capture.py b/tasks/lite-xl__lite-xl-1812/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/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/lite-xl__lite-xl-1812/tests/instruction.md b/tasks/lite-xl__lite-xl-1812/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90587ada11fcd5fb5e76b4c1ba6d614bbabb3710 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/tests/instruction.md @@ -0,0 +1,275 @@ +# Issue + +**Title:** subprojects: update lua,pcre2,sdl2 + +## Description + +Lua: + +``` +lua: Make library install by default + +The lua library wasn't set to be installed which would result in the corresponding shared library being missing in the install directory. This would cause the linker being unable to find the library when using a dependent project unless the SO was manually copied out from the build directory. +``` + +PCRE2: +``` +Version 10.45 xx-xxx-2024 +------------------------- + +1. Change 6 of 10.44 broke 32-bit compiles because pcre2test's reporting of +memory size was changed to the entire compiled data block, instead of just the +pattern and tables data, so as to align with the new length restriction. +Because the block's header contains pointers, this meant the pcre2test output +was different in 32-bit mode. A patch by Carlo reverts to the preevious state +and makes sure that any limit set by pcre2_set_max_pattern_compiled_length() +also avoids the internal struct overhead. + + +Version 10.44 07-June-2024 +-------------------------- + +1. If a pattern contained a variable-length lookbehind in which the first +branch was not the one with the shortest minimum length, and the lookbehind +contained a capturing group, and elsewhere in the pattern there was another +lookbehind that referenced that group, the pattern was incorrectly compiled, +leading to unpredictable results, including crashes in JIT compiling. An +example pattern is: /(((?<=123?456456|ABC)))(?<=\2)/ + +2. Further updates to the oss-fuzz support: + + (a) Limit quantifiers for groups and classes to be no more than 10. This + avoids very long JIT compile times that happen in some cases when groups + are replicated for quantification, and very long match times when + classes contain a lot of non-ascii characters. + + (b) Added PCRE2_EXTENDED_MORE to the list of allowed options. + + (c) Arranged for text error messages to be shown in 16-bit and 32-bit modes. + + (d) Made the output in standalone mode more readable. + + (e) General code tidies. + + (f) Limit the size of compiled patterns to 10MB (see 6 below). + + (g) Do not run JIT on patterns whose compiled length is greater than 200K + bytes because this takes a long time, causing oss-fuzz to time out. + + (h) Avoid compiling or matching twice with the same options (this could + happen if the input didn't set any options). + +3. Increase the maximum length of a name for a group from 32 to 128 because +there is a user for whom 32 is too small. + +4. Cause pcre2test to output a message when pcre2_jit_compile() gives an error +return if either jitverify or info is specified. + +5. Some auxiliary files for building under OpenVMS that were contributed by +Alexey Chupahin have been installed. + +6. Added pcre2_set_max_pattern_compiled_length() to limit the size of compiled +patterns. + +7. There was a bug in the implementation of \X caused by my (PH) misreading or +misunderstanding one of the grapheme sequence breaking rules in Unicode Annex +#29. A break should occur between two characters with the Extended Pictographic +break property unless a zero-width joiner intervenes. PCRE2 was not insisting +on the ZWJ, causing \X to match more than it should. See GitHub issue #410. + +8. Avoid compilation issues with proprietary compilers in UNIX since 10.43. + + +Version 10.43 16-February-2024 +------------------------------ + +1. The test program added by change 2 of 10.42 didn't work when the default +newline setting didn't include \n as a newline. One test needed (*LF) to ensure +that it worked. + +2. Added the new freestanding POSIX test program to the ManyConfigTests script +in the maint directory (overlooked in 2 below). Also improved the selection +facilities in that script, and added a test with JIT in a non-source directory, +fixing an oversight that would have made such a test fail before. + +3. Added pcre2_get_match_data_heapframes_size() and related pcre2test flags +to allow for finer control of the heap used when pcre2_match() without JIT is +used and the match_data might be reused. This began as PR #191, but has had +further refinement and documentation edits. + +4. Applied PR #181, which tidies some casts in pcre2_valid_utf.c. + +5. Applied PR #184, which avoids overflow issues with the heap limit +(introduced in 10.41/9). + +6. Applied PR #192, which changes the timing units for pcre2test from +milliseconds to microseconds. This is more useful for modern CPUs. + +7. Applied PR #193, which makes the requirement for C99 explicit in +configure.ac and CMakeLists.txt. + +8. Fixed a bug in pcre2test when a ridiculously large string repeat required a +stupid amount of memory. It now gives a clean realloc() failure error. + +9. Updates to restrict the interaction between ASCII and non-ASCII characters +for caseless matching and items like \d: + + (a) Added PCRE2_EXTRA_CASELESS_RESTRICT to lock out mixing of ASCII and + non-ASCII when matching caselessly. This is also /r in pcre2test and + (?r) within patterns. + + (b) Added PCRE2_EXTRA_ASCII_{BSD,BSS,BSW,POSIX} and corresponding (?aD) etc + in patterns and /a in pcre2test. + + (c) Corresponding updates to pcre2test. + +10. Unicode has been updated to 15.0.0. + +11. The Python scripts and ucptest.c in maint have been updated (a) a minor +change needed for 9(a) above; (b) fix bugs in ucptest, + +12. Integer overflow testing is now centralized in a new function. + +13. Made PCRE2_UCP the default in UTF mode in pcre2grep, and added new options +--case-restrict and --no-ucp. + +14. In the debugging printint module (which is normally only linked into +pcre2test), avoid the use of a variable called "not" because that's deprecated +in C and forbidden in C++. Also rewrite some code to avoid a goto into a block +that bypassed its initialization (though it didn't actually matter). + +15. More minor code adjustments to avoid using reserved C++ words as variable +names ("new" and "typename") and another jump that bypassed an (irrelevant) +initialization. + +16. Merged a pull request that removed pcre2_ucptables.c from the list of files +to compile in NON-AUTOTOOLS-BUILD because it is #included in pcre2_tables.c. +Also adjusted the BUILD.bazel and build.zig files, which had the same issue. At +the same time, fixed a typo in the Bazel file. + +17. Add PCRE2_EXTRA_ASCII_DIGIT to allow [:digit:] to be kept on sync with \d +even in UCP mode. + +18. Fix an invalid match of ascii word classes when invalid utf is enabled. + +19. Add a --posix-digit to pcre2grep for compatibility with GNU grep, and +other tools that prefer the POSIX compatible unicode definition for \d. + +20. Report the bit width of the library in use by pcre2test for usability. + +21. A pathological pattern conversion test could result in a string longer than +the available input buffer. Cause such a test to fail. + +22. Add a check that forces a compiler error if PCRE2_CODE_UNIT_WIDTH is not 8, +16, or 32 when compiling any of the library modules. + +23. Update pcre2_compile() to treat a NULL pattern with zero length as an empty +string. + +24. Add support for limited-length variable-length lookbehind assertions, with +default maximum length 255 characters (same as Perl) but with a function to +adjust the limit. + +25. Applied pull request #262, which updates the zig configuration, and #278 +which fixes a bug with out-of-source-tree CMake build testing. + +26. Add support for LoongArch to JIT. + +27. Fixed a bug in pcre2_match() in the code for handling the vector of +backtracking frames on the heap, which caused a heap overflow if *LIMIT_HEAP +restricted an attempt to extend to less than the frame size. Generally tidy up +the code for extending the heap frames vector. This fixes GitHub issue #275. + +28. Update pcre2_fuzzsupport.c to avoid clang sanitize complaint about shifting +left by 16 when there are non-zeros in the top 16 bits. + +29. Perl 5.34.0 changed the meaning of (for example) {,3} which did not used to +be treated as a quantifier. Now it is interpreted as {0,3} and PCRE2 has +changed to match. Note that {,} is still not a quantifier. + +30. Perl allows spaces and/or horizontal tabs after { or before } in all items +that use braces, and also before or after the comma in quantifiers. PCRE2 now +does the same, except for \u{...}, which is recognized only when +PCRE2_EXTRA_ALT_BSUX is set. This an ECMAScript, non-Perl compatible, +extension, so PCRE2 follows ECMAScript rather than Perl. + +31. Applied pull request #300 by Carlo, which . The bug was that +pcre2_match() was not fully resetting all captures that had been set within a +(possibly recursive) subroutine call such as (?3). + +32. Changed the meaning of \w (and its synonyms) in UCP mode to match Perl. It +now matches characters whose general categories are L or N or whose particular +categories are Mn (non-spacing mark) or Pc (combining punctuation). The latter +includes underscore. + +33. Changed the meaning of [:xdigit:] in UCP mode to match Perl. It now also +matches the "fullwidth" versions of the hex digits. Just like it is done for +[:digit:], PCRE2_EXTRA_ASCII_DIGIT can be used to keep this class ASCII only +without affecting other POSIX classes. + +34. GitHub PR305 fixes a potential integer overflow in pcre2_dfa_match(). + +35. Updated handling of \b and \B in UCP mode to match the changes to \w in 32 +above because \b and \B are defined in terms of \w. + +36. Within a pattern (?aT) and (?-aT) set and reset the PCRE2_EXTRA_ASCII_DIGIT +option, and (?aP) also sets (?aT) so that (?-aP) disables all ASCII +restrictions on POSIX classes. + +37. If PCRE2_FIRSTLINE was set on an anchored pattern, pcre2_match() and +pcre2_dfa_match() misbehaved. PCRE2_FIRSTLINE is now ignored for anchored +patterns. + +38. Add a test for ridiculous ovector offset values to the substring extraction +functions. + +39. Make OP_REVERSE use IMM2_SIZE for its data instead of LINK_SIZE, for +consistency with OP_VREVERSE. + +40. In some legacy environments with a pre C99 snprintf, pcre2_regerror could +return an incorrect value when the provided buffer was too small. + +41. Applied pull request #342 which adds sanity checks for ctype functions and +locks out any accidental sign-extension. + +42. In the 32-bit library, in non-UTF mode, a quantifier that followed a +literal character with a value greater than or equal to 0x80000000u caused +undefined behaviour. + +43. \z was misbehaving when matching fragments inside invalid UTF strings. + +44. Implement --group-separator and --no-group-separator for pcre2grep. + +45. Fix \X matching in 32 bit mode without UTF in JIT. + +46. Fix backref iterators when PCRE2_MATCH_UNSET_BACKREF is set in JIT. + +47. Refactor the handling of whole-pattern recursion (?0) in pcre2_match() so +that its end is handled similarly to other recursions. This has altered the +behaviour of /|(?0)./endanchored which was previously not right. + +48. Improved the test for looping recursion by checking the last referenced +character as well as the current character. This allows some patterns that +previously triggered the check to run to completion instead of giving the loop +error. + +49. In 32-bit mode, the compiler looped for the pattern /[\x{ffffffff}]/ when +PCRE2_CASELESS and PCRE2_UCP (but not PCRE2_UTF) were set. Fixed by not trying +to look for other cases for characters above the Unicode range. + +50. In caseless 32-bit mode with UCP (but not UTF) set, the character +0xffffffff incorrectly matched any character that has more than one other case, +in particular k and s. + +51. Fix accept and endanchored interaction in JIT. + +52. Fix backreferences with unset backref and non-greedy iterators in JIT. + +53. Improve the logic that checks for a list of starting code units -- positive +lookahead assertions are now ignored if the immediately following item is one +that sets a mandatory starting character. For example, /a?(?=bc|)d/ used to set +all of a, b, and d as possible + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1812/tests/oracle.patch b/tasks/lite-xl__lite-xl-1812/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..738888cca06b72422e84124cf3600d6e02377b3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/tests/oracle.patch @@ -0,0 +1,99 @@ +diff --git a/meson.build b/meson.build +index be995302..c8f3aeb9 100644 +--- a/meson.build ++++ b/meson.build +@@ -123,7 +123,6 @@ if not get_option('source-only') + sdl_options += 'use_atomic=enabled' + sdl_options += 'use_threads=enabled' + sdl_options += 'use_timers=enabled' +- sdl_options += 'with_main=true' + # investigate if this is truly needed + # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released + sdl_options += 'use_events=enabled' +@@ -150,9 +149,11 @@ if not get_option('source-only') + sdl_options += 'test=false' + sdl_options += 'use_sensor=disabled' + sdl_options += 'use_haptic=disabled' ++ sdl_options += 'use_hidapi=disabled' + sdl_options += 'use_audio=disabled' + sdl_options += 'use_cpuinfo=disabled' + sdl_options += 'use_joystick=disabled' ++ sdl_options += 'use_joystick_xinput=disabled' + sdl_options += 'use_video_vulkan=disabled' + sdl_options += 'use_video_offscreen=disabled' + sdl_options += 'use_power=disabled' +diff --git a/subprojects/lua.wrap b/subprojects/lua.wrap +index 16502616..a1ffdaf3 100644 +--- a/subprojects/lua.wrap ++++ b/subprojects/lua.wrap +@@ -3,11 +3,11 @@ directory = lua-5.4.6 + source_url = https://www.lua.org/ftp/lua-5.4.6.tar.gz + source_filename = lua-5.4.6.tar.gz + source_hash = 7d5ea1b9cb6aa0b59ca3dde1c6adcb57ef83a1ba8e5432c0ecd06bf439b3ad88 +-patch_filename = lua_5.4.6-3_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-3/get_patch +-patch_hash = 9b72a95422fd47f79f969d9abdb589ee95712d5512a5246f94e7e4f63d2cb7b7 +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-3/lua-5.4.6.tar.gz +-wrapdb_version = 5.4.6-3 ++patch_filename = lua_5.4.6-4_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-4/get_patch ++patch_hash = b5a8c9b3673fbe58afaf842041bc9551f1f742c363fd3be8d47db2e6a483b54c ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-4/lua-5.4.6.tar.gz ++wrapdb_version = 5.4.6-4 + + [provide] + lua-5.4 = lua_dep +diff --git a/subprojects/pcre2.wrap b/subprojects/pcre2.wrap +index 6bfef6f3..73b727ec 100644 +--- a/subprojects/pcre2.wrap ++++ b/subprojects/pcre2.wrap +@@ -1,13 +1,13 @@ + [wrap-file] +-directory = pcre2-10.42 +-source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.42/pcre2-10.42.tar.bz2 +-source_filename = pcre2-10.42.tar.bz2 +-source_hash = 8d36cd8cb6ea2a4c2bb358ff6411b0c788633a2a45dabbf1aeb4b701d1b5e840 +-patch_filename = pcre2_10.42-5_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.42-5/get_patch +-patch_hash = 7ba1730a3786c46f41735658a9884b09bc592af3840716e0ccc552e7ddf5630c +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.42-5/pcre2-10.42.tar.bz2 +-wrapdb_version = 10.42-5 ++directory = pcre2-10.44 ++source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.bz2 ++source_filename = pcre2-10.44.tar.bz2 ++source_hash = d34f02e113cf7193a1ebf2770d3ac527088d485d4e047ed10e5d217c6ef5de96 ++patch_filename = pcre2_10.44-1_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-1/get_patch ++patch_hash = 947ee4d309302024f780a5839e779674309c94c05bb5a0618d201979b424002f ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-1/pcre2-10.44.tar.bz2 ++wrapdb_version = 10.44-1 + + [provide] + libpcre2-8 = libpcre2_8 +diff --git a/subprojects/sdl2.wrap b/subprojects/sdl2.wrap +index 14c18533..ae308d73 100644 +--- a/subprojects/sdl2.wrap ++++ b/subprojects/sdl2.wrap +@@ -1,13 +1,13 @@ + [wrap-file] +-directory = SDL2-2.28.1 +-source_url = https://github.com/libsdl-org/SDL/releases/download/release-2.28.1/SDL2-2.28.1.tar.gz +-source_filename = SDL2-2.28.1.tar.gz +-source_hash = 4977ceba5c0054dbe6c2f114641aced43ce3bf2b41ea64b6a372d6ba129cb15d +-patch_filename = sdl2_2.28.1-2_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/sdl2_2.28.1-2/get_patch +-patch_hash = 2dd332226ba2a4373c6d4eb29fa915e9d5414cf7bb9fa2e4a5ef3b16a06e2736 +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sdl2_2.28.1-2/SDL2-2.28.1.tar.gz +-wrapdb_version = 2.28.1-2 ++directory = SDL2-2.30.3 ++source_url = https://github.com/libsdl-org/SDL/releases/download/release-2.30.3/SDL2-2.30.3.tar.gz ++source_filename = SDL2-2.30.3.tar.gz ++source_hash = 820440072f8f5b50188c1dae104f2ad25984de268785be40c41a099a510f0aec ++patch_filename = sdl2_2.30.3-2_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/sdl2_2.30.3-2/get_patch ++patch_hash = 2c08bde67b3896db88e01481c379322625ea6c928cdb68ead91d0e3749863bc2 ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sdl2_2.30.3-2/SDL2-2.30.3.tar.gz ++wrapdb_version = 2.30.3-2 + + [provide] + sdl2 = sdl2_dep diff --git a/tasks/lite-xl__lite-xl-1812/tests/test.sh b/tasks/lite-xl__lite-xl-1812/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8acb957d2675975b38e177042cf5eb6ff8679fd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/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 39ba8606451db00f1b151020995fdad47f9c5d8b > "$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/lite-xl__lite-xl-1812/tests/verifier.py b/tasks/lite-xl__lite-xl-1812/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1812/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/lite-xl__lite-xl-1814/environment/Dockerfile b/tasks/lite-xl__lite-xl-1814/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a5da7d1507693a83611d305991f26776a1bed7d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 39ba8606451db00f1b151020995fdad47f9c5d8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 39ba8606451db00f1b151020995fdad47f9c5d8b \ + && 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/lite-xl__lite-xl-1814/instruction.md b/tasks/lite-xl__lite-xl-1814/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01e6c8f8abc21b5f101e5ba7e24ad403f6f2d859 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** ci: dependabot updates + +## Description + +me when github runners deprecate node 20 there's warning everywhere until it straight up broke + +Joking aside, this is a real issue because no one actually keep tracks of new action releases, which means our CI eventually degrade and break. The recent #1804 and #1724 are good examples of how things can go really wrong. IIRC dependabot will not keep track of `docker://` protocol versions which was used by `lite-xl-build-box`, but I don't expect the build box to break. + +https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#github-actions + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1814/solution/patch.diff b/tasks/lite-xl__lite-xl-1814/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3e32137d1a24beb0ddb8351d6cd73b4c4444590c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/.github/dependabot.yml b/.github/dependabot.yml +new file mode 100644 +index 00000000..3f4f0b92 +--- /dev/null ++++ b/.github/dependabot.yml +@@ -0,0 +1,9 @@ ++version: 2 ++updates: ++ - package-ecosystem: github-actions ++ directory: "/" ++ schedule: ++ interval: weekly ++ groups: ++ github-actions: ++ patterns: ["*"] diff --git a/tasks/lite-xl__lite-xl-1814/solution/solve.sh b/tasks/lite-xl__lite-xl-1814/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/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/lite-xl__lite-xl-1814/task.toml b/tasks/lite-xl__lite-xl-1814/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..743168918f5457cfe71cf0a829c09915ec31b176 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1814" +description = "ci: dependabot updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "39ba8606451db00f1b151020995fdad47f9c5d8b" +reference = "https://github.com/lite-xl/lite-xl/pull/1814" +source_access = "auto" +built_at = "2026-11-16T16:09:56.211012+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a6c7ce41b867dd97ce8a403844b4a3f3fafd196c605f540ec7777b7fc1550e8e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-18T14:04:41Z" +diff_format = "unified" +context_files = [ + ".github/dependabot.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.297726+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3977f0f62a5786c7e7a672d506ee3c66c8dc8f3708d03885035bf0bc45af5726" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1814/tests/capture.py b/tasks/lite-xl__lite-xl-1814/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/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/lite-xl__lite-xl-1814/tests/instruction.md b/tasks/lite-xl__lite-xl-1814/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01e6c8f8abc21b5f101e5ba7e24ad403f6f2d859 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** ci: dependabot updates + +## Description + +me when github runners deprecate node 20 there's warning everywhere until it straight up broke + +Joking aside, this is a real issue because no one actually keep tracks of new action releases, which means our CI eventually degrade and break. The recent #1804 and #1724 are good examples of how things can go really wrong. IIRC dependabot will not keep track of `docker://` protocol versions which was used by `lite-xl-build-box`, but I don't expect the build box to break. + +https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#github-actions + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `39ba8606451d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1814/tests/oracle.patch b/tasks/lite-xl__lite-xl-1814/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3e32137d1a24beb0ddb8351d6cd73b4c4444590c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/.github/dependabot.yml b/.github/dependabot.yml +new file mode 100644 +index 00000000..3f4f0b92 +--- /dev/null ++++ b/.github/dependabot.yml +@@ -0,0 +1,9 @@ ++version: 2 ++updates: ++ - package-ecosystem: github-actions ++ directory: "/" ++ schedule: ++ interval: weekly ++ groups: ++ github-actions: ++ patterns: ["*"] diff --git a/tasks/lite-xl__lite-xl-1814/tests/test.sh b/tasks/lite-xl__lite-xl-1814/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8acb957d2675975b38e177042cf5eb6ff8679fd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/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 39ba8606451db00f1b151020995fdad47f9c5d8b > "$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/lite-xl__lite-xl-1814/tests/verifier.py b/tasks/lite-xl__lite-xl-1814/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1814/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/lite-xl__lite-xl-1815/environment/Dockerfile b/tasks/lite-xl__lite-xl-1815/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..667c540f2ab7a255f4c101000d167be043a18003 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a9d918901e9966d90b3fe9414b3ef81412071635 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a9d918901e9966d90b3fe9414b3ef81412071635 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a9d918901e9966d90b3fe9414b3ef81412071635 \ + && 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/lite-xl__lite-xl-1815/instruction.md b/tasks/lite-xl__lite-xl-1815/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b2315f2e7981470c82064451a3b46e71bf64427 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update macOS copyright notice + +## Description + +New copyright: + +![image](https://github.com/lite-xl/lite-xl/assets/20792268/8656b48e-262b-43a9-a183-a738f9bdac1d) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9d918901e99`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1815/solution/patch.diff b/tasks/lite-xl__lite-xl-1815/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ff4887489d05ee5c161c80a4244abcb1b1c266ef --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/meson.build b/meson.build +index fc43e20e..023507ec 100644 +--- a/meson.build ++++ b/meson.build +@@ -192,6 +192,10 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + lite_bindir = 'Contents/MacOS' + lite_docdir = 'Contents/Resources' + lite_datadir = 'Contents/Resources' ++ conf_data.set( ++ 'CURRENT_YEAR', ++ run_command('date', '+%Y', capture: true).stdout().strip() ++ ) + install_data('resources/icons/icon.icns', install_dir : 'Contents/Resources') + configure_file( + input : 'resources/macos/Info.plist.in', +diff --git a/resources/macos/Info.plist.in b/resources/macos/Info.plist.in +index 6fe6b751..a23d2a79 100644 +--- a/resources/macos/Info.plist.in ++++ b/resources/macos/Info.plist.in +@@ -27,7 +27,9 @@ + CFBundleShortVersionString + @PROJECT_VERSION@ + NSHumanReadableCopyright +- © 2019-2022 Lite XL Team ++ © 2020 rxi ++© 2020-2022 Francesco Abbate ++© 2022-@CURRENT_YEAR@ Lite XL Team + + + diff --git a/tasks/lite-xl__lite-xl-1815/solution/solve.sh b/tasks/lite-xl__lite-xl-1815/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/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/lite-xl__lite-xl-1815/task.toml b/tasks/lite-xl__lite-xl-1815/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..727cb8634e6d9737ed16db0b1650b6901bcf4bfc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1815" +description = "Update macOS copyright notice" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "a9d918901e9966d90b3fe9414b3ef81412071635" +reference = "https://github.com/lite-xl/lite-xl/pull/1815" +source_access = "auto" +built_at = "2026-11-16T16:09:56.209747+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fa0d100d0c6ae7ecc732dedc7e6a45d3632d3db4f24f1ae823dbb79f862fd7ff" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-18T13:00:14Z" +diff_format = "unified" +context_files = [ + "meson.build", + "resources/macos/Info.plist.in", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.298173+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bed0594787ca06d9e0fefe560369185400bf820b84181b0c5544c5fde330192e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1815/tests/capture.py b/tasks/lite-xl__lite-xl-1815/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/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/lite-xl__lite-xl-1815/tests/instruction.md b/tasks/lite-xl__lite-xl-1815/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b2315f2e7981470c82064451a3b46e71bf64427 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Update macOS copyright notice + +## Description + +New copyright: + +![image](https://github.com/lite-xl/lite-xl/assets/20792268/8656b48e-262b-43a9-a183-a738f9bdac1d) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a9d918901e99`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1815/tests/oracle.patch b/tasks/lite-xl__lite-xl-1815/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ff4887489d05ee5c161c80a4244abcb1b1c266ef --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/meson.build b/meson.build +index fc43e20e..023507ec 100644 +--- a/meson.build ++++ b/meson.build +@@ -192,6 +192,10 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + lite_bindir = 'Contents/MacOS' + lite_docdir = 'Contents/Resources' + lite_datadir = 'Contents/Resources' ++ conf_data.set( ++ 'CURRENT_YEAR', ++ run_command('date', '+%Y', capture: true).stdout().strip() ++ ) + install_data('resources/icons/icon.icns', install_dir : 'Contents/Resources') + configure_file( + input : 'resources/macos/Info.plist.in', +diff --git a/resources/macos/Info.plist.in b/resources/macos/Info.plist.in +index 6fe6b751..a23d2a79 100644 +--- a/resources/macos/Info.plist.in ++++ b/resources/macos/Info.plist.in +@@ -27,7 +27,9 @@ + CFBundleShortVersionString + @PROJECT_VERSION@ + NSHumanReadableCopyright +- © 2019-2022 Lite XL Team ++ © 2020 rxi ++© 2020-2022 Francesco Abbate ++© 2022-@CURRENT_YEAR@ Lite XL Team + + + diff --git a/tasks/lite-xl__lite-xl-1815/tests/test.sh b/tasks/lite-xl__lite-xl-1815/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6cd7415e625ef1b523be9f158a8afd2d6091b66f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/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 a9d918901e9966d90b3fe9414b3ef81412071635 > "$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/lite-xl__lite-xl-1815/tests/verifier.py b/tasks/lite-xl__lite-xl-1815/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1815/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/lite-xl__lite-xl-1818/environment/Dockerfile b/tasks/lite-xl__lite-xl-1818/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e09aa27e5749776ac3fba7e66ae627b89ae7a535 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4df2871a46647a5b2d98508e3548241430b68822 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4df2871a46647a5b2d98508e3548241430b68822 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4df2871a46647a5b2d98508e3548241430b68822 \ + && 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/lite-xl__lite-xl-1818/instruction.md b/tasks/lite-xl__lite-xl-1818/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..786275f801826e1300596bf4d925728cc205c09c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** language_cpp: backport number highlighting from c + +## Description + +Backported #1752 for C++. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4df2871a4664`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1818/solution/patch.diff b/tasks/lite-xl__lite-xl-1818/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9f94cfa2df4372849199c272ed976f92096e7846 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/data/plugins/language_cpp.lua b/data/plugins/language_cpp.lua +index 4efd50ed..d2486736 100644 +--- a/data/plugins/language_cpp.lua ++++ b/data/plugins/language_cpp.lua +@@ -1,6 +1,11 @@ + -- mod-version:3 + local syntax = require "core.syntax" + ++-- integer suffix combinations as a regex ++local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] ++-- float suffix combinations as a Lua pattern / regex ++local fsuf = "[fFlL]?" ++ + syntax.add { + name = "C++", + files = { +@@ -15,9 +20,13 @@ syntax.add { + { pattern = { "/%*", "%*/" }, type = "comment" }, + { pattern = { '"', '"', '\\' }, type = "string" }, + { pattern = { "'", "'", '\\' }, type = "string" }, +- { pattern = "0x%x+[%x']*", type = "number" }, +- { pattern = "%d+[%d%.'eE]*f?", type = "number" }, +- { pattern = "%.?%d+[%d']*f?", type = "number" }, ++ { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, ++ { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, ++ { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, ++ { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, ++ { pattern = "%d+%.%d*"..fsuf, type = "number" }, ++ { pattern = "%.%d+"..fsuf, type = "number" }, ++ { regex = "\\d+"..isuf, type = "number" }, + { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, + { pattern = "##", type = "operator" }, + { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, diff --git a/tasks/lite-xl__lite-xl-1818/solution/solve.sh b/tasks/lite-xl__lite-xl-1818/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/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/lite-xl__lite-xl-1818/task.toml b/tasks/lite-xl__lite-xl-1818/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8100cc8a8a2788ddc206cb6995bf8b1f1a1995b6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1818" +description = "language_cpp: backport number highlighting from c" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "4df2871a46647a5b2d98508e3548241430b68822" +reference = "https://github.com/lite-xl/lite-xl/pull/1818" +source_access = "auto" +built_at = "2026-11-16T16:09:56.218280+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:77ed8edbf59afd9a0aa35793ed13c5e20f3525fdd66abcc9e3d5bc6eda5f8b31" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-20T02:16:39Z" +diff_format = "unified" +context_files = [ + "data/plugins/language_cpp.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.298615+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:13d364d7f11379c39a1165be3f077f9a1873e66e854065d32ae865bb5f9c9113" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1818/tests/capture.py b/tasks/lite-xl__lite-xl-1818/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/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/lite-xl__lite-xl-1818/tests/instruction.md b/tasks/lite-xl__lite-xl-1818/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..786275f801826e1300596bf4d925728cc205c09c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** language_cpp: backport number highlighting from c + +## Description + +Backported #1752 for C++. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4df2871a4664`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1818/tests/oracle.patch b/tasks/lite-xl__lite-xl-1818/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9f94cfa2df4372849199c272ed976f92096e7846 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/data/plugins/language_cpp.lua b/data/plugins/language_cpp.lua +index 4efd50ed..d2486736 100644 +--- a/data/plugins/language_cpp.lua ++++ b/data/plugins/language_cpp.lua +@@ -1,6 +1,11 @@ + -- mod-version:3 + local syntax = require "core.syntax" + ++-- integer suffix combinations as a regex ++local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] ++-- float suffix combinations as a Lua pattern / regex ++local fsuf = "[fFlL]?" ++ + syntax.add { + name = "C++", + files = { +@@ -15,9 +20,13 @@ syntax.add { + { pattern = { "/%*", "%*/" }, type = "comment" }, + { pattern = { '"', '"', '\\' }, type = "string" }, + { pattern = { "'", "'", '\\' }, type = "string" }, +- { pattern = "0x%x+[%x']*", type = "number" }, +- { pattern = "%d+[%d%.'eE]*f?", type = "number" }, +- { pattern = "%.?%d+[%d']*f?", type = "number" }, ++ { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, ++ { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, ++ { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, ++ { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, ++ { pattern = "%d+%.%d*"..fsuf, type = "number" }, ++ { pattern = "%.%d+"..fsuf, type = "number" }, ++ { regex = "\\d+"..isuf, type = "number" }, + { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, + { pattern = "##", type = "operator" }, + { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, diff --git a/tasks/lite-xl__lite-xl-1818/tests/test.sh b/tasks/lite-xl__lite-xl-1818/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..617b3b9f887da0665549ef1a8ac8f96fd462b23a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/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 4df2871a46647a5b2d98508e3548241430b68822 > "$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/lite-xl__lite-xl-1818/tests/verifier.py b/tasks/lite-xl__lite-xl-1818/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1818/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/lite-xl__lite-xl-1822/environment/Dockerfile b/tasks/lite-xl__lite-xl-1822/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57941f1a172023e992d3f52e17bce8cce46340 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 290c7bc27f2df03b7d826f15b99f29d4e3492c6c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 290c7bc27f2df03b7d826f15b99f29d4e3492c6c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 290c7bc27f2df03b7d826f15b99f29d4e3492c6c \ + && 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/lite-xl__lite-xl-1822/instruction.md b/tasks/lite-xl__lite-xl-1822/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14f92f667d8ebdaa05cace2f53af87c53b9bd47e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** macos: support drag-and-drop and default file associations + +## Description + +. + +~~Aside from fixes from our side, I am also planning to take this up to SDL2 and see if they would adapt the changes. It would eliminate the need of method swizzling if they adopted it.~~ + +No need for all that, this is just a info.plist change. + +A potential issue is that the supported file extension can be too "wide", perhaps we should limit it? + +https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-101685 + +## Before + +https://github.com/lite-xl/lite-xl/assets/20792268/41558f6b-02fa-4cb0-a1b3-f7a112c51c54 + +## After + +https://github.com/lite-xl/lite-xl/assets/20792268/ca464ad5-f0c9-4922-81d4-8d965912b9aa + +https://github.com/lite-xl/lite-xl/assets/20792268/2ad1fdbd-7161-47b5-a711-31627da6ffa5 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `290c7bc27f2d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1822/solution/patch.diff b/tasks/lite-xl__lite-xl-1822/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f9fac56de24c388841afda66760eb0823f15f475 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/data/core/init.lua b/data/core/init.lua +index 910c24a3..ec6cebd5 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -1313,20 +1313,7 @@ function core.on_event(type, ...) + elseif type == "minimized" or type == "maximized" or type == "restored" then + core.window_mode = type == "restored" and "normal" or type + elseif type == "filedropped" then +- if not core.root_view:on_file_dropped(...) then +- local filename, mx, my = ... +- local info = system.get_file_info(filename) +- if info and info.type == "dir" then +- system.exec(string.format("%q %q", EXEFILE, filename)) +- else +- local ok, doc = core.try(core.open_doc, filename) +- if ok then +- local node = core.root_view.root_node:get_child_overlapping_point(mx, my) +- node:set_active_view(node.active_view) +- core.root_view:open_doc(doc) +- end +- end +- end ++ core.root_view:on_file_dropped(...) + elseif type == "focuslost" then + core.root_view:on_focus_lost(...) + elseif type == "quit" then +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index ec9d5e0e..965203fe 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -27,6 +27,7 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil ++ self.first_update_done = false + end + + +@@ -372,7 +373,28 @@ end + ---@return boolean + function RootView:on_file_dropped(filename, x, y) + local node = self.root_node:get_child_overlapping_point(x, y) +- return node and node.active_view:on_file_dropped(filename, x, y) ++ local result = node and node.active_view:on_file_dropped(filename, x, y) ++ if result then return result end ++ local info = system.get_file_info(filename) ++ if info and info.type == "dir" then ++ if self.first_update_done then ++ -- first update done, open in new window ++ system.exec(string.format("%q %q", EXEFILE, filename)) ++ else ++ -- DND event before first update, this is sent by macOS when folder is dropped into the dock ++ core.confirm_close_docs(core.docs, function(dirpath) ++ core.open_folder_project(dirpath) ++ end, system.absolute_path(filename)) ++ end ++ else ++ local ok, doc = core.try(core.open_doc, filename) ++ if ok then ++ local node = core.root_view.root_node:get_child_overlapping_point(x, y) ++ node:set_active_view(node.active_view) ++ core.root_view:open_doc(doc) ++ end ++ end ++ return true + end + + +@@ -460,6 +482,7 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) ++ self.first_update_done = true + end + + +diff --git a/resources/macos/Info.plist.in b/resources/macos/Info.plist.in +index a23d2a79..17d7408d 100644 +--- a/resources/macos/Info.plist.in ++++ b/resources/macos/Info.plist.in +@@ -8,8 +8,32 @@ + lite-xl + CFBundleIconFile + icon.icns +- CFBundleIdentifier +- com.lite-xl ++ CFBundleDocumentTypes ++ ++ ++ CFBundleTypeExtensions ++ ++ * ++ ++ CFBundleTypeRole ++ Editor ++ NSDocumentClass ++ NSDocument ++ CFBundleTypeName ++ All Files ++ ++ ++ LSItemContentTypes ++ ++ public.text ++ public.folder ++ ++ NSExportableTypes ++ ++ public.text ++ ++ CFBundleIdentifier ++ com.lite-xl + CFBundleName + Lite XL + CFBundlePackageType diff --git a/tasks/lite-xl__lite-xl-1822/solution/solve.sh b/tasks/lite-xl__lite-xl-1822/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/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/lite-xl__lite-xl-1822/task.toml b/tasks/lite-xl__lite-xl-1822/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c77d47b892c1fab799c79958923e653726979ea9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1822" +description = "macos: support drag-and-drop and default file associations" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "290c7bc27f2df03b7d826f15b99f29d4e3492c6c" +reference = "https://github.com/lite-xl/lite-xl/pull/1822" +source_access = "auto" +built_at = "2026-11-16T16:09:56.202195+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:241768150c820c37f0258d05e1ac895eea690f1cf8c7ce8da5788763510a31a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-22T04:23:06Z" +diff_format = "unified" +context_files = [ + "data/core/init.lua", + "data/core/rootview.lua", + "resources/macos/Info.plist.in", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 68 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.299061+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5a566cb02f863c04d04b5de012f070d8997845b2d243c031fe33d6000e8c9e85" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1822/tests/capture.py b/tasks/lite-xl__lite-xl-1822/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/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/lite-xl__lite-xl-1822/tests/instruction.md b/tasks/lite-xl__lite-xl-1822/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14f92f667d8ebdaa05cace2f53af87c53b9bd47e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** macos: support drag-and-drop and default file associations + +## Description + +. + +~~Aside from fixes from our side, I am also planning to take this up to SDL2 and see if they would adapt the changes. It would eliminate the need of method swizzling if they adopted it.~~ + +No need for all that, this is just a info.plist change. + +A potential issue is that the supported file extension can be too "wide", perhaps we should limit it? + +https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html#//apple_ref/doc/uid/20001431-101685 + +## Before + +https://github.com/lite-xl/lite-xl/assets/20792268/41558f6b-02fa-4cb0-a1b3-f7a112c51c54 + +## After + +https://github.com/lite-xl/lite-xl/assets/20792268/ca464ad5-f0c9-4922-81d4-8d965912b9aa + +https://github.com/lite-xl/lite-xl/assets/20792268/2ad1fdbd-7161-47b5-a711-31627da6ffa5 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `290c7bc27f2d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1822/tests/oracle.patch b/tasks/lite-xl__lite-xl-1822/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f9fac56de24c388841afda66760eb0823f15f475 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/data/core/init.lua b/data/core/init.lua +index 910c24a3..ec6cebd5 100644 +--- a/data/core/init.lua ++++ b/data/core/init.lua +@@ -1313,20 +1313,7 @@ function core.on_event(type, ...) + elseif type == "minimized" or type == "maximized" or type == "restored" then + core.window_mode = type == "restored" and "normal" or type + elseif type == "filedropped" then +- if not core.root_view:on_file_dropped(...) then +- local filename, mx, my = ... +- local info = system.get_file_info(filename) +- if info and info.type == "dir" then +- system.exec(string.format("%q %q", EXEFILE, filename)) +- else +- local ok, doc = core.try(core.open_doc, filename) +- if ok then +- local node = core.root_view.root_node:get_child_overlapping_point(mx, my) +- node:set_active_view(node.active_view) +- core.root_view:open_doc(doc) +- end +- end +- end ++ core.root_view:on_file_dropped(...) + elseif type == "focuslost" then + core.root_view:on_focus_lost(...) + elseif type == "quit" then +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index ec9d5e0e..965203fe 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -27,6 +27,7 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil ++ self.first_update_done = false + end + + +@@ -372,7 +373,28 @@ end + ---@return boolean + function RootView:on_file_dropped(filename, x, y) + local node = self.root_node:get_child_overlapping_point(x, y) +- return node and node.active_view:on_file_dropped(filename, x, y) ++ local result = node and node.active_view:on_file_dropped(filename, x, y) ++ if result then return result end ++ local info = system.get_file_info(filename) ++ if info and info.type == "dir" then ++ if self.first_update_done then ++ -- first update done, open in new window ++ system.exec(string.format("%q %q", EXEFILE, filename)) ++ else ++ -- DND event before first update, this is sent by macOS when folder is dropped into the dock ++ core.confirm_close_docs(core.docs, function(dirpath) ++ core.open_folder_project(dirpath) ++ end, system.absolute_path(filename)) ++ end ++ else ++ local ok, doc = core.try(core.open_doc, filename) ++ if ok then ++ local node = core.root_view.root_node:get_child_overlapping_point(x, y) ++ node:set_active_view(node.active_view) ++ core.root_view:open_doc(doc) ++ end ++ end ++ return true + end + + +@@ -460,6 +482,7 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) ++ self.first_update_done = true + end + + +diff --git a/resources/macos/Info.plist.in b/resources/macos/Info.plist.in +index a23d2a79..17d7408d 100644 +--- a/resources/macos/Info.plist.in ++++ b/resources/macos/Info.plist.in +@@ -8,8 +8,32 @@ + lite-xl + CFBundleIconFile + icon.icns +- CFBundleIdentifier +- com.lite-xl ++ CFBundleDocumentTypes ++ ++ ++ CFBundleTypeExtensions ++ ++ * ++ ++ CFBundleTypeRole ++ Editor ++ NSDocumentClass ++ NSDocument ++ CFBundleTypeName ++ All Files ++ ++ ++ LSItemContentTypes ++ ++ public.text ++ public.folder ++ ++ NSExportableTypes ++ ++ public.text ++ ++ CFBundleIdentifier ++ com.lite-xl + CFBundleName + Lite XL + CFBundlePackageType diff --git a/tasks/lite-xl__lite-xl-1822/tests/test.sh b/tasks/lite-xl__lite-xl-1822/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab18395e3d7199ece3296040a7b7f3aa64c07625 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/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 290c7bc27f2df03b7d826f15b99f29d4e3492c6c > "$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/lite-xl__lite-xl-1822/tests/verifier.py b/tasks/lite-xl__lite-xl-1822/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1822/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/lite-xl__lite-xl-1828/environment/Dockerfile b/tasks/lite-xl__lite-xl-1828/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc9850334065f115eda517a47bdf3af14452109c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 74fcd19ac2b51c0e8b2a6cdc0e49f5d04e651db0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 74fcd19ac2b51c0e8b2a6cdc0e49f5d04e651db0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 74fcd19ac2b51c0e8b2a6cdc0e49f5d04e651db0 \ + && 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/lite-xl__lite-xl-1828/instruction.md b/tasks/lite-xl__lite-xl-1828/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2589a6fa5827015ae7bd216ecc08d0ee71bb7608 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** core/rootview: fix dnd multiple folders into dock + +## Description + +This PR fixes a bug in #1822 that causes multi-folder drag and drop open only the last folder. This PR makes it so that the first pre-update DnD event changes the project folder, and all subsequent DnD events open new instances of Lite XL. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74fcd19ac2b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1828/solution/patch.diff b/tasks/lite-xl__lite-xl-1828/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2b4f839f638b8915d6c0c1e6a42483003398ff2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index 965203fe..06e3c28f 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -27,7 +27,7 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil +- self.first_update_done = false ++ self.first_dnd_processed = false + end + + +@@ -377,7 +377,7 @@ function RootView:on_file_dropped(filename, x, y) + if result then return result end + local info = system.get_file_info(filename) + if info and info.type == "dir" then +- if self.first_update_done then ++ if self.first_dnd_processed then + -- first update done, open in new window + system.exec(string.format("%q %q", EXEFILE, filename)) + else +@@ -385,6 +385,7 @@ function RootView:on_file_dropped(filename, x, y) + core.confirm_close_docs(core.docs, function(dirpath) + core.open_folder_project(dirpath) + end, system.absolute_path(filename)) ++ self.first_dnd_processed = true + end + else + local ok, doc = core.try(core.open_doc, filename) +@@ -482,7 +483,9 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) +- self.first_update_done = true ++ -- set this to true because at this point there are no dnd requests ++ -- that are caused by the initial dnd into dock user action ++ self.first_dnd_processed = true + end + + diff --git a/tasks/lite-xl__lite-xl-1828/solution/solve.sh b/tasks/lite-xl__lite-xl-1828/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/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/lite-xl__lite-xl-1828/task.toml b/tasks/lite-xl__lite-xl-1828/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0fdbc4fc0475a16fb9bb84423f90fb0606460642 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1828" +description = "core/rootview: fix dnd multiple folders into dock" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "74fcd19ac2b51c0e8b2a6cdc0e49f5d04e651db0" +reference = "https://github.com/lite-xl/lite-xl/pull/1828" +source_access = "auto" +built_at = "2026-11-16T16:09:56.200864+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:74d181d47a4d54aa00d2f805f6e0756e57bf25d9d94bf63dd9d61f140ffb2e31" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-06-23T05:09:07Z" +diff_format = "unified" +context_files = [ + "data/core/rootview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.299509+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:411ea2b74817241f5c1118a41927d2f4c63d672bcd721e77d8ddacc46d62d06b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1828/tests/capture.py b/tasks/lite-xl__lite-xl-1828/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/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/lite-xl__lite-xl-1828/tests/instruction.md b/tasks/lite-xl__lite-xl-1828/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2589a6fa5827015ae7bd216ecc08d0ee71bb7608 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** core/rootview: fix dnd multiple folders into dock + +## Description + +This PR fixes a bug in #1822 that causes multi-folder drag and drop open only the last folder. This PR makes it so that the first pre-update DnD event changes the project folder, and all subsequent DnD events open new instances of Lite XL. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74fcd19ac2b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1828/tests/oracle.patch b/tasks/lite-xl__lite-xl-1828/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2b4f839f638b8915d6c0c1e6a42483003398ff2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index 965203fe..06e3c28f 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -27,7 +27,7 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil +- self.first_update_done = false ++ self.first_dnd_processed = false + end + + +@@ -377,7 +377,7 @@ function RootView:on_file_dropped(filename, x, y) + if result then return result end + local info = system.get_file_info(filename) + if info and info.type == "dir" then +- if self.first_update_done then ++ if self.first_dnd_processed then + -- first update done, open in new window + system.exec(string.format("%q %q", EXEFILE, filename)) + else +@@ -385,6 +385,7 @@ function RootView:on_file_dropped(filename, x, y) + core.confirm_close_docs(core.docs, function(dirpath) + core.open_folder_project(dirpath) + end, system.absolute_path(filename)) ++ self.first_dnd_processed = true + end + else + local ok, doc = core.try(core.open_doc, filename) +@@ -482,7 +483,9 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) +- self.first_update_done = true ++ -- set this to true because at this point there are no dnd requests ++ -- that are caused by the initial dnd into dock user action ++ self.first_dnd_processed = true + end + + diff --git a/tasks/lite-xl__lite-xl-1828/tests/test.sh b/tasks/lite-xl__lite-xl-1828/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bb709c40e1ebb9f6ee6ecc6c705bcbc54268987 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/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 74fcd19ac2b51c0e8b2a6cdc0e49f5d04e651db0 > "$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/lite-xl__lite-xl-1828/tests/verifier.py b/tasks/lite-xl__lite-xl-1828/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1828/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/lite-xl__lite-xl-1830/environment/Dockerfile b/tasks/lite-xl__lite-xl-1830/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54bd75e8d98bc318f83184bb87d04a2e7582c718 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e0db40ce70a1ae2c468dd2d4c2143096fa4c8c66 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e0db40ce70a1ae2c468dd2d4c2143096fa4c8c66 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e0db40ce70a1ae2c468dd2d4c2143096fa4c8c66 \ + && 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/lite-xl__lite-xl-1830/instruction.md b/tasks/lite-xl__lite-xl-1830/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f4595f138d5367e7c6c0e428058e1968f41e5f9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Improve folder drag-and-drop experience + +## Description + +### Before +When you drag a folder into Lite XL, Lite XL opens another instance. This might confuse new users, which expects it to open in the same instance. + +### After +Lite XL prompts the user (for each folder) if they should add the directory to current project (this window) or open the project directory (new instance). + +[Screencast_20240623_220354.webm](https://github.com/lite-xl/lite-xl/assets/20792268/d2672733-c0a1-44be-91fc-c2bbff138c12) + +### Other considerations +There was a suggestion to make it "smarter": if the user places the folder in TreeView, then the folder should be added to current project. This is currently impossible with SDL because the SDL_DROPBEGIN event is utterly useless (it does not signify if the drag-and-drop item _enters_ the window). + +Another suggestion is to make Lite XL ask only once for all pending folders. I personally think that more control should be given to the user, but with how NagView is designed it's hard to put the "Yes to all" and "No to all" option here. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e0db40ce70a1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1830/solution/patch.diff b/tasks/lite-xl__lite-xl-1830/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8bdca753a9f1ee421be56b0999b3f6bfaaf5d325 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/solution/patch.diff @@ -0,0 +1,107 @@ +diff --git a/data/core/nagview.lua b/data/core/nagview.lua +index 71272962..98860d1e 100644 +--- a/data/core/nagview.lua ++++ b/data/core/nagview.lua +@@ -305,7 +305,7 @@ function NagView:show(title, message, options, on_select) + opts.options = assert(options, "No options") + opts.on_selected = on_select or noop + table.insert(self.queue, opts) +- self:next() ++ if not self.visible then self:next() end + end + + return NagView +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index c4daca7b..8f94f475 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -29,7 +29,9 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil ++ self.defer_open_docs = {} + self.first_dnd_processed = false ++ self.first_update_done = false + end + + +@@ -379,17 +381,55 @@ function RootView:on_file_dropped(filename, x, y) + if result then return result end + local info = system.get_file_info(filename) + if info and info.type == "dir" then ++ local abspath = system.absolute_path(filename) --[[@as string]] ++ if self.first_update_done then ++ -- ask the user if they want to open it here or somewhere else ++ core.nag_view:show( ++ "Open directory", ++ string.format('You are trying to open "%s"\n', common.home_encode(abspath)) ++ .. "Do you want to open this directory here, or in a new window?", ++ { ++ { text = "Current window", default_yes = true }, ++ { text = "New window", default_no = true }, ++ { text = "Cancel" } ++ }, ++ function(opt) ++ if opt.text == "Current window" then ++ core.add_project(abspath) ++ elseif opt.text == "New window" then ++ system.exec(string.format("%q %q", EXEFILE, filename)) ++ end ++ end ++ ) ++ return true ++ end ++ -- in macOS, when dropping folders into Lite XL in the dock, ++ -- the OS tries to start an instance of Lite XL with each folder as a DND request. ++ -- When this happens, the DND request always arrive before the first update() call. ++ -- We need to change the current project folder for the first request, and start ++ -- new instances for the rest to emulate existing behavior. + if self.first_dnd_processed then +- -- first update done, open in new window ++ -- FIXME: port to process API + system.exec(string.format("%q %q", EXEFILE, filename)) + else +- -- DND event before first update, this is sent by macOS when folder is dropped into the dock ++ -- change project directory + core.confirm_close_docs(core.docs, function(dirpath) + core.open_folder_project(dirpath) + end, system.absolute_path(filename)) + self.first_dnd_processed = true + end +- else ++ return true ++ end ++ -- defer opening docs in case nagview is visible (which will cause a locked node error) ++ table.insert(self.defer_open_docs, { filename, x, y }) ++ return true ++end ++ ++function RootView:process_defer_open_docs() ++ if core.active_view == core.nag_view then return end ++ for _, drop in ipairs(self.defer_open_docs) do ++ -- file dragged into lite-xl, try to open it ++ local filename, x, y = table.unpack(drop) + local ok, doc = core.try(core.open_doc, filename) + if ok then + local node = core.root_view.root_node:get_child_overlapping_point(x, y) +@@ -397,7 +437,7 @@ function RootView:on_file_dropped(filename, x, y) + core.root_view:open_doc(doc) + end + end +- return true ++ self.defer_open_docs = {} + end + + +@@ -485,9 +525,8 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) +- -- set this to true because at this point there are no dnd requests +- -- that are caused by the initial dnd into dock user action +- self.first_dnd_processed = true ++ self:process_defer_open_docs() ++ self.first_update_done = true + end + + diff --git a/tasks/lite-xl__lite-xl-1830/solution/solve.sh b/tasks/lite-xl__lite-xl-1830/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/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/lite-xl__lite-xl-1830/task.toml b/tasks/lite-xl__lite-xl-1830/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..55ef18c3c12657ad7f79f1e9501f00e80b64b8a3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1830" +description = "Improve folder drag-and-drop experience" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e0db40ce70a1ae2c468dd2d4c2143096fa4c8c66" +reference = "https://github.com/lite-xl/lite-xl/pull/1830" +source_access = "auto" +built_at = "2026-11-16T16:09:56.173523+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:364b2d5a79c0ec9f03510409677ec5a3a05f401b0f17ad324a94b30596464224" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-08-29T15:47:08Z" +diff_format = "unified" +context_files = [ + "data/core/nagview.lua", + "data/core/rootview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 55 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.299955+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:60b4e59bdae76a58dfa16c3a16c11e64fe2eacfea8a5edf647485db2798123b1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1830/tests/capture.py b/tasks/lite-xl__lite-xl-1830/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/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/lite-xl__lite-xl-1830/tests/instruction.md b/tasks/lite-xl__lite-xl-1830/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f4595f138d5367e7c6c0e428058e1968f41e5f9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Improve folder drag-and-drop experience + +## Description + +### Before +When you drag a folder into Lite XL, Lite XL opens another instance. This might confuse new users, which expects it to open in the same instance. + +### After +Lite XL prompts the user (for each folder) if they should add the directory to current project (this window) or open the project directory (new instance). + +[Screencast_20240623_220354.webm](https://github.com/lite-xl/lite-xl/assets/20792268/d2672733-c0a1-44be-91fc-c2bbff138c12) + +### Other considerations +There was a suggestion to make it "smarter": if the user places the folder in TreeView, then the folder should be added to current project. This is currently impossible with SDL because the SDL_DROPBEGIN event is utterly useless (it does not signify if the drag-and-drop item _enters_ the window). + +Another suggestion is to make Lite XL ask only once for all pending folders. I personally think that more control should be given to the user, but with how NagView is designed it's hard to put the "Yes to all" and "No to all" option here. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e0db40ce70a1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1830/tests/oracle.patch b/tasks/lite-xl__lite-xl-1830/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8bdca753a9f1ee421be56b0999b3f6bfaaf5d325 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/tests/oracle.patch @@ -0,0 +1,107 @@ +diff --git a/data/core/nagview.lua b/data/core/nagview.lua +index 71272962..98860d1e 100644 +--- a/data/core/nagview.lua ++++ b/data/core/nagview.lua +@@ -305,7 +305,7 @@ function NagView:show(title, message, options, on_select) + opts.options = assert(options, "No options") + opts.on_selected = on_select or noop + table.insert(self.queue, opts) +- self:next() ++ if not self.visible then self:next() end + end + + return NagView +diff --git a/data/core/rootview.lua b/data/core/rootview.lua +index c4daca7b..8f94f475 100644 +--- a/data/core/rootview.lua ++++ b/data/core/rootview.lua +@@ -29,7 +29,9 @@ function RootView:new() + self.grab = nil -- = {view = nil, button = nil} + self.overlapping_view = nil + self.touched_view = nil ++ self.defer_open_docs = {} + self.first_dnd_processed = false ++ self.first_update_done = false + end + + +@@ -379,17 +381,55 @@ function RootView:on_file_dropped(filename, x, y) + if result then return result end + local info = system.get_file_info(filename) + if info and info.type == "dir" then ++ local abspath = system.absolute_path(filename) --[[@as string]] ++ if self.first_update_done then ++ -- ask the user if they want to open it here or somewhere else ++ core.nag_view:show( ++ "Open directory", ++ string.format('You are trying to open "%s"\n', common.home_encode(abspath)) ++ .. "Do you want to open this directory here, or in a new window?", ++ { ++ { text = "Current window", default_yes = true }, ++ { text = "New window", default_no = true }, ++ { text = "Cancel" } ++ }, ++ function(opt) ++ if opt.text == "Current window" then ++ core.add_project(abspath) ++ elseif opt.text == "New window" then ++ system.exec(string.format("%q %q", EXEFILE, filename)) ++ end ++ end ++ ) ++ return true ++ end ++ -- in macOS, when dropping folders into Lite XL in the dock, ++ -- the OS tries to start an instance of Lite XL with each folder as a DND request. ++ -- When this happens, the DND request always arrive before the first update() call. ++ -- We need to change the current project folder for the first request, and start ++ -- new instances for the rest to emulate existing behavior. + if self.first_dnd_processed then +- -- first update done, open in new window ++ -- FIXME: port to process API + system.exec(string.format("%q %q", EXEFILE, filename)) + else +- -- DND event before first update, this is sent by macOS when folder is dropped into the dock ++ -- change project directory + core.confirm_close_docs(core.docs, function(dirpath) + core.open_folder_project(dirpath) + end, system.absolute_path(filename)) + self.first_dnd_processed = true + end +- else ++ return true ++ end ++ -- defer opening docs in case nagview is visible (which will cause a locked node error) ++ table.insert(self.defer_open_docs, { filename, x, y }) ++ return true ++end ++ ++function RootView:process_defer_open_docs() ++ if core.active_view == core.nag_view then return end ++ for _, drop in ipairs(self.defer_open_docs) do ++ -- file dragged into lite-xl, try to open it ++ local filename, x, y = table.unpack(drop) + local ok, doc = core.try(core.open_doc, filename) + if ok then + local node = core.root_view.root_node:get_child_overlapping_point(x, y) +@@ -397,7 +437,7 @@ function RootView:on_file_dropped(filename, x, y) + core.root_view:open_doc(doc) + end + end +- return true ++ self.defer_open_docs = {} + end + + +@@ -485,9 +525,8 @@ function RootView:update() + self:update_drag_overlay() + self:interpolate_drag_overlay(self.drag_overlay) + self:interpolate_drag_overlay(self.drag_overlay_tab) +- -- set this to true because at this point there are no dnd requests +- -- that are caused by the initial dnd into dock user action +- self.first_dnd_processed = true ++ self:process_defer_open_docs() ++ self.first_update_done = true + end + + diff --git a/tasks/lite-xl__lite-xl-1830/tests/test.sh b/tasks/lite-xl__lite-xl-1830/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d95a5ec8033a7a50dfe2090d287231fa40efabaf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/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 e0db40ce70a1ae2c468dd2d4c2143096fa4c8c66 > "$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/lite-xl__lite-xl-1830/tests/verifier.py b/tasks/lite-xl__lite-xl-1830/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1830/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/lite-xl__lite-xl-1852/environment/Dockerfile b/tasks/lite-xl__lite-xl-1852/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d83aae5d63144ac4eaecbcc7e40ec0948086d52a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3d0344393c12b1efe947969a9fcca9eb08603536 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3d0344393c12b1efe947969a9fcca9eb08603536 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3d0344393c12b1efe947969a9fcca9eb08603536 \ + && 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/lite-xl__lite-xl-1852/instruction.md b/tasks/lite-xl__lite-xl-1852/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a526535f5eb0c08889b54db5ec10267c55c2eac1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** api/system: check if a window is created when firing DND events + +## Description + +Tested to work. +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3d0344393c12`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1852/solution/patch.diff b/tasks/lite-xl__lite-xl-1852/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..17d8c5dad490a3de51925d23b8ca7efdc31a5e93 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/src/api/system.c b/src/api/system.c +index f301dba5..f3af9570 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -228,8 +228,9 @@ top: + SDL_GetMouseState(&mx, &my); + lua_pushstring(L, "filedropped"); + lua_pushstring(L, e.drop.file); +- lua_pushinteger(L, mx * window_renderer->scale_x); +- lua_pushinteger(L, my * window_renderer->scale_y); ++ // a DND into dock event fired before a window is created ++ lua_pushinteger(L, mx * (window_renderer ? window_renderer->scale_x : 0)); ++ lua_pushinteger(L, my * (window_renderer ? window_renderer->scale_y : 0)); + SDL_free(e.drop.file); + return 4; + } diff --git a/tasks/lite-xl__lite-xl-1852/solution/solve.sh b/tasks/lite-xl__lite-xl-1852/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/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/lite-xl__lite-xl-1852/task.toml b/tasks/lite-xl__lite-xl-1852/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd146915104e5401d3b85ad72df6cbd3014f80f5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1852" +description = "api/system: check if a window is created when firing DND events" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "3d0344393c12b1efe947969a9fcca9eb08603536" +reference = "https://github.com/lite-xl/lite-xl/pull/1852" +source_access = "auto" +built_at = "2026-11-16T16:09:56.216935+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4e95ad0e325518fdb2f2cbec39d2855e7fc6b7ab08c86ea919c1a685f323538d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-07-04T14:25:36Z" +diff_format = "unified" +context_files = [ + "src/api/system.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.300381+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b10bc22a8649ea1d7b222dc5221de11bab09859874e1f62eb2855d0b1972384a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1852/tests/capture.py b/tasks/lite-xl__lite-xl-1852/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/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/lite-xl__lite-xl-1852/tests/instruction.md b/tasks/lite-xl__lite-xl-1852/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a526535f5eb0c08889b54db5ec10267c55c2eac1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** api/system: check if a window is created when firing DND events + +## Description + +Tested to work. +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3d0344393c12`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1852/tests/oracle.patch b/tasks/lite-xl__lite-xl-1852/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..17d8c5dad490a3de51925d23b8ca7efdc31a5e93 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/src/api/system.c b/src/api/system.c +index f301dba5..f3af9570 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -228,8 +228,9 @@ top: + SDL_GetMouseState(&mx, &my); + lua_pushstring(L, "filedropped"); + lua_pushstring(L, e.drop.file); +- lua_pushinteger(L, mx * window_renderer->scale_x); +- lua_pushinteger(L, my * window_renderer->scale_y); ++ // a DND into dock event fired before a window is created ++ lua_pushinteger(L, mx * (window_renderer ? window_renderer->scale_x : 0)); ++ lua_pushinteger(L, my * (window_renderer ? window_renderer->scale_y : 0)); + SDL_free(e.drop.file); + return 4; + } diff --git a/tasks/lite-xl__lite-xl-1852/tests/test.sh b/tasks/lite-xl__lite-xl-1852/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bc287e6b96688f789097c55f2fc1ffa07d73f959 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/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 3d0344393c12b1efe947969a9fcca9eb08603536 > "$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/lite-xl__lite-xl-1852/tests/verifier.py b/tasks/lite-xl__lite-xl-1852/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1852/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/lite-xl__lite-xl-1856/environment/Dockerfile b/tasks/lite-xl__lite-xl-1856/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1856/instruction.md b/tasks/lite-xl__lite-xl-1856/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..952d2d59e78383c176bfef08a7901d852d0d465d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** renderer: defer bitmap rendering when possible + +## Description + +ren_font_group_get_width() is getting called a lot while not 100% of the glyphs loaded from this function will be rendered. We can defer the bitmap rendering to ren_draw_text. + +It's hard to benchmark this because the synthetic benchmark would obviously perform well, but that doesn't translate to actual performance. I have some metrics that I've collected by printing the frame time, but so far it has been very inconclusive. + +https://docs.google.com/spreadsheets/d/1OngibXEUds0-rACNCOF5g6OzLWPoSns3QQBLQd_YDbc/edit?usp=sharing + +Other changes including setting the default number of glyphs to 96, height overflow to 0 and width overflow to 9, because with some testing this has less wastage compared to the current values. The atlas is also indexed by bitmap type (8 bits and 24 bits) to further reduce wastage, as all subpixel bitmaps are now put in the same atlas. + +I'm putting this here for more ideas and suggestions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1856/solution/patch.diff b/tasks/lite-xl__lite-xl-1856/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4074fe3f0256b266470bf69494a80c798570503e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/solution/patch.diff @@ -0,0 +1,407 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 8a961995..6200a173 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -34,10 +34,10 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + /************************* Fonts *************************/ + + // approximate number of glyphs per atlas surface +-#define GLYPHS_PER_ATLAS 256 ++#define GLYPHS_PER_ATLAS 96 + // some padding to add to atlas surface to store more glyphs +-#define FONT_HEIGHT_OVERFLOW_PX 6 +-#define FONT_WIDTH_OVERFLOW_PX 6 ++#define FONT_HEIGHT_OVERFLOW_PX 0 ++#define FONT_WIDTH_OVERFLOW_PX 9 + + // maximum unicode codepoint supported (https://stackoverflow.com/a/52203901) + #define MAX_UNICODE 0x10FFFF +@@ -54,20 +54,28 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + // number of subpixel bitmaps + #define SUBPIXEL_BITMAPS_CACHED 3 + ++// the bitmap format of the glyph + typedef enum { +- EGlyphNone = 0, +- EGlyphLoaded = (1 << 0L), +- EGlyphBitmap = (1 << 1L), +- // currently no-op because blits are always assumed to be dual source +- EGlyphDualSource = (1 << 2L), ++ EGlyphFormatGrayscale, // 8bit graysclae ++ EGlyphFormatSubpixel, // 24bit subpixel ++ EGlyphFormatSize ++} ERenGlyphFormat; ++ ++// extra flags to store glyph info ++typedef enum { ++ EGlyphNone = 0, // glyph is not loaded ++ EGlyphXAdvance = (1 << 0L), // xadvance is loaded ++ EGlyphBitmap = (1 << 1L) // bitmap is loaded + } ERenGlyphFlags; + + // metrics for a loaded glyph + typedef struct { ++ float xadvance; + unsigned short atlas_idx, surface_idx; +- unsigned int x1, y0, y1, flags; + int bitmap_left, bitmap_top; +- float xadvance; ++ unsigned int x1, y0, y1; ++ unsigned short flags; ++ unsigned char format; + } GlyphMetric; + + // maps codepoints -> glyph IDs +@@ -85,9 +93,10 @@ typedef struct { + typedef struct { + // accessed with metrics[bitmap_idx][glyph_id / nrow][glyph_id - (row * ncol)] + GlyphMetric *metrics[SUBPIXEL_BITMAPS_CACHED][GLYPHMAP_ROW]; +- // accessed with atlas[bitmap_idx][atlas_idx].surfaces[surface_idx] +- GlyphAtlas *atlas[SUBPIXEL_BITMAPS_CACHED]; +- size_t natlas, bytesize; ++ // accessed by atlas[glyph_format][atlas_idx].surfaces[surface_idx] ++ GlyphAtlas *atlas[EGlyphFormatSize]; ++ size_t natlas[EGlyphFormatSize]; ++ size_t bytesize; + } GlyphMap; + + typedef struct RenFont { +@@ -98,7 +107,7 @@ typedef struct RenFont { + int scale; + #endif + float size, space_advance; +- unsigned short max_height, baseline, height, tab_size; ++ unsigned short baseline, height, tab_size; + unsigned short underline_thickness; + ERenFontAntialiasing antialiasing; + ERenFontHinting hinting; +@@ -193,30 +202,39 @@ static unsigned int font_get_glyph_id(RenFont *font, unsigned int codepoint) { + + #define FONT_IS_SUBPIXEL(F) ((F)->antialiasing == FONT_ANTIALIASING_SUBPIXEL) + #define FONT_BITMAP_COUNT(F) ((F)->antialiasing == FONT_ANTIALIASING_SUBPIXEL ? SUBPIXEL_BITMAPS_CACHED : 1) ++#define SLOT_BITMAP_TYPE(B) ((B).pixel_mode == FT_PIXEL_MODE_LCD ? EGlyphFormatSubpixel : EGlyphFormatGrayscale) ++ ++static inline SDL_PixelFormatEnum glyphformat_to_pixelformat(ERenGlyphFormat format, int *depth) { ++ switch (format) { ++ case EGlyphFormatSubpixel: *depth = 24; return SDL_PIXELFORMAT_RGB24; ++ case EGlyphFormatGrayscale: *depth = 8; return SDL_PIXELFORMAT_INDEX8; ++ default: return SDL_PIXELFORMAT_UNKNOWN; ++ } ++} + + static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot, int bitmap_idx, GlyphMetric *metric) { + // get an atlas with the correct width ++ ERenGlyphFormat glyph_format = SLOT_BITMAP_TYPE(slot->bitmap); + int atlas_idx = -1; +- for (int i = 0; i < font->glyphs.natlas; i++) { +- if (font->glyphs.atlas[bitmap_idx][i].width >= metric->x1) { ++ for (int i = 0; i < font->glyphs.natlas[glyph_format]; i++) { ++ if (font->glyphs.atlas[glyph_format][i].width >= metric->x1) { + atlas_idx = i; + break; + } + } + if (atlas_idx < 0) { +- // create a new atlas with the correct width, for each subpixel bitmap +- for (int i = 0; i < FONT_BITMAP_COUNT(font); i++) { +- font->glyphs.atlas[i] = check_alloc(realloc(font->glyphs.atlas[i], sizeof(GlyphAtlas) * (font->glyphs.natlas + 1))); +- font->glyphs.atlas[i][font->glyphs.natlas] = (GlyphAtlas) { +- .width = metric->x1 + FONT_WIDTH_OVERFLOW_PX, .nsurface = 0, +- .surfaces = NULL, +- }; +- } ++ font->glyphs.atlas[glyph_format] = check_alloc( ++ realloc(font->glyphs.atlas[glyph_format], sizeof(GlyphAtlas) * (font->glyphs.natlas[glyph_format] + 1)) ++ ); ++ font->glyphs.atlas[glyph_format][font->glyphs.natlas[glyph_format]] = (GlyphAtlas) { ++ .width = metric->x1 + FONT_WIDTH_OVERFLOW_PX, .nsurface = 0, ++ .surfaces = NULL, ++ }; + font->glyphs.bytesize += sizeof(GlyphAtlas); +- atlas_idx = font->glyphs.natlas++; ++ atlas_idx = font->glyphs.natlas[glyph_format]++; + } + metric->atlas_idx = atlas_idx; +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format][atlas_idx]; + + // find the surface with the minimum height that can fit the glyph (limited to last 100 surfaces) + int surface_idx = -1, max_surface_idx = (int) atlas->nsurface - 100, min_waste = INT_MAX; +@@ -234,14 +252,12 @@ static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot + int h = FONT_HEIGHT_OVERFLOW_PX + (double) font->face->size->metrics.height / 64.0f; + if (h <= FONT_HEIGHT_OVERFLOW_PX) h += slot->bitmap.rows; + if (h <= FONT_HEIGHT_OVERFLOW_PX) h += font->size; ++ int depth = 0; SDL_PixelFormatEnum format = glyphformat_to_pixelformat(glyph_format, &depth); + atlas->surfaces = check_alloc(realloc(atlas->surfaces, sizeof(SDL_Surface *) * (atlas->nsurface + 1))); +- atlas->surfaces[atlas->nsurface] = check_alloc(SDL_CreateRGBSurface( +- 0, atlas->width, GLYPHS_PER_ATLAS * h, FONT_BITMAP_COUNT(font) * 8, +- 0, 0, 0, 0 +- )); ++ atlas->surfaces[atlas->nsurface] = check_alloc(SDL_CreateRGBSurfaceWithFormat(0, atlas->width, GLYPHS_PER_ATLAS * h, depth, format)); + atlas->surfaces[atlas->nsurface]->userdata = NULL; + surface_idx = atlas->nsurface++; +- font->glyphs.bytesize += (sizeof(SDL_Surface *) + sizeof(SDL_Surface) + atlas->width * GLYPHS_PER_ATLAS * h * FONT_BITMAP_COUNT(font)); ++ font->glyphs.bytesize += (sizeof(SDL_Surface *) + sizeof(SDL_Surface) + atlas->width * GLYPHS_PER_ATLAS * h * glyph_format); + } + metric->surface_idx = surface_idx; + if (atlas->surfaces[surface_idx]->userdata) { +@@ -252,68 +268,80 @@ static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot + return atlas->surfaces[surface_idx]; + } + +-static void font_load_glyph(RenFont *font, unsigned int glyph_id) { +- unsigned int render_option = font_set_render_options(font); ++static GlyphMetric *font_load_glyph_metric(RenFont *font, unsigned int glyph_id, unsigned int bitmap_idx) { + unsigned int load_option = font_set_load_options(font); +- // load the font without hinting to fix an issue with monospaced fonts, +- // because freetype doesn't report the correct LSB and RSB delta. Transformation & subpixel positioning don't affect +- // the xadvance, so we can save some time by not doing this step multiple times +- if (FT_Load_Glyph(font->face, glyph_id, (load_option | FT_LOAD_BITMAP_METRICS_ONLY | FT_LOAD_NO_HINTING) & ~FT_LOAD_FORCE_AUTOHINT) != 0) +- return; +- double unhinted_xadv = font->face->glyph->advance.x / 64.0f; +- // render the glyph for all bitmap +- int bitmaps = FONT_BITMAP_COUNT(font); + int row = glyph_id / GLYPHMAP_COL, col = glyph_id - (row * GLYPHMAP_COL); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- FT_GlyphSlot slot = font->face->glyph; +- if (FT_Load_Glyph(font->face, glyph_id, load_option | FT_LOAD_BITMAP_METRICS_ONLY) != 0 +- || font_set_style(&slot->outline, bitmap_idx * (64 / SUBPIXEL_BITMAPS_CACHED), font->style) != 0 +- || FT_Render_Glyph(slot, render_option) != 0) +- return; ++ int bitmaps = FONT_BITMAP_COUNT(font); + +- // save the metrics +- if (!font->glyphs.metrics[bitmap_idx][row]) { +- font->glyphs.metrics[bitmap_idx][row] = check_alloc(calloc(sizeof(GlyphMetric), GLYPHMAP_COL)); +- font->glyphs.bytesize += sizeof(GlyphMetric) * GLYPHMAP_COL; ++ // we set all 3 subpixel bitmaps at once, so if either of them are missing we should load it with freetype ++ if (!font->glyphs.metrics[0][row] || !(font->glyphs.metrics[0][row][col].flags & EGlyphXAdvance)) { ++ // load the font without hinting to fix an issue with monospaced fonts, ++ // because freetype doesn't report the correct LSB and RSB delta. Transformation & subpixel positioning don't affect ++ // the xadvance, so we can save some time by not doing this step multiple times ++ if (FT_Load_Glyph(font->face, glyph_id, (load_option | FT_LOAD_BITMAP_METRICS_ONLY | FT_LOAD_NO_HINTING) & ~FT_LOAD_FORCE_AUTOHINT) != 0) ++ return NULL; ++ for (int i = 0; i < bitmaps; i++) { ++ // save the metrics for all subpixel indexes ++ if (!font->glyphs.metrics[i][row]) { ++ font->glyphs.metrics[i][row] = check_alloc(calloc(sizeof(GlyphMetric), GLYPHMAP_COL)); ++ font->glyphs.bytesize += sizeof(GlyphMetric) * GLYPHMAP_COL; ++ } ++ GlyphMetric *metric = &font->glyphs.metrics[i][row][col]; ++ metric->flags |= EGlyphXAdvance; ++ metric->xadvance = font->face->glyph->advance.x / 64.0f; + } +- GlyphMetric *metric = &font->glyphs.metrics[bitmap_idx][row][col]; +- metric->flags = EGlyphLoaded; +- metric->xadvance = unhinted_xadv; +- +- // if this bitmap is empty, or has a format we don't support, just store the xadvance +- if (!slot->bitmap.width || !slot->bitmap.rows || !slot->bitmap.buffer || +- (slot->bitmap.pixel_mode != FT_PIXEL_MODE_MONO +- && slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY +- && slot->bitmap.pixel_mode != FT_PIXEL_MODE_LCD)) +- continue; +- +- unsigned int glyph_width = slot->bitmap.width / bitmaps; +- // FT_PIXEL_MODE_MONO uses 1 bit per pixel packed bitmap +- if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) glyph_width *= 8; +- +- metric->x1 = glyph_width; +- metric->y1 = slot->bitmap.rows; +- metric->bitmap_left = slot->bitmap_left; +- metric->bitmap_top = slot->bitmap_top; +- metric->flags |= (EGlyphBitmap | EGlyphDualSource); +- +- // find the best surface to copy the glyph over, and copy it +- SDL_Surface *surface = font_allocate_glyph_surface(font, slot, bitmap_idx, metric); +- uint8_t* pixels = surface->pixels; +- for (unsigned int line = 0; line < slot->bitmap.rows; ++line) { +- int target_offset = surface->pitch * (line + metric->y0); // x0 is always assumed to be 0 +- int source_offset = line * slot->bitmap.pitch; +- if (font->antialiasing == FONT_ANTIALIASING_NONE) { +- for (unsigned int column = 0; column < slot->bitmap.width; ++column) { +- int current_source_offset = source_offset + (column / 8); +- int source_pixel = slot->bitmap.buffer[current_source_offset]; +- pixels[++target_offset] = ((source_pixel >> (7 - (column % 8))) & 0x1) * 0xFF; +- } +- } else { +- memcpy(&pixels[target_offset], &slot->bitmap.buffer[source_offset], slot->bitmap.width); ++ } ++ return &font->glyphs.metrics[bitmap_idx][row][col]; ++} ++ ++static SDL_Surface *font_load_glyph_bitmap(RenFont *font, unsigned int glyph_id, unsigned int bitmap_idx) { ++ GlyphMetric *metric = font_load_glyph_metric(font, glyph_id, bitmap_idx); ++ if (!metric) return NULL; ++ if (metric->flags & EGlyphBitmap) return font->glyphs.atlas[metric->format][metric->atlas_idx].surfaces[metric->surface_idx]; ++ ++ // render the glyph for a bitmap_idx ++ unsigned int load_option = font_set_load_options(font), render_option = font_set_render_options(font); ++ FT_GlyphSlot slot = font->face->glyph; ++ if (FT_Load_Glyph(font->face, glyph_id, load_option | FT_LOAD_BITMAP_METRICS_ONLY) != 0 ++ || font_set_style(&slot->outline, bitmap_idx * (64 / SUBPIXEL_BITMAPS_CACHED), font->style) != 0 ++ || FT_Render_Glyph(slot, render_option) != 0) ++ return NULL; ++ ++ // if this bitmap is empty, or has a format we don't support, just store the xadvance ++ if (!slot->bitmap.width || !slot->bitmap.rows || !slot->bitmap.buffer || ++ (slot->bitmap.pixel_mode != FT_PIXEL_MODE_MONO ++ && slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY ++ && slot->bitmap.pixel_mode != FT_PIXEL_MODE_LCD)) ++ return NULL; ++ ++ unsigned int glyph_width = slot->bitmap.width / FONT_BITMAP_COUNT(font); ++ // FT_PIXEL_MODE_MONO uses 1 bit per pixel packed bitmap ++ if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) glyph_width *= 8; ++ ++ metric->x1 = glyph_width; ++ metric->y1 = slot->bitmap.rows; ++ metric->bitmap_left = slot->bitmap_left; ++ metric->bitmap_top = slot->bitmap_top; ++ metric->flags |= EGlyphBitmap; ++ metric->format = SLOT_BITMAP_TYPE(slot->bitmap); ++ ++ // find the best surface to copy the glyph over, and copy it ++ SDL_Surface *surface = font_allocate_glyph_surface(font, slot, bitmap_idx, metric); ++ uint8_t* pixels = surface->pixels; ++ for (unsigned int line = 0; line < slot->bitmap.rows; ++line) { ++ int target_offset = surface->pitch * (line + metric->y0); // x0 is always assumed to be 0 ++ int source_offset = line * slot->bitmap.pitch; ++ if (font->antialiasing == FONT_ANTIALIASING_NONE) { ++ for (unsigned int column = 0; column < slot->bitmap.width; ++column) { ++ int current_source_offset = source_offset + (column / 8); ++ int source_pixel = slot->bitmap.buffer[current_source_offset]; ++ pixels[++target_offset] = ((source_pixel >> (7 - (column % 8))) & 0x1) * 0xFF; + } ++ } else { ++ memcpy(&pixels[target_offset], &slot->bitmap.buffer[source_offset], slot->bitmap.width); + } + } ++ return surface; + } + + // https://en.wikipedia.org/wiki/Whitespace_character +@@ -324,11 +352,6 @@ static inline int is_whitespace(unsigned int codepoint) { + return (codepoint >= 0x9 && codepoint <= 0xD) || (codepoint >= 0x2000 && codepoint <= 0x200A); + } + +-static inline GlyphMetric *font_get_glyph(RenFont *font, unsigned int glyph_id, int subpixel_idx) { +- int row = glyph_id / GLYPHMAP_COL, col = glyph_id - (row * GLYPHMAP_COL); +- return font->glyphs.metrics[subpixel_idx][row] ? &font->glyphs.metrics[subpixel_idx][row][col] : NULL; +-} +- + static RenFont *font_group_get_glyph(RenFont **fonts, unsigned int codepoint, int subpixel_idx, SDL_Surface **surface, GlyphMetric **metric) { + if (subpixel_idx < 0) subpixel_idx += SUBPIXEL_BITMAPS_CACHED; + RenFont *font = NULL; +@@ -340,38 +363,36 @@ static RenFont *font_group_get_glyph(RenFont **fonts, unsigned int codepoint, in + } + // load the glyph if it is not loaded + subpixel_idx = FONT_IS_SUBPIXEL(font) ? subpixel_idx : 0; +- GlyphMetric *m = font_get_glyph(font, glyph_id, subpixel_idx); +- if (!m || !(m->flags & EGlyphLoaded)) font_load_glyph(font, glyph_id); +- // if the glyph ID (possibly 0) is not available and we are not trying to load whitespace, try to load U+25A1 (box character) +- if ((!m || !(m->flags & EGlyphLoaded)) && codepoint != 0x25A1 && !is_whitespace(codepoint)) ++ GlyphMetric *m = font_load_glyph_metric(font, glyph_id, subpixel_idx); ++ // try the box drawing character (0x25A1) if the requested codepoint is not a whitespace, and we cannot load the .notdef glyph ++ if ((!m || !m->flags) && codepoint != 0x25A1 && !is_whitespace(codepoint)) + return font_group_get_glyph(fonts, 0x25A1, subpixel_idx, surface, metric); +- // fetch the glyph metrics again and save it +- m = font_get_glyph(font, glyph_id, subpixel_idx); + if (metric && m) *metric = m; +- if (surface && m && m->flags & EGlyphBitmap) *surface = font->glyphs.atlas[subpixel_idx][m->atlas_idx].surfaces[m->surface_idx]; ++ if (surface && m) *surface = font_load_glyph_bitmap(font, glyph_id, subpixel_idx); + return font; + } + + static void font_clear_glyph_cache(RenFont* font) { +- int bitmaps = FONT_BITMAP_COUNT(font); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas; atlas_idx++) { +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ for (int glyph_format_idx = 0; glyph_format_idx < EGlyphFormatSize; glyph_format_idx++) { ++ for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas[glyph_format_idx]; atlas_idx++) { ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format_idx][atlas_idx]; + for (int surface_idx = 0; surface_idx < atlas->nsurface; surface_idx++) { + SDL_FreeSurface(atlas->surfaces[surface_idx]); + } + free(atlas->surfaces); + } +- free(font->glyphs.atlas[bitmap_idx]); +- font->glyphs.atlas[bitmap_idx] = NULL; +- // clear glyph metric ++ free(font->glyphs.atlas[glyph_format_idx]); ++ font->glyphs.atlas[glyph_format_idx] = NULL; ++ font->glyphs.natlas[glyph_format_idx] = 0; ++ } ++ // clear glyph metric ++ for (int subpixel_idx = 0; subpixel_idx < FONT_BITMAP_COUNT(font); subpixel_idx++) { + for (int glyphmap_row = 0; glyphmap_row < GLYPHMAP_ROW; glyphmap_row++) { +- free(font->glyphs.metrics[bitmap_idx][glyphmap_row]); +- font->glyphs.metrics[bitmap_idx][glyphmap_row] = NULL; ++ free(font->glyphs.metrics[subpixel_idx][glyphmap_row]); ++ font->glyphs.metrics[subpixel_idx][glyphmap_row] = NULL; + } + } + font->glyphs.bytesize = 0; +- font->glyphs.natlas = 0; + } + + // based on https://github.com/libsdl-org/SDL_ttf/blob/2a094959055fba09f7deed6e1ffeb986188982ae/SDL_ttf.c#L1735 +@@ -408,7 +429,7 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + } else { + font->height = (short) font->face->size->metrics.height / 64.0f; + font->baseline = (short) font->face->size->metrics.ascender / 64.0f; +- } ++ } + if(!font->underline_thickness) + font->underline_thickness = ceil((double) font->height / 14.0); + +@@ -424,7 +445,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + + file = SDL_RWFromFile(path, "rb"); + if (!file) return NULL; +- ++ + int len = strlen(path); + font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); + strcpy(font->path, path); +@@ -545,12 +566,11 @@ double ren_font_group_get_width(RenFont **fonts, const char *text, size_t len, i + // this function can be used to debug font atlases, it is not public + void ren_font_dump(RenFont *font) { + char filename[1024]; +- int bitmaps = FONT_BITMAP_COUNT(font); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas; atlas_idx++) { +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ for (int glyph_format_idx = 0; glyph_format_idx < EGlyphFormatSize; glyph_format_idx++) { ++ for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas[glyph_format_idx]; atlas_idx++) { ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format_idx][atlas_idx]; + for (int surface_idx = 0; surface_idx < atlas->nsurface; surface_idx++) { +- snprintf(filename, 1024, "%s-%d-%d-%d.bmp", font->face->family_name, bitmap_idx, atlas_idx, surface_idx); ++ snprintf(filename, 1024, "%s-%d-%d-%d.bmp", font->face->family_name, glyph_format_idx, atlas_idx, surface_idx); + SDL_SaveBMP(atlas->surfaces[surface_idx], filename); + } + } +@@ -611,11 +631,10 @@ double ren_draw_text(RenSurface *rs, RenFont **fonts, const char *text, size_t l + SDL_Color dst = { (destination_color & surface->format->Rmask) >> surface->format->Rshift, (destination_color & surface->format->Gmask) >> surface->format->Gshift, (destination_color & surface->format->Bmask) >> surface->format->Bshift, (destination_color & surface->format->Amask) >> surface->format->Ashift }; + SDL_Color src; + +- if (font->antialiasing == FONT_ANTIALIASING_SUBPIXEL) { ++ if (metric->format == EGlyphFormatSubpixel) { + src.r = *(source_pixel++); + src.g = *(source_pixel++); +- } +- else { ++ } else { + src.r = *(source_pixel); + src.g = *(source_pixel); + } +@@ -717,7 +736,7 @@ int ren_init(void) { + + void ren_free(void) { + SDL_FreeSurface(draw_rect_surface); +- FT_Done_FreeType(library); ++ FT_Done_FreeType(library); + } + + RenWindow* ren_create(SDL_Window *win) { diff --git a/tasks/lite-xl__lite-xl-1856/solution/solve.sh b/tasks/lite-xl__lite-xl-1856/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/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/lite-xl__lite-xl-1856/task.toml b/tasks/lite-xl__lite-xl-1856/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f72451a77516e7c1052951ecfee72567023ec81 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1856" +description = "renderer: defer bitmap rendering when possible" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1856" +source_access = "auto" +built_at = "2026-11-16T16:09:56.306279+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7f7a9bd2d142fcc5d88337975f0e8a58d08f3a0bc60147d33c1db4475c0824c1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T14:43:18Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 257 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.300819+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1856/tests/capture.py b/tasks/lite-xl__lite-xl-1856/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/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/lite-xl__lite-xl-1856/tests/instruction.md b/tasks/lite-xl__lite-xl-1856/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..952d2d59e78383c176bfef08a7901d852d0d465d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** renderer: defer bitmap rendering when possible + +## Description + +ren_font_group_get_width() is getting called a lot while not 100% of the glyphs loaded from this function will be rendered. We can defer the bitmap rendering to ren_draw_text. + +It's hard to benchmark this because the synthetic benchmark would obviously perform well, but that doesn't translate to actual performance. I have some metrics that I've collected by printing the frame time, but so far it has been very inconclusive. + +https://docs.google.com/spreadsheets/d/1OngibXEUds0-rACNCOF5g6OzLWPoSns3QQBLQd_YDbc/edit?usp=sharing + +Other changes including setting the default number of glyphs to 96, height overflow to 0 and width overflow to 9, because with some testing this has less wastage compared to the current values. The atlas is also indexed by bitmap type (8 bits and 24 bits) to further reduce wastage, as all subpixel bitmaps are now put in the same atlas. + +I'm putting this here for more ideas and suggestions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1856/tests/oracle.patch b/tasks/lite-xl__lite-xl-1856/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4074fe3f0256b266470bf69494a80c798570503e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/tests/oracle.patch @@ -0,0 +1,407 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 8a961995..6200a173 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -34,10 +34,10 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + /************************* Fonts *************************/ + + // approximate number of glyphs per atlas surface +-#define GLYPHS_PER_ATLAS 256 ++#define GLYPHS_PER_ATLAS 96 + // some padding to add to atlas surface to store more glyphs +-#define FONT_HEIGHT_OVERFLOW_PX 6 +-#define FONT_WIDTH_OVERFLOW_PX 6 ++#define FONT_HEIGHT_OVERFLOW_PX 0 ++#define FONT_WIDTH_OVERFLOW_PX 9 + + // maximum unicode codepoint supported (https://stackoverflow.com/a/52203901) + #define MAX_UNICODE 0x10FFFF +@@ -54,20 +54,28 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + // number of subpixel bitmaps + #define SUBPIXEL_BITMAPS_CACHED 3 + ++// the bitmap format of the glyph + typedef enum { +- EGlyphNone = 0, +- EGlyphLoaded = (1 << 0L), +- EGlyphBitmap = (1 << 1L), +- // currently no-op because blits are always assumed to be dual source +- EGlyphDualSource = (1 << 2L), ++ EGlyphFormatGrayscale, // 8bit graysclae ++ EGlyphFormatSubpixel, // 24bit subpixel ++ EGlyphFormatSize ++} ERenGlyphFormat; ++ ++// extra flags to store glyph info ++typedef enum { ++ EGlyphNone = 0, // glyph is not loaded ++ EGlyphXAdvance = (1 << 0L), // xadvance is loaded ++ EGlyphBitmap = (1 << 1L) // bitmap is loaded + } ERenGlyphFlags; + + // metrics for a loaded glyph + typedef struct { ++ float xadvance; + unsigned short atlas_idx, surface_idx; +- unsigned int x1, y0, y1, flags; + int bitmap_left, bitmap_top; +- float xadvance; ++ unsigned int x1, y0, y1; ++ unsigned short flags; ++ unsigned char format; + } GlyphMetric; + + // maps codepoints -> glyph IDs +@@ -85,9 +93,10 @@ typedef struct { + typedef struct { + // accessed with metrics[bitmap_idx][glyph_id / nrow][glyph_id - (row * ncol)] + GlyphMetric *metrics[SUBPIXEL_BITMAPS_CACHED][GLYPHMAP_ROW]; +- // accessed with atlas[bitmap_idx][atlas_idx].surfaces[surface_idx] +- GlyphAtlas *atlas[SUBPIXEL_BITMAPS_CACHED]; +- size_t natlas, bytesize; ++ // accessed by atlas[glyph_format][atlas_idx].surfaces[surface_idx] ++ GlyphAtlas *atlas[EGlyphFormatSize]; ++ size_t natlas[EGlyphFormatSize]; ++ size_t bytesize; + } GlyphMap; + + typedef struct RenFont { +@@ -98,7 +107,7 @@ typedef struct RenFont { + int scale; + #endif + float size, space_advance; +- unsigned short max_height, baseline, height, tab_size; ++ unsigned short baseline, height, tab_size; + unsigned short underline_thickness; + ERenFontAntialiasing antialiasing; + ERenFontHinting hinting; +@@ -193,30 +202,39 @@ static unsigned int font_get_glyph_id(RenFont *font, unsigned int codepoint) { + + #define FONT_IS_SUBPIXEL(F) ((F)->antialiasing == FONT_ANTIALIASING_SUBPIXEL) + #define FONT_BITMAP_COUNT(F) ((F)->antialiasing == FONT_ANTIALIASING_SUBPIXEL ? SUBPIXEL_BITMAPS_CACHED : 1) ++#define SLOT_BITMAP_TYPE(B) ((B).pixel_mode == FT_PIXEL_MODE_LCD ? EGlyphFormatSubpixel : EGlyphFormatGrayscale) ++ ++static inline SDL_PixelFormatEnum glyphformat_to_pixelformat(ERenGlyphFormat format, int *depth) { ++ switch (format) { ++ case EGlyphFormatSubpixel: *depth = 24; return SDL_PIXELFORMAT_RGB24; ++ case EGlyphFormatGrayscale: *depth = 8; return SDL_PIXELFORMAT_INDEX8; ++ default: return SDL_PIXELFORMAT_UNKNOWN; ++ } ++} + + static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot, int bitmap_idx, GlyphMetric *metric) { + // get an atlas with the correct width ++ ERenGlyphFormat glyph_format = SLOT_BITMAP_TYPE(slot->bitmap); + int atlas_idx = -1; +- for (int i = 0; i < font->glyphs.natlas; i++) { +- if (font->glyphs.atlas[bitmap_idx][i].width >= metric->x1) { ++ for (int i = 0; i < font->glyphs.natlas[glyph_format]; i++) { ++ if (font->glyphs.atlas[glyph_format][i].width >= metric->x1) { + atlas_idx = i; + break; + } + } + if (atlas_idx < 0) { +- // create a new atlas with the correct width, for each subpixel bitmap +- for (int i = 0; i < FONT_BITMAP_COUNT(font); i++) { +- font->glyphs.atlas[i] = check_alloc(realloc(font->glyphs.atlas[i], sizeof(GlyphAtlas) * (font->glyphs.natlas + 1))); +- font->glyphs.atlas[i][font->glyphs.natlas] = (GlyphAtlas) { +- .width = metric->x1 + FONT_WIDTH_OVERFLOW_PX, .nsurface = 0, +- .surfaces = NULL, +- }; +- } ++ font->glyphs.atlas[glyph_format] = check_alloc( ++ realloc(font->glyphs.atlas[glyph_format], sizeof(GlyphAtlas) * (font->glyphs.natlas[glyph_format] + 1)) ++ ); ++ font->glyphs.atlas[glyph_format][font->glyphs.natlas[glyph_format]] = (GlyphAtlas) { ++ .width = metric->x1 + FONT_WIDTH_OVERFLOW_PX, .nsurface = 0, ++ .surfaces = NULL, ++ }; + font->glyphs.bytesize += sizeof(GlyphAtlas); +- atlas_idx = font->glyphs.natlas++; ++ atlas_idx = font->glyphs.natlas[glyph_format]++; + } + metric->atlas_idx = atlas_idx; +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format][atlas_idx]; + + // find the surface with the minimum height that can fit the glyph (limited to last 100 surfaces) + int surface_idx = -1, max_surface_idx = (int) atlas->nsurface - 100, min_waste = INT_MAX; +@@ -234,14 +252,12 @@ static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot + int h = FONT_HEIGHT_OVERFLOW_PX + (double) font->face->size->metrics.height / 64.0f; + if (h <= FONT_HEIGHT_OVERFLOW_PX) h += slot->bitmap.rows; + if (h <= FONT_HEIGHT_OVERFLOW_PX) h += font->size; ++ int depth = 0; SDL_PixelFormatEnum format = glyphformat_to_pixelformat(glyph_format, &depth); + atlas->surfaces = check_alloc(realloc(atlas->surfaces, sizeof(SDL_Surface *) * (atlas->nsurface + 1))); +- atlas->surfaces[atlas->nsurface] = check_alloc(SDL_CreateRGBSurface( +- 0, atlas->width, GLYPHS_PER_ATLAS * h, FONT_BITMAP_COUNT(font) * 8, +- 0, 0, 0, 0 +- )); ++ atlas->surfaces[atlas->nsurface] = check_alloc(SDL_CreateRGBSurfaceWithFormat(0, atlas->width, GLYPHS_PER_ATLAS * h, depth, format)); + atlas->surfaces[atlas->nsurface]->userdata = NULL; + surface_idx = atlas->nsurface++; +- font->glyphs.bytesize += (sizeof(SDL_Surface *) + sizeof(SDL_Surface) + atlas->width * GLYPHS_PER_ATLAS * h * FONT_BITMAP_COUNT(font)); ++ font->glyphs.bytesize += (sizeof(SDL_Surface *) + sizeof(SDL_Surface) + atlas->width * GLYPHS_PER_ATLAS * h * glyph_format); + } + metric->surface_idx = surface_idx; + if (atlas->surfaces[surface_idx]->userdata) { +@@ -252,68 +268,80 @@ static SDL_Surface *font_allocate_glyph_surface(RenFont *font, FT_GlyphSlot slot + return atlas->surfaces[surface_idx]; + } + +-static void font_load_glyph(RenFont *font, unsigned int glyph_id) { +- unsigned int render_option = font_set_render_options(font); ++static GlyphMetric *font_load_glyph_metric(RenFont *font, unsigned int glyph_id, unsigned int bitmap_idx) { + unsigned int load_option = font_set_load_options(font); +- // load the font without hinting to fix an issue with monospaced fonts, +- // because freetype doesn't report the correct LSB and RSB delta. Transformation & subpixel positioning don't affect +- // the xadvance, so we can save some time by not doing this step multiple times +- if (FT_Load_Glyph(font->face, glyph_id, (load_option | FT_LOAD_BITMAP_METRICS_ONLY | FT_LOAD_NO_HINTING) & ~FT_LOAD_FORCE_AUTOHINT) != 0) +- return; +- double unhinted_xadv = font->face->glyph->advance.x / 64.0f; +- // render the glyph for all bitmap +- int bitmaps = FONT_BITMAP_COUNT(font); + int row = glyph_id / GLYPHMAP_COL, col = glyph_id - (row * GLYPHMAP_COL); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- FT_GlyphSlot slot = font->face->glyph; +- if (FT_Load_Glyph(font->face, glyph_id, load_option | FT_LOAD_BITMAP_METRICS_ONLY) != 0 +- || font_set_style(&slot->outline, bitmap_idx * (64 / SUBPIXEL_BITMAPS_CACHED), font->style) != 0 +- || FT_Render_Glyph(slot, render_option) != 0) +- return; ++ int bitmaps = FONT_BITMAP_COUNT(font); + +- // save the metrics +- if (!font->glyphs.metrics[bitmap_idx][row]) { +- font->glyphs.metrics[bitmap_idx][row] = check_alloc(calloc(sizeof(GlyphMetric), GLYPHMAP_COL)); +- font->glyphs.bytesize += sizeof(GlyphMetric) * GLYPHMAP_COL; ++ // we set all 3 subpixel bitmaps at once, so if either of them are missing we should load it with freetype ++ if (!font->glyphs.metrics[0][row] || !(font->glyphs.metrics[0][row][col].flags & EGlyphXAdvance)) { ++ // load the font without hinting to fix an issue with monospaced fonts, ++ // because freetype doesn't report the correct LSB and RSB delta. Transformation & subpixel positioning don't affect ++ // the xadvance, so we can save some time by not doing this step multiple times ++ if (FT_Load_Glyph(font->face, glyph_id, (load_option | FT_LOAD_BITMAP_METRICS_ONLY | FT_LOAD_NO_HINTING) & ~FT_LOAD_FORCE_AUTOHINT) != 0) ++ return NULL; ++ for (int i = 0; i < bitmaps; i++) { ++ // save the metrics for all subpixel indexes ++ if (!font->glyphs.metrics[i][row]) { ++ font->glyphs.metrics[i][row] = check_alloc(calloc(sizeof(GlyphMetric), GLYPHMAP_COL)); ++ font->glyphs.bytesize += sizeof(GlyphMetric) * GLYPHMAP_COL; ++ } ++ GlyphMetric *metric = &font->glyphs.metrics[i][row][col]; ++ metric->flags |= EGlyphXAdvance; ++ metric->xadvance = font->face->glyph->advance.x / 64.0f; + } +- GlyphMetric *metric = &font->glyphs.metrics[bitmap_idx][row][col]; +- metric->flags = EGlyphLoaded; +- metric->xadvance = unhinted_xadv; +- +- // if this bitmap is empty, or has a format we don't support, just store the xadvance +- if (!slot->bitmap.width || !slot->bitmap.rows || !slot->bitmap.buffer || +- (slot->bitmap.pixel_mode != FT_PIXEL_MODE_MONO +- && slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY +- && slot->bitmap.pixel_mode != FT_PIXEL_MODE_LCD)) +- continue; +- +- unsigned int glyph_width = slot->bitmap.width / bitmaps; +- // FT_PIXEL_MODE_MONO uses 1 bit per pixel packed bitmap +- if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) glyph_width *= 8; +- +- metric->x1 = glyph_width; +- metric->y1 = slot->bitmap.rows; +- metric->bitmap_left = slot->bitmap_left; +- metric->bitmap_top = slot->bitmap_top; +- metric->flags |= (EGlyphBitmap | EGlyphDualSource); +- +- // find the best surface to copy the glyph over, and copy it +- SDL_Surface *surface = font_allocate_glyph_surface(font, slot, bitmap_idx, metric); +- uint8_t* pixels = surface->pixels; +- for (unsigned int line = 0; line < slot->bitmap.rows; ++line) { +- int target_offset = surface->pitch * (line + metric->y0); // x0 is always assumed to be 0 +- int source_offset = line * slot->bitmap.pitch; +- if (font->antialiasing == FONT_ANTIALIASING_NONE) { +- for (unsigned int column = 0; column < slot->bitmap.width; ++column) { +- int current_source_offset = source_offset + (column / 8); +- int source_pixel = slot->bitmap.buffer[current_source_offset]; +- pixels[++target_offset] = ((source_pixel >> (7 - (column % 8))) & 0x1) * 0xFF; +- } +- } else { +- memcpy(&pixels[target_offset], &slot->bitmap.buffer[source_offset], slot->bitmap.width); ++ } ++ return &font->glyphs.metrics[bitmap_idx][row][col]; ++} ++ ++static SDL_Surface *font_load_glyph_bitmap(RenFont *font, unsigned int glyph_id, unsigned int bitmap_idx) { ++ GlyphMetric *metric = font_load_glyph_metric(font, glyph_id, bitmap_idx); ++ if (!metric) return NULL; ++ if (metric->flags & EGlyphBitmap) return font->glyphs.atlas[metric->format][metric->atlas_idx].surfaces[metric->surface_idx]; ++ ++ // render the glyph for a bitmap_idx ++ unsigned int load_option = font_set_load_options(font), render_option = font_set_render_options(font); ++ FT_GlyphSlot slot = font->face->glyph; ++ if (FT_Load_Glyph(font->face, glyph_id, load_option | FT_LOAD_BITMAP_METRICS_ONLY) != 0 ++ || font_set_style(&slot->outline, bitmap_idx * (64 / SUBPIXEL_BITMAPS_CACHED), font->style) != 0 ++ || FT_Render_Glyph(slot, render_option) != 0) ++ return NULL; ++ ++ // if this bitmap is empty, or has a format we don't support, just store the xadvance ++ if (!slot->bitmap.width || !slot->bitmap.rows || !slot->bitmap.buffer || ++ (slot->bitmap.pixel_mode != FT_PIXEL_MODE_MONO ++ && slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY ++ && slot->bitmap.pixel_mode != FT_PIXEL_MODE_LCD)) ++ return NULL; ++ ++ unsigned int glyph_width = slot->bitmap.width / FONT_BITMAP_COUNT(font); ++ // FT_PIXEL_MODE_MONO uses 1 bit per pixel packed bitmap ++ if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) glyph_width *= 8; ++ ++ metric->x1 = glyph_width; ++ metric->y1 = slot->bitmap.rows; ++ metric->bitmap_left = slot->bitmap_left; ++ metric->bitmap_top = slot->bitmap_top; ++ metric->flags |= EGlyphBitmap; ++ metric->format = SLOT_BITMAP_TYPE(slot->bitmap); ++ ++ // find the best surface to copy the glyph over, and copy it ++ SDL_Surface *surface = font_allocate_glyph_surface(font, slot, bitmap_idx, metric); ++ uint8_t* pixels = surface->pixels; ++ for (unsigned int line = 0; line < slot->bitmap.rows; ++line) { ++ int target_offset = surface->pitch * (line + metric->y0); // x0 is always assumed to be 0 ++ int source_offset = line * slot->bitmap.pitch; ++ if (font->antialiasing == FONT_ANTIALIASING_NONE) { ++ for (unsigned int column = 0; column < slot->bitmap.width; ++column) { ++ int current_source_offset = source_offset + (column / 8); ++ int source_pixel = slot->bitmap.buffer[current_source_offset]; ++ pixels[++target_offset] = ((source_pixel >> (7 - (column % 8))) & 0x1) * 0xFF; + } ++ } else { ++ memcpy(&pixels[target_offset], &slot->bitmap.buffer[source_offset], slot->bitmap.width); + } + } ++ return surface; + } + + // https://en.wikipedia.org/wiki/Whitespace_character +@@ -324,11 +352,6 @@ static inline int is_whitespace(unsigned int codepoint) { + return (codepoint >= 0x9 && codepoint <= 0xD) || (codepoint >= 0x2000 && codepoint <= 0x200A); + } + +-static inline GlyphMetric *font_get_glyph(RenFont *font, unsigned int glyph_id, int subpixel_idx) { +- int row = glyph_id / GLYPHMAP_COL, col = glyph_id - (row * GLYPHMAP_COL); +- return font->glyphs.metrics[subpixel_idx][row] ? &font->glyphs.metrics[subpixel_idx][row][col] : NULL; +-} +- + static RenFont *font_group_get_glyph(RenFont **fonts, unsigned int codepoint, int subpixel_idx, SDL_Surface **surface, GlyphMetric **metric) { + if (subpixel_idx < 0) subpixel_idx += SUBPIXEL_BITMAPS_CACHED; + RenFont *font = NULL; +@@ -340,38 +363,36 @@ static RenFont *font_group_get_glyph(RenFont **fonts, unsigned int codepoint, in + } + // load the glyph if it is not loaded + subpixel_idx = FONT_IS_SUBPIXEL(font) ? subpixel_idx : 0; +- GlyphMetric *m = font_get_glyph(font, glyph_id, subpixel_idx); +- if (!m || !(m->flags & EGlyphLoaded)) font_load_glyph(font, glyph_id); +- // if the glyph ID (possibly 0) is not available and we are not trying to load whitespace, try to load U+25A1 (box character) +- if ((!m || !(m->flags & EGlyphLoaded)) && codepoint != 0x25A1 && !is_whitespace(codepoint)) ++ GlyphMetric *m = font_load_glyph_metric(font, glyph_id, subpixel_idx); ++ // try the box drawing character (0x25A1) if the requested codepoint is not a whitespace, and we cannot load the .notdef glyph ++ if ((!m || !m->flags) && codepoint != 0x25A1 && !is_whitespace(codepoint)) + return font_group_get_glyph(fonts, 0x25A1, subpixel_idx, surface, metric); +- // fetch the glyph metrics again and save it +- m = font_get_glyph(font, glyph_id, subpixel_idx); + if (metric && m) *metric = m; +- if (surface && m && m->flags & EGlyphBitmap) *surface = font->glyphs.atlas[subpixel_idx][m->atlas_idx].surfaces[m->surface_idx]; ++ if (surface && m) *surface = font_load_glyph_bitmap(font, glyph_id, subpixel_idx); + return font; + } + + static void font_clear_glyph_cache(RenFont* font) { +- int bitmaps = FONT_BITMAP_COUNT(font); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas; atlas_idx++) { +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ for (int glyph_format_idx = 0; glyph_format_idx < EGlyphFormatSize; glyph_format_idx++) { ++ for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas[glyph_format_idx]; atlas_idx++) { ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format_idx][atlas_idx]; + for (int surface_idx = 0; surface_idx < atlas->nsurface; surface_idx++) { + SDL_FreeSurface(atlas->surfaces[surface_idx]); + } + free(atlas->surfaces); + } +- free(font->glyphs.atlas[bitmap_idx]); +- font->glyphs.atlas[bitmap_idx] = NULL; +- // clear glyph metric ++ free(font->glyphs.atlas[glyph_format_idx]); ++ font->glyphs.atlas[glyph_format_idx] = NULL; ++ font->glyphs.natlas[glyph_format_idx] = 0; ++ } ++ // clear glyph metric ++ for (int subpixel_idx = 0; subpixel_idx < FONT_BITMAP_COUNT(font); subpixel_idx++) { + for (int glyphmap_row = 0; glyphmap_row < GLYPHMAP_ROW; glyphmap_row++) { +- free(font->glyphs.metrics[bitmap_idx][glyphmap_row]); +- font->glyphs.metrics[bitmap_idx][glyphmap_row] = NULL; ++ free(font->glyphs.metrics[subpixel_idx][glyphmap_row]); ++ font->glyphs.metrics[subpixel_idx][glyphmap_row] = NULL; + } + } + font->glyphs.bytesize = 0; +- font->glyphs.natlas = 0; + } + + // based on https://github.com/libsdl-org/SDL_ttf/blob/2a094959055fba09f7deed6e1ffeb986188982ae/SDL_ttf.c#L1735 +@@ -408,7 +429,7 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + } else { + font->height = (short) font->face->size->metrics.height / 64.0f; + font->baseline = (short) font->face->size->metrics.ascender / 64.0f; +- } ++ } + if(!font->underline_thickness) + font->underline_thickness = ceil((double) font->height / 14.0); + +@@ -424,7 +445,7 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + + file = SDL_RWFromFile(path, "rb"); + if (!file) return NULL; +- ++ + int len = strlen(path); + font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); + strcpy(font->path, path); +@@ -545,12 +566,11 @@ double ren_font_group_get_width(RenFont **fonts, const char *text, size_t len, i + // this function can be used to debug font atlases, it is not public + void ren_font_dump(RenFont *font) { + char filename[1024]; +- int bitmaps = FONT_BITMAP_COUNT(font); +- for (int bitmap_idx = 0; bitmap_idx < bitmaps; bitmap_idx++) { +- for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas; atlas_idx++) { +- GlyphAtlas *atlas = &font->glyphs.atlas[bitmap_idx][atlas_idx]; ++ for (int glyph_format_idx = 0; glyph_format_idx < EGlyphFormatSize; glyph_format_idx++) { ++ for (int atlas_idx = 0; atlas_idx < font->glyphs.natlas[glyph_format_idx]; atlas_idx++) { ++ GlyphAtlas *atlas = &font->glyphs.atlas[glyph_format_idx][atlas_idx]; + for (int surface_idx = 0; surface_idx < atlas->nsurface; surface_idx++) { +- snprintf(filename, 1024, "%s-%d-%d-%d.bmp", font->face->family_name, bitmap_idx, atlas_idx, surface_idx); ++ snprintf(filename, 1024, "%s-%d-%d-%d.bmp", font->face->family_name, glyph_format_idx, atlas_idx, surface_idx); + SDL_SaveBMP(atlas->surfaces[surface_idx], filename); + } + } +@@ -611,11 +631,10 @@ double ren_draw_text(RenSurface *rs, RenFont **fonts, const char *text, size_t l + SDL_Color dst = { (destination_color & surface->format->Rmask) >> surface->format->Rshift, (destination_color & surface->format->Gmask) >> surface->format->Gshift, (destination_color & surface->format->Bmask) >> surface->format->Bshift, (destination_color & surface->format->Amask) >> surface->format->Ashift }; + SDL_Color src; + +- if (font->antialiasing == FONT_ANTIALIASING_SUBPIXEL) { ++ if (metric->format == EGlyphFormatSubpixel) { + src.r = *(source_pixel++); + src.g = *(source_pixel++); +- } +- else { ++ } else { + src.r = *(source_pixel); + src.g = *(source_pixel); + } +@@ -717,7 +736,7 @@ int ren_init(void) { + + void ren_free(void) { + SDL_FreeSurface(draw_rect_surface); +- FT_Done_FreeType(library); ++ FT_Done_FreeType(library); + } + + RenWindow* ren_create(SDL_Window *win) { diff --git a/tasks/lite-xl__lite-xl-1856/tests/test.sh b/tasks/lite-xl__lite-xl-1856/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1856/tests/verifier.py b/tasks/lite-xl__lite-xl-1856/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1856/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/lite-xl__lite-xl-1864/environment/Dockerfile b/tasks/lite-xl__lite-xl-1864/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9b5e9fe0a51e81345b600b10d48674638157e5a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efa257ddbdd9ade1cad588918c62f091493ccb1b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && 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/lite-xl__lite-xl-1864/instruction.md b/tasks/lite-xl__lite-xl-1864/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fb8966abdac18f1d0e00122f4d081fc730a9be8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** api/system: make stat() call consistent across platforms + +## Description + +Includes #1826. + +This PR uses GetFileAttributesExW on Windows to get everything we need for get_file_info(), including `symlink`. All platforms will now have `symlink` and high-resolution timestamps if supported. This should help with #1862. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1864/solution/patch.diff b/tasks/lite-xl__lite-xl-1864/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d9294a3d4c811c5952e82d38ca4fade105c00c07 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/solution/patch.diff @@ -0,0 +1,125 @@ +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 66af600f..60870529 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -8,13 +8,14 @@ system = {} + ---@alias system.fileinfotype + ---| "file" # It is a file. + ---| "dir" # It is a directory. ++---| nil # The file type is unspecified. + + --- + ---@class system.fileinfo + ---@field public modified number A timestamp in seconds. + ---@field public size number Size in bytes. + ---@field public type system.fileinfotype Type of file +----@field public symlink boolean The directory is a symlink. This field is only set on Linux and on directories. ++---@field public symlink boolean The directory is a symlink. This field is only set on directories. + + --- + ---Core function used to retrieve the current event been triggered by SDL. +diff --git a/src/api/system.c b/src/api/system.c +index ace17337..958bab1b 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -13,21 +13,6 @@ + #include + #include + #include "../utfconv.h" +- +- // Windows does not define the S_ISREG and S_ISDIR macros in stat.h, so we do. +- // We have to define _CRT_INTERNAL_NONSTDC_NAMES 1 before #including sys/stat.h +- // in order for Microsoft's stat.h to define names like S_IFMT, S_IFREG, and S_IFDIR, +- // rather than just defining _S_IFMT, _S_IFREG, and _S_IFDIR as it normally does. +- #define _CRT_INTERNAL_NONSTDC_NAMES 1 +- #include +- #include +- #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) +- #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +- #endif +- #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) +- #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +- #endif +- + #define fileno _fileno + #define ftruncate _chsize + #else +@@ -760,30 +745,46 @@ static int f_absolute_path(lua_State *L) { + static int f_get_file_info(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++ lua_newtable(L); + #ifdef _WIN32 +- struct _stat s; + LPWSTR wpath = utfconv_utf8towc(path); + if (wpath == NULL) { +- lua_pushnil(L); +- lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ lua_pushnil(L); lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ WIN32_FILE_ATTRIBUTE_DATA data; ++ if (!GetFileAttributesExW(wpath, GetFileExInfoStandard, &data)) { ++ free(wpath); ++ lua_pushnil(L); push_win32_error(L, GetLastError()); + return 2; + } +- int err = _wstat(wpath, &s); + free(wpath); ++ ULARGE_INTEGER large_int = {0}; ++ #define TICKS_PER_MILISECOND 10000 ++ #define EPOCH_DIFFERENCE 11644473600000LL ++ // https://stackoverflow.com/questions/6161776/convert-windows-filetime-to-second-in-unix-linux ++ large_int.HighPart = data.ftLastWriteTime.dwHighDateTime; large_int.LowPart = data.ftLastWriteTime.dwLowDateTime; ++ lua_pushnumber(L, (double)((large_int.QuadPart / TICKS_PER_MILISECOND - EPOCH_DIFFERENCE)/1000.0)); ++ lua_setfield(L, -2, "modified"); ++ ++ large_int.HighPart = data.nFileSizeHigh; large_int.LowPart = data.nFileSizeLow; ++ lua_pushinteger(L, large_int.QuadPart); ++ lua_setfield(L, -2, "size"); ++ ++ lua_pushstring(L, data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ? "dir" : "file"); ++ lua_setfield(L, -2, "type"); ++ ++ lua_pushboolean(L, data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY && data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT); ++ lua_setfield(L, -2, "symlink"); + #else + struct stat s; + int err = stat(path, &s); +-#endif + if (err < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); + return 2; + } + +- lua_newtable(L); +- lua_pushinteger(L, s.st_mtime); +- lua_setfield(L, -2, "modified"); +- + lua_pushinteger(L, s.st_size); + lua_setfield(L, -2, "size"); + +@@ -796,7 +797,21 @@ static int f_get_file_info(lua_State *L) { + } + lua_setfield(L, -2, "type"); + +-#if __linux__ ++ double mtime; ++ #if _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE > 700 || _POSIX_C_SOURCE >= 200809L ++ mtime = (double)s.st_mtim.tv_sec + (s.st_mtim.tv_nsec / 1000000000.0); ++ #elif __APPLE__ ++ #if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) ++ mtime = (double)s.st_mtimespec.tv_sec + (s.st_mtimespec.tv_nsec / 1000000000.0); ++ #else ++ mtime = (double)s.st_mtime + (s.st_atimensec / 1000000000.0); ++ #endif ++ #else ++ mtime = s.st_mtime; ++ #endif ++ lua_pushnumber(L, mtime); ++ lua_setfield(L, -2, "modified"); ++ + if (S_ISDIR(s.st_mode)) { + if (lstat(path, &s) == 0) { + lua_pushboolean(L, S_ISLNK(s.st_mode)); diff --git a/tasks/lite-xl__lite-xl-1864/solution/solve.sh b/tasks/lite-xl__lite-xl-1864/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/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/lite-xl__lite-xl-1864/task.toml b/tasks/lite-xl__lite-xl-1864/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9babe1a2e3781d5861cfd2da804202da3888662b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1864" +description = "api/system: make stat() call consistent across platforms" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "efa257ddbdd9ade1cad588918c62f091493ccb1b" +reference = "https://github.com/lite-xl/lite-xl/pull/1864" +source_access = "auto" +built_at = "2026-11-16T16:09:56.313483+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:48839659e2d27338b28a4dc9b198322930795c9b8ca56eca089c94e05703137f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-04T14:17:11Z" +diff_format = "unified" +context_files = [ + "docs/api/system.lua", + "src/api/system.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 68 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.301262+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e471019fc62f655a2609323e51e42ae2bc2456a7a8e3dcf0a0d756b495639e90" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1864/tests/capture.py b/tasks/lite-xl__lite-xl-1864/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/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/lite-xl__lite-xl-1864/tests/instruction.md b/tasks/lite-xl__lite-xl-1864/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fb8966abdac18f1d0e00122f4d081fc730a9be8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** api/system: make stat() call consistent across platforms + +## Description + +Includes #1826. + +This PR uses GetFileAttributesExW on Windows to get everything we need for get_file_info(), including `symlink`. All platforms will now have `symlink` and high-resolution timestamps if supported. This should help with #1862. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1864/tests/oracle.patch b/tasks/lite-xl__lite-xl-1864/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d9294a3d4c811c5952e82d38ca4fade105c00c07 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/tests/oracle.patch @@ -0,0 +1,125 @@ +diff --git a/docs/api/system.lua b/docs/api/system.lua +index 66af600f..60870529 100644 +--- a/docs/api/system.lua ++++ b/docs/api/system.lua +@@ -8,13 +8,14 @@ system = {} + ---@alias system.fileinfotype + ---| "file" # It is a file. + ---| "dir" # It is a directory. ++---| nil # The file type is unspecified. + + --- + ---@class system.fileinfo + ---@field public modified number A timestamp in seconds. + ---@field public size number Size in bytes. + ---@field public type system.fileinfotype Type of file +----@field public symlink boolean The directory is a symlink. This field is only set on Linux and on directories. ++---@field public symlink boolean The directory is a symlink. This field is only set on directories. + + --- + ---Core function used to retrieve the current event been triggered by SDL. +diff --git a/src/api/system.c b/src/api/system.c +index ace17337..958bab1b 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -13,21 +13,6 @@ + #include + #include + #include "../utfconv.h" +- +- // Windows does not define the S_ISREG and S_ISDIR macros in stat.h, so we do. +- // We have to define _CRT_INTERNAL_NONSTDC_NAMES 1 before #including sys/stat.h +- // in order for Microsoft's stat.h to define names like S_IFMT, S_IFREG, and S_IFDIR, +- // rather than just defining _S_IFMT, _S_IFREG, and _S_IFDIR as it normally does. +- #define _CRT_INTERNAL_NONSTDC_NAMES 1 +- #include +- #include +- #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG) +- #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +- #endif +- #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR) +- #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +- #endif +- + #define fileno _fileno + #define ftruncate _chsize + #else +@@ -760,30 +745,46 @@ static int f_absolute_path(lua_State *L) { + static int f_get_file_info(lua_State *L) { + const char *path = luaL_checkstring(L, 1); + ++ lua_newtable(L); + #ifdef _WIN32 +- struct _stat s; + LPWSTR wpath = utfconv_utf8towc(path); + if (wpath == NULL) { +- lua_pushnil(L); +- lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ lua_pushnil(L); lua_pushstring(L, UTFCONV_ERROR_INVALID_CONVERSION); ++ return 2; ++ } ++ WIN32_FILE_ATTRIBUTE_DATA data; ++ if (!GetFileAttributesExW(wpath, GetFileExInfoStandard, &data)) { ++ free(wpath); ++ lua_pushnil(L); push_win32_error(L, GetLastError()); + return 2; + } +- int err = _wstat(wpath, &s); + free(wpath); ++ ULARGE_INTEGER large_int = {0}; ++ #define TICKS_PER_MILISECOND 10000 ++ #define EPOCH_DIFFERENCE 11644473600000LL ++ // https://stackoverflow.com/questions/6161776/convert-windows-filetime-to-second-in-unix-linux ++ large_int.HighPart = data.ftLastWriteTime.dwHighDateTime; large_int.LowPart = data.ftLastWriteTime.dwLowDateTime; ++ lua_pushnumber(L, (double)((large_int.QuadPart / TICKS_PER_MILISECOND - EPOCH_DIFFERENCE)/1000.0)); ++ lua_setfield(L, -2, "modified"); ++ ++ large_int.HighPart = data.nFileSizeHigh; large_int.LowPart = data.nFileSizeLow; ++ lua_pushinteger(L, large_int.QuadPart); ++ lua_setfield(L, -2, "size"); ++ ++ lua_pushstring(L, data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ? "dir" : "file"); ++ lua_setfield(L, -2, "type"); ++ ++ lua_pushboolean(L, data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY && data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT); ++ lua_setfield(L, -2, "symlink"); + #else + struct stat s; + int err = stat(path, &s); +-#endif + if (err < 0) { + lua_pushnil(L); + lua_pushstring(L, strerror(errno)); + return 2; + } + +- lua_newtable(L); +- lua_pushinteger(L, s.st_mtime); +- lua_setfield(L, -2, "modified"); +- + lua_pushinteger(L, s.st_size); + lua_setfield(L, -2, "size"); + +@@ -796,7 +797,21 @@ static int f_get_file_info(lua_State *L) { + } + lua_setfield(L, -2, "type"); + +-#if __linux__ ++ double mtime; ++ #if _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE > 700 || _POSIX_C_SOURCE >= 200809L ++ mtime = (double)s.st_mtim.tv_sec + (s.st_mtim.tv_nsec / 1000000000.0); ++ #elif __APPLE__ ++ #if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) ++ mtime = (double)s.st_mtimespec.tv_sec + (s.st_mtimespec.tv_nsec / 1000000000.0); ++ #else ++ mtime = (double)s.st_mtime + (s.st_atimensec / 1000000000.0); ++ #endif ++ #else ++ mtime = s.st_mtime; ++ #endif ++ lua_pushnumber(L, mtime); ++ lua_setfield(L, -2, "modified"); ++ + if (S_ISDIR(s.st_mode)) { + if (lstat(path, &s) == 0) { + lua_pushboolean(L, S_ISLNK(s.st_mode)); diff --git a/tasks/lite-xl__lite-xl-1864/tests/test.sh b/tasks/lite-xl__lite-xl-1864/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a86f795051b02c6b6d05fc262010882539f3b57f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/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 efa257ddbdd9ade1cad588918c62f091493ccb1b > "$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/lite-xl__lite-xl-1864/tests/verifier.py b/tasks/lite-xl__lite-xl-1864/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1864/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/lite-xl__lite-xl-1876/environment/Dockerfile b/tasks/lite-xl__lite-xl-1876/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1876/instruction.md b/tasks/lite-xl__lite-xl-1876/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0535526ca7450e39e05ae6e691e7c7ef61b543b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** improve projectsearch + +## Description + +- stick status to top of view +- add horizontal scrolling +- added ellipsis at the end of the text if it's too long + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1876/solution/patch.diff b/tasks/lite-xl__lite-xl-1876/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c626cc706b5d7885d047d31538617109063bb023 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/solution/patch.diff @@ -0,0 +1,105 @@ +diff --git a/data/plugins/projectsearch.lua b/data/plugins/projectsearch.lua +index 8c8dfd95..bcd36292 100644 +--- a/data/plugins/projectsearch.lua ++++ b/data/plugins/projectsearch.lua +@@ -15,6 +15,7 @@ function ResultsView:new(path, text, fn) + ResultsView.super.new(self) + self.scrollable = true + self.brightness = 0 ++ self.max_h_scroll = 0 + self:begin_search(path, text, fn) + end + +@@ -34,7 +35,9 @@ local function find_all_matches_in_file(t, filename, fn) + -- Insert maximum 256 characters. If we insert more, for compiled files, which can have very long lines + -- things tend to get sluggish. If our line is longer than 80 characters, begin to truncate the thing. + local start_index = math.max(s - 80, 1) +- table.insert(t, { file = filename, text = (start_index > 1 and "..." or "") .. line:sub(start_index, 256 + start_index), line = n, col = s }) ++ local text = (start_index > 1 and "..." or "") .. line:sub(start_index, 256 + start_index) ++ if #line > 256 + start_index then text = text .. "..." end ++ table.insert(t, { file = filename, text = text, line = n, col = s }) + core.redraw = true + end + if n % 100 == 0 then coroutine.yield(0) end +@@ -133,10 +136,16 @@ function ResultsView:get_scrollable_size() + end + + ++function ResultsView:get_h_scrollable_size() ++ return self.max_h_scroll ++end ++ ++ + function ResultsView:get_visible_results_range() + local lh = self:get_line_height() + local oy = self:get_results_yoffset() +- local min = math.max(1, math.floor((self.scroll.y - oy) / lh)) ++ local min = self.scroll.y+oy-style.font:get_height() ++ min = math.max(1, math.floor(min / lh)) + return min, min + math.floor(self.size.y / lh) + 1 + end + +@@ -150,7 +159,8 @@ function ResultsView:each_visible_result() + for i = min, max do + local item = self.results[i] + if not item then break end +- coroutine.yield(i, item, x, y, self.size.x, lh) ++ local _, _, w = self:get_content_bounds() ++ coroutine.yield(i, item, x, y, w, lh) + y = y + lh + end + end) +@@ -159,9 +169,9 @@ end + + function ResultsView:scroll_to_make_selected_visible() + local h = self:get_line_height() +- local y = self:get_results_yoffset() + h * (self.selected_idx - 1) ++ local y = h * (self.selected_idx - 1) + self.scroll.to.y = math.min(self.scroll.to.y, y) +- self.scroll.to.y = math.max(self.scroll.to.y, y + h - self.size.y) ++ self.scroll.to.y = math.max(self.scroll.to.y, y + h - self.size.y + self:get_results_yoffset()) + end + + +@@ -169,7 +179,13 @@ function ResultsView:draw() + self:draw_background(style.background) + + -- status +- local ox, oy = self:get_content_offset() ++ local ox, oy = self.position.x, self.position.y ++ local yoffset = self:get_results_yoffset() ++ renderer.draw_rect(self.position.x, self.position.y, self.size.x, yoffset, style.background) ++ if self.scroll.y ~= 0 then ++ renderer.draw_rect(self.position.x, self.position.y+yoffset, self.size.x, style.divider_size, style.divider) ++ end ++ + local x, y = ox + style.padding.x, oy + style.padding.y + local files_number = core.project_files_number() + local per = common.clamp(files_number and self.last_file_idx / files_number or 1, 0, 1) +@@ -191,7 +207,6 @@ function ResultsView:draw() + renderer.draw_text(style.font, text, x, y, color) + + -- horizontal line +- local yoffset = self:get_results_yoffset() + local x = ox + style.padding.x + local w = self.size.x - style.padding.x * 2 + local h = style.divider_size +@@ -202,6 +217,8 @@ function ResultsView:draw() + end + + -- results ++ local _, _, bw = self:get_content_bounds() ++ core.push_clip_rect(ox, oy+yoffset + style.divider_size, bw, self.size.y-yoffset) + local y1, y2 = self.position.y, self.position.y + self.size.y + for i, item, x,y,w,h in self:each_visible_result() do + local color = style.text +@@ -213,7 +230,9 @@ function ResultsView:draw() + local text = string.format("%s at line %d (col %d): ", item.file, item.line, item.col) + x = common.draw_text(style.font, style.dim, text, "left", x, y, w, h) + x = common.draw_text(style.code_font, color, item.text, "left", x, y, w, h) ++ self.max_h_scroll = math.max(self.max_h_scroll, x) + end ++ core.pop_clip_rect() + + self:draw_scrollbar() + end diff --git a/tasks/lite-xl__lite-xl-1876/solution/solve.sh b/tasks/lite-xl__lite-xl-1876/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/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/lite-xl__lite-xl-1876/task.toml b/tasks/lite-xl__lite-xl-1876/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c34dac37ae5ee0881451092658649ddd45dc264 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1876" +description = "improve projectsearch" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1876" +source_access = "auto" +built_at = "2026-11-16T16:09:56.339077+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:459915e8f5d2ce2f39ef0f06021c889337306b044fcb09fa6aec3fef853f6a3b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T16:10:33Z" +diff_format = "unified" +context_files = [ + "data/plugins/projectsearch.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 33 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.301702+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1876/tests/capture.py b/tasks/lite-xl__lite-xl-1876/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/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/lite-xl__lite-xl-1876/tests/instruction.md b/tasks/lite-xl__lite-xl-1876/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0535526ca7450e39e05ae6e691e7c7ef61b543b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** improve projectsearch + +## Description + +- stick status to top of view +- add horizontal scrolling +- added ellipsis at the end of the text if it's too long + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1876/tests/oracle.patch b/tasks/lite-xl__lite-xl-1876/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c626cc706b5d7885d047d31538617109063bb023 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/tests/oracle.patch @@ -0,0 +1,105 @@ +diff --git a/data/plugins/projectsearch.lua b/data/plugins/projectsearch.lua +index 8c8dfd95..bcd36292 100644 +--- a/data/plugins/projectsearch.lua ++++ b/data/plugins/projectsearch.lua +@@ -15,6 +15,7 @@ function ResultsView:new(path, text, fn) + ResultsView.super.new(self) + self.scrollable = true + self.brightness = 0 ++ self.max_h_scroll = 0 + self:begin_search(path, text, fn) + end + +@@ -34,7 +35,9 @@ local function find_all_matches_in_file(t, filename, fn) + -- Insert maximum 256 characters. If we insert more, for compiled files, which can have very long lines + -- things tend to get sluggish. If our line is longer than 80 characters, begin to truncate the thing. + local start_index = math.max(s - 80, 1) +- table.insert(t, { file = filename, text = (start_index > 1 and "..." or "") .. line:sub(start_index, 256 + start_index), line = n, col = s }) ++ local text = (start_index > 1 and "..." or "") .. line:sub(start_index, 256 + start_index) ++ if #line > 256 + start_index then text = text .. "..." end ++ table.insert(t, { file = filename, text = text, line = n, col = s }) + core.redraw = true + end + if n % 100 == 0 then coroutine.yield(0) end +@@ -133,10 +136,16 @@ function ResultsView:get_scrollable_size() + end + + ++function ResultsView:get_h_scrollable_size() ++ return self.max_h_scroll ++end ++ ++ + function ResultsView:get_visible_results_range() + local lh = self:get_line_height() + local oy = self:get_results_yoffset() +- local min = math.max(1, math.floor((self.scroll.y - oy) / lh)) ++ local min = self.scroll.y+oy-style.font:get_height() ++ min = math.max(1, math.floor(min / lh)) + return min, min + math.floor(self.size.y / lh) + 1 + end + +@@ -150,7 +159,8 @@ function ResultsView:each_visible_result() + for i = min, max do + local item = self.results[i] + if not item then break end +- coroutine.yield(i, item, x, y, self.size.x, lh) ++ local _, _, w = self:get_content_bounds() ++ coroutine.yield(i, item, x, y, w, lh) + y = y + lh + end + end) +@@ -159,9 +169,9 @@ end + + function ResultsView:scroll_to_make_selected_visible() + local h = self:get_line_height() +- local y = self:get_results_yoffset() + h * (self.selected_idx - 1) ++ local y = h * (self.selected_idx - 1) + self.scroll.to.y = math.min(self.scroll.to.y, y) +- self.scroll.to.y = math.max(self.scroll.to.y, y + h - self.size.y) ++ self.scroll.to.y = math.max(self.scroll.to.y, y + h - self.size.y + self:get_results_yoffset()) + end + + +@@ -169,7 +179,13 @@ function ResultsView:draw() + self:draw_background(style.background) + + -- status +- local ox, oy = self:get_content_offset() ++ local ox, oy = self.position.x, self.position.y ++ local yoffset = self:get_results_yoffset() ++ renderer.draw_rect(self.position.x, self.position.y, self.size.x, yoffset, style.background) ++ if self.scroll.y ~= 0 then ++ renderer.draw_rect(self.position.x, self.position.y+yoffset, self.size.x, style.divider_size, style.divider) ++ end ++ + local x, y = ox + style.padding.x, oy + style.padding.y + local files_number = core.project_files_number() + local per = common.clamp(files_number and self.last_file_idx / files_number or 1, 0, 1) +@@ -191,7 +207,6 @@ function ResultsView:draw() + renderer.draw_text(style.font, text, x, y, color) + + -- horizontal line +- local yoffset = self:get_results_yoffset() + local x = ox + style.padding.x + local w = self.size.x - style.padding.x * 2 + local h = style.divider_size +@@ -202,6 +217,8 @@ function ResultsView:draw() + end + + -- results ++ local _, _, bw = self:get_content_bounds() ++ core.push_clip_rect(ox, oy+yoffset + style.divider_size, bw, self.size.y-yoffset) + local y1, y2 = self.position.y, self.position.y + self.size.y + for i, item, x,y,w,h in self:each_visible_result() do + local color = style.text +@@ -213,7 +230,9 @@ function ResultsView:draw() + local text = string.format("%s at line %d (col %d): ", item.file, item.line, item.col) + x = common.draw_text(style.font, style.dim, text, "left", x, y, w, h) + x = common.draw_text(style.code_font, color, item.text, "left", x, y, w, h) ++ self.max_h_scroll = math.max(self.max_h_scroll, x) + end ++ core.pop_clip_rect() + + self:draw_scrollbar() + end diff --git a/tasks/lite-xl__lite-xl-1876/tests/test.sh b/tasks/lite-xl__lite-xl-1876/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1876/tests/verifier.py b/tasks/lite-xl__lite-xl-1876/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1876/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/lite-xl__lite-xl-1877/environment/Dockerfile b/tasks/lite-xl__lite-xl-1877/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8df97b253b6de799935779651a53e839313c8c37 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 872364ded3525e91f71d5f70622e25b875143d11 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 872364ded3525e91f71d5f70622e25b875143d11 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 872364ded3525e91f71d5f70622e25b875143d11 \ + && 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/lite-xl__lite-xl-1877/instruction.md b/tasks/lite-xl__lite-xl-1877/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bec98213c04581ba8eb0cfca0653a9836bf5b71c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Use lite-xl-build-box-manylinux + +## Description + +This PR builds Lite XL with lite-xl-build-box-manylinux. + +I have created a build box variant with [manylinux_2014](https://github.com/pypa/manylinux). manylinux is Python's solution for the whole Glibc incompatibility thing and we are using the CentOS 7 variant with Glibc 2.17 while Ubuntu 18.04 is on Glibc 2.27. Python obviously works on the manylinux image, and some amenities were installed by default (GCC, CMake, new version of Git). Hopefully this would allow us to support more systems and make maintenance easier. + +Example build is in https://github.com/takase1121/lite-xl/releases/tag/v2.1.5-manylinux. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `872364ded352`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1877/solution/patch.diff b/tasks/lite-xl__lite-xl-1877/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9ddacbff93389bacecf860ba92677e1096fa3c28 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 6535114a..234fa37a 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -92,7 +92,7 @@ jobs: + sudo apt-get install -y ccache + + - name: Build Portable +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | +@@ -100,7 +100,7 @@ jobs: + bash scripts/build.sh --debug --forcefallback --portable --release + + - name: Package Portables +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | +@@ -108,7 +108,7 @@ jobs: + bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release + + - name: Build AppImages +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | diff --git a/tasks/lite-xl__lite-xl-1877/solution/solve.sh b/tasks/lite-xl__lite-xl-1877/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/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/lite-xl__lite-xl-1877/task.toml b/tasks/lite-xl__lite-xl-1877/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c85b468372b9f1da7de2a05718b1f7a5ccf1ab90 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1877" +description = "Use lite-xl-build-box-manylinux" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "872364ded3525e91f71d5f70622e25b875143d11" +reference = "https://github.com/lite-xl/lite-xl/pull/1877" +source_access = "auto" +built_at = "2026-11-16T16:09:56.199608+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1cd69481fa418027fedab37f6f5daf170b55287d1dc10e135f1336523c923190" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-09-06T16:49:14Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.302151+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:76aa51f0a7fc79f785b8fa9c3083ec0022b407f190f9a197748754500ffaff29" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1877/tests/capture.py b/tasks/lite-xl__lite-xl-1877/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/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/lite-xl__lite-xl-1877/tests/instruction.md b/tasks/lite-xl__lite-xl-1877/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bec98213c04581ba8eb0cfca0653a9836bf5b71c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Use lite-xl-build-box-manylinux + +## Description + +This PR builds Lite XL with lite-xl-build-box-manylinux. + +I have created a build box variant with [manylinux_2014](https://github.com/pypa/manylinux). manylinux is Python's solution for the whole Glibc incompatibility thing and we are using the CentOS 7 variant with Glibc 2.17 while Ubuntu 18.04 is on Glibc 2.27. Python obviously works on the manylinux image, and some amenities were installed by default (GCC, CMake, new version of Git). Hopefully this would allow us to support more systems and make maintenance easier. + +Example build is in https://github.com/takase1121/lite-xl/releases/tag/v2.1.5-manylinux. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `872364ded352`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1877/tests/oracle.patch b/tasks/lite-xl__lite-xl-1877/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9ddacbff93389bacecf860ba92677e1096fa3c28 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 6535114a..234fa37a 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -92,7 +92,7 @@ jobs: + sudo apt-get install -y ccache + + - name: Build Portable +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | +@@ -100,7 +100,7 @@ jobs: + bash scripts/build.sh --debug --forcefallback --portable --release + + - name: Package Portables +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | +@@ -108,7 +108,7 @@ jobs: + bash scripts/package.sh --version ${INSTALL_REF} --debug --addons --binary --release + + - name: Build AppImages +- uses: docker://ghcr.io/lite-xl/lite-xl-build-box:v2.2.0 ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 + with: + entrypoint: /entrypoint.sh + args: | diff --git a/tasks/lite-xl__lite-xl-1877/tests/test.sh b/tasks/lite-xl__lite-xl-1877/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d3890dd4672ae264feeef7296c76e41dd95078b5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/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 872364ded3525e91f71d5f70622e25b875143d11 > "$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/lite-xl__lite-xl-1877/tests/verifier.py b/tasks/lite-xl__lite-xl-1877/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1877/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/lite-xl__lite-xl-1880/environment/Dockerfile b/tasks/lite-xl__lite-xl-1880/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..56ec381f1f89d190b3d421f804899c99e7feef69 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f5c63d8c8f55e5d40f25e999e57736169f9a559d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f5c63d8c8f55e5d40f25e999e57736169f9a559d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f5c63d8c8f55e5d40f25e999e57736169f9a559d \ + && 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/lite-xl__lite-xl-1880/instruction.md b/tasks/lite-xl__lite-xl-1880/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ab915e0667998d7dfb569038a46fca18453f3e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Added in keyboard shortcut tooltips for ToolbarView. + +## Description + +Automatically adds a dim keyboard shortcut to the tooltip for buttons toolbarview. + +![image](https://github.com/user-attachments/assets/8c29b6fd-108d-45e5-bdc4-791dbba9d1a7) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f5c63d8c8f55`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1880/solution/patch.diff b/tasks/lite-xl__lite-xl-1880/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cd3d22dfc818ee073156075007c19259139a73ad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/data/plugins/toolbarview.lua b/data/plugins/toolbarview.lua +index ddc0f39d..9523066d 100644 +--- a/data/plugins/toolbarview.lua ++++ b/data/plugins/toolbarview.lua +@@ -3,6 +3,7 @@ local core = require "core" + local common = require "core.common" + local command = require "core.command" + local style = require "core.style" ++local keymap = require "core.keymap" + local View = require "core.view" + + local ToolbarView = View:extend() +@@ -120,7 +121,9 @@ function ToolbarView:on_mouse_moved(px, py, ...) + y_min, y_max = y, y + h + if px > x and py > y and px <= x + w and py <= y + h then + self.hovered_item = item +- core.status_view:show_tooltip(command.prettify_name(item.command)) ++ local binding = keymap.get_binding(item.command) ++ local name = command.prettify_name(item.command) ++ core.status_view:show_tooltip(binding and { name, style.dim, " ", binding } or { name }) + self.tooltip = true + return + end diff --git a/tasks/lite-xl__lite-xl-1880/solution/solve.sh b/tasks/lite-xl__lite-xl-1880/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/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/lite-xl__lite-xl-1880/task.toml b/tasks/lite-xl__lite-xl-1880/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ac0b462dee7bef3d593f22e32b0871ec0f8b3d55 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1880" +description = "Added in keyboard shortcut tooltips for ToolbarView." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f5c63d8c8f55e5d40f25e999e57736169f9a559d" +reference = "https://github.com/lite-xl/lite-xl/pull/1880" +source_access = "auto" +built_at = "2026-11-16T16:09:56.344562+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f50acafeb7636797c45a33ecce5f5f2c5026fbbe147250a593fd47fbf5dcd78c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-02T03:41:12Z" +diff_format = "unified" +context_files = [ + "data/plugins/toolbarview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.302600+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eeb02daec83756b9655d80a49bed3eb6ce16faef6e1bc4f921575fe46162b05b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1880/tests/capture.py b/tasks/lite-xl__lite-xl-1880/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/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/lite-xl__lite-xl-1880/tests/instruction.md b/tasks/lite-xl__lite-xl-1880/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..83ab915e0667998d7dfb569038a46fca18453f3e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Added in keyboard shortcut tooltips for ToolbarView. + +## Description + +Automatically adds a dim keyboard shortcut to the tooltip for buttons toolbarview. + +![image](https://github.com/user-attachments/assets/8c29b6fd-108d-45e5-bdc4-791dbba9d1a7) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f5c63d8c8f55`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1880/tests/oracle.patch b/tasks/lite-xl__lite-xl-1880/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cd3d22dfc818ee073156075007c19259139a73ad --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/data/plugins/toolbarview.lua b/data/plugins/toolbarview.lua +index ddc0f39d..9523066d 100644 +--- a/data/plugins/toolbarview.lua ++++ b/data/plugins/toolbarview.lua +@@ -3,6 +3,7 @@ local core = require "core" + local common = require "core.common" + local command = require "core.command" + local style = require "core.style" ++local keymap = require "core.keymap" + local View = require "core.view" + + local ToolbarView = View:extend() +@@ -120,7 +121,9 @@ function ToolbarView:on_mouse_moved(px, py, ...) + y_min, y_max = y, y + h + if px > x and py > y and px <= x + w and py <= y + h then + self.hovered_item = item +- core.status_view:show_tooltip(command.prettify_name(item.command)) ++ local binding = keymap.get_binding(item.command) ++ local name = command.prettify_name(item.command) ++ core.status_view:show_tooltip(binding and { name, style.dim, " ", binding } or { name }) + self.tooltip = true + return + end diff --git a/tasks/lite-xl__lite-xl-1880/tests/test.sh b/tasks/lite-xl__lite-xl-1880/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e98d08b0e984636c293eb42eb5e73f486b26d8f6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/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 f5c63d8c8f55e5d40f25e999e57736169f9a559d > "$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/lite-xl__lite-xl-1880/tests/verifier.py b/tasks/lite-xl__lite-xl-1880/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1880/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/lite-xl__lite-xl-1891/environment/Dockerfile b/tasks/lite-xl__lite-xl-1891/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc773bb67a2159c737021bdbca5427266f58ad52 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5b6c666652f6dfba8d8ad9c5298db65779cad31d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5b6c666652f6dfba8d8ad9c5298db65779cad31d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5b6c666652f6dfba8d8ad9c5298db65779cad31d \ + && 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/lite-xl__lite-xl-1891/instruction.md b/tasks/lite-xl__lite-xl-1891/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..620004d3dd78b2ed252ee583c1ce9475f783dca0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Implement logic for tracking active window + +## Description + +this will be needed when SDL3 happens due to many more functions requesting a window handle +wording could be improved? maybe `current` instead of `active`? idk, lots of bike shedding. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b6c666652f6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1891/solution/patch.diff b/tasks/lite-xl__lite-xl-1891/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..06a0eeb173dc34935f29f3230e08f0ba1f95f2af --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/solution/patch.diff @@ -0,0 +1,137 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index ef10cc03..6ecb4e77 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -8,8 +8,6 @@ + #endif + #include "lua.h" + +-RenWindow *active_window_renderer = NULL; +- + // a reference index to a table that stores the fonts + static int RENDERER_FONT_REF = LUA_NOREF; + +@@ -119,7 +117,7 @@ static bool font_retrieve(lua_State* L, RenFont** fonts, int idx) { + } + } + #ifdef LITE_USE_SDL_RENDERER +- update_font_scale(active_window_renderer, fonts); ++ update_font_scale(ren_get_target_window(), fonts); + #endif + return is_table; + } +@@ -231,8 +229,9 @@ static int f_font_set_size(lua_State *L) { + float size = luaL_checknumber(L, 2); + int scale = 1; + #ifdef LITE_USE_SDL_RENDERER +- if (active_window_renderer != NULL) { +- scale = renwin_get_surface(active_window_renderer).scale; ++ RenWindow *window = ren_get_target_window(); ++ if (window != NULL) { ++ scale = renwin_get_surface(window).scale; + } + #endif + ren_font_group_set_size(fonts, size, scale); +@@ -294,8 +293,9 @@ static int f_show_debug(lua_State *L) { + + static int f_get_size(lua_State *L) { + int w = 0, h = 0; +- if (active_window_renderer) +- ren_get_size(active_window_renderer, &w, &h); ++ RenWindow *window = ren_get_target_window(); ++ if (window) ++ ren_get_size(window, &w, &h); + lua_pushnumber(L, w); + lua_pushnumber(L, h); + return 2; +@@ -303,17 +303,19 @@ static int f_get_size(lua_State *L) { + + + static int f_begin_frame(UNUSED lua_State *L) { +- assert(active_window_renderer == NULL); +- active_window_renderer = *(RenWindow**)luaL_checkudata(L, 1, API_TYPE_RENWINDOW); +- rencache_begin_frame(active_window_renderer); ++ assert(ren_get_target_window() == NULL); ++ RenWindow *window = *(RenWindow**)luaL_checkudata(L, 1, API_TYPE_RENWINDOW); ++ ren_set_target_window(window); ++ rencache_begin_frame(window); + return 0; + } + + + static int f_end_frame(UNUSED lua_State *L) { +- assert(active_window_renderer != NULL); +- rencache_end_frame(active_window_renderer); +- active_window_renderer = NULL; ++ RenWindow *window = ren_get_target_window(); ++ assert(window != NULL); ++ rencache_end_frame(window); ++ ren_set_target_window(NULL); + // clear the font reference table + lua_newtable(L); + lua_rawseti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); +@@ -334,7 +336,7 @@ static int f_set_clip_rect(lua_State *L) { + lua_Number w = luaL_checknumber(L, 3); + lua_Number h = luaL_checknumber(L, 4); + RenRect rect = rect_to_grid(x, y, w, h); +- rencache_set_clip_rect(active_window_renderer, rect); ++ rencache_set_clip_rect(ren_get_target_window(), rect); + return 0; + } + +@@ -346,7 +348,7 @@ static int f_draw_rect(lua_State *L) { + lua_Number h = luaL_checknumber(L, 4); + RenRect rect = rect_to_grid(x, y, w, h); + RenColor color = checkcolor(L, 5, 255); +- rencache_draw_rect(active_window_renderer, rect, color); ++ rencache_draw_rect(ren_get_target_window(), rect, color); + return 0; + } + +@@ -371,7 +373,7 @@ static int f_draw_text(lua_State *L) { + double x = luaL_checknumber(L, 3); + int y = luaL_checknumber(L, 4); + RenColor color = checkcolor(L, 5, 255); +- x = rencache_draw_text(active_window_renderer, fonts, text, len, x, y, color); ++ x = rencache_draw_text(ren_get_target_window(), fonts, text, len, x, y, color); + lua_pushnumber(L, x); + return 1; + } +diff --git a/src/renderer.c b/src/renderer.c +index 8a961995..abd9a35c 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -16,6 +16,7 @@ + // #define RENDERER_DEBUG + + static RenWindow **window_list = NULL; ++static RenWindow *target_window = NULL; + static size_t window_count = 0; + + // draw_rect_surface is used as a 1x1 surface to simplify ren_draw_rect with blending +@@ -794,3 +795,13 @@ RenWindow* ren_find_window_from_id(uint32_t id) { + SDL_Window *window = SDL_GetWindowFromID(id); + return ren_find_window(window); + } ++ ++RenWindow* ren_get_target_window(void) ++{ ++ return target_window; ++} ++ ++void ren_set_target_window(RenWindow *window) ++{ ++ target_window = window; ++} +diff --git a/src/renderer.h b/src/renderer.h +index a94d7024..67282211 100644 +--- a/src/renderer.h ++++ b/src/renderer.h +@@ -52,5 +52,7 @@ void ren_get_size(RenWindow *window_renderer, int *x, int *y); /* Reports the si + size_t ren_get_window_list(RenWindow ***window_list_dest); + RenWindow* ren_find_window(SDL_Window *window); + RenWindow* ren_find_window_from_id(uint32_t id); ++RenWindow* ren_get_target_window(void); ++void ren_set_target_window(RenWindow *window); + + #endif diff --git a/tasks/lite-xl__lite-xl-1891/solution/solve.sh b/tasks/lite-xl__lite-xl-1891/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/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/lite-xl__lite-xl-1891/task.toml b/tasks/lite-xl__lite-xl-1891/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08a656339148f935b227a7207c56584be0e114f0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1891" +description = "Implement logic for tracking active window" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "5b6c666652f6dfba8d8ad9c5298db65779cad31d" +reference = "https://github.com/lite-xl/lite-xl/pull/1891" +source_access = "auto" +built_at = "2026-11-16T16:09:56.341987+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a58f86e62f9676e1b1581719f5a47b062439d3cfe10ce56c06f51eaf55d35899" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T15:09:21Z" +diff_format = "unified" +context_files = [ + "src/api/renderer.c", + "src/renderer.c", + "src/renderer.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 47 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.303060+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6fca5194657853e24dcd813510c5ffa568bf8651321852b0c211cc2b55853898" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1891/tests/capture.py b/tasks/lite-xl__lite-xl-1891/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/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/lite-xl__lite-xl-1891/tests/instruction.md b/tasks/lite-xl__lite-xl-1891/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..620004d3dd78b2ed252ee583c1ce9475f783dca0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Implement logic for tracking active window + +## Description + +this will be needed when SDL3 happens due to many more functions requesting a window handle +wording could be improved? maybe `current` instead of `active`? idk, lots of bike shedding. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b6c666652f6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1891/tests/oracle.patch b/tasks/lite-xl__lite-xl-1891/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..06a0eeb173dc34935f29f3230e08f0ba1f95f2af --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/tests/oracle.patch @@ -0,0 +1,137 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index ef10cc03..6ecb4e77 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -8,8 +8,6 @@ + #endif + #include "lua.h" + +-RenWindow *active_window_renderer = NULL; +- + // a reference index to a table that stores the fonts + static int RENDERER_FONT_REF = LUA_NOREF; + +@@ -119,7 +117,7 @@ static bool font_retrieve(lua_State* L, RenFont** fonts, int idx) { + } + } + #ifdef LITE_USE_SDL_RENDERER +- update_font_scale(active_window_renderer, fonts); ++ update_font_scale(ren_get_target_window(), fonts); + #endif + return is_table; + } +@@ -231,8 +229,9 @@ static int f_font_set_size(lua_State *L) { + float size = luaL_checknumber(L, 2); + int scale = 1; + #ifdef LITE_USE_SDL_RENDERER +- if (active_window_renderer != NULL) { +- scale = renwin_get_surface(active_window_renderer).scale; ++ RenWindow *window = ren_get_target_window(); ++ if (window != NULL) { ++ scale = renwin_get_surface(window).scale; + } + #endif + ren_font_group_set_size(fonts, size, scale); +@@ -294,8 +293,9 @@ static int f_show_debug(lua_State *L) { + + static int f_get_size(lua_State *L) { + int w = 0, h = 0; +- if (active_window_renderer) +- ren_get_size(active_window_renderer, &w, &h); ++ RenWindow *window = ren_get_target_window(); ++ if (window) ++ ren_get_size(window, &w, &h); + lua_pushnumber(L, w); + lua_pushnumber(L, h); + return 2; +@@ -303,17 +303,19 @@ static int f_get_size(lua_State *L) { + + + static int f_begin_frame(UNUSED lua_State *L) { +- assert(active_window_renderer == NULL); +- active_window_renderer = *(RenWindow**)luaL_checkudata(L, 1, API_TYPE_RENWINDOW); +- rencache_begin_frame(active_window_renderer); ++ assert(ren_get_target_window() == NULL); ++ RenWindow *window = *(RenWindow**)luaL_checkudata(L, 1, API_TYPE_RENWINDOW); ++ ren_set_target_window(window); ++ rencache_begin_frame(window); + return 0; + } + + + static int f_end_frame(UNUSED lua_State *L) { +- assert(active_window_renderer != NULL); +- rencache_end_frame(active_window_renderer); +- active_window_renderer = NULL; ++ RenWindow *window = ren_get_target_window(); ++ assert(window != NULL); ++ rencache_end_frame(window); ++ ren_set_target_window(NULL); + // clear the font reference table + lua_newtable(L); + lua_rawseti(L, LUA_REGISTRYINDEX, RENDERER_FONT_REF); +@@ -334,7 +336,7 @@ static int f_set_clip_rect(lua_State *L) { + lua_Number w = luaL_checknumber(L, 3); + lua_Number h = luaL_checknumber(L, 4); + RenRect rect = rect_to_grid(x, y, w, h); +- rencache_set_clip_rect(active_window_renderer, rect); ++ rencache_set_clip_rect(ren_get_target_window(), rect); + return 0; + } + +@@ -346,7 +348,7 @@ static int f_draw_rect(lua_State *L) { + lua_Number h = luaL_checknumber(L, 4); + RenRect rect = rect_to_grid(x, y, w, h); + RenColor color = checkcolor(L, 5, 255); +- rencache_draw_rect(active_window_renderer, rect, color); ++ rencache_draw_rect(ren_get_target_window(), rect, color); + return 0; + } + +@@ -371,7 +373,7 @@ static int f_draw_text(lua_State *L) { + double x = luaL_checknumber(L, 3); + int y = luaL_checknumber(L, 4); + RenColor color = checkcolor(L, 5, 255); +- x = rencache_draw_text(active_window_renderer, fonts, text, len, x, y, color); ++ x = rencache_draw_text(ren_get_target_window(), fonts, text, len, x, y, color); + lua_pushnumber(L, x); + return 1; + } +diff --git a/src/renderer.c b/src/renderer.c +index 8a961995..abd9a35c 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -16,6 +16,7 @@ + // #define RENDERER_DEBUG + + static RenWindow **window_list = NULL; ++static RenWindow *target_window = NULL; + static size_t window_count = 0; + + // draw_rect_surface is used as a 1x1 surface to simplify ren_draw_rect with blending +@@ -794,3 +795,13 @@ RenWindow* ren_find_window_from_id(uint32_t id) { + SDL_Window *window = SDL_GetWindowFromID(id); + return ren_find_window(window); + } ++ ++RenWindow* ren_get_target_window(void) ++{ ++ return target_window; ++} ++ ++void ren_set_target_window(RenWindow *window) ++{ ++ target_window = window; ++} +diff --git a/src/renderer.h b/src/renderer.h +index a94d7024..67282211 100644 +--- a/src/renderer.h ++++ b/src/renderer.h +@@ -52,5 +52,7 @@ void ren_get_size(RenWindow *window_renderer, int *x, int *y); /* Reports the si + size_t ren_get_window_list(RenWindow ***window_list_dest); + RenWindow* ren_find_window(SDL_Window *window); + RenWindow* ren_find_window_from_id(uint32_t id); ++RenWindow* ren_get_target_window(void); ++void ren_set_target_window(RenWindow *window); + + #endif diff --git a/tasks/lite-xl__lite-xl-1891/tests/test.sh b/tasks/lite-xl__lite-xl-1891/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5df0f792c960632a9290df6461c30b28a08a33dc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/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 5b6c666652f6dfba8d8ad9c5298db65779cad31d > "$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/lite-xl__lite-xl-1891/tests/verifier.py b/tasks/lite-xl__lite-xl-1891/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1891/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/lite-xl__lite-xl-1895/environment/Dockerfile b/tasks/lite-xl__lite-xl-1895/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc773bb67a2159c737021bdbca5427266f58ad52 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5b6c666652f6dfba8d8ad9c5298db65779cad31d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5b6c666652f6dfba8d8ad9c5298db65779cad31d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5b6c666652f6dfba8d8ad9c5298db65779cad31d \ + && 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/lite-xl__lite-xl-1895/instruction.md b/tasks/lite-xl__lite-xl-1895/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47b534a38327c03b242dc73147b33a0d79a612f5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** treeview: remove unused code + +## Description + +It caused a lot of useless `system.absolute_path` calls. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b6c666652f6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1895/solution/patch.diff b/tasks/lite-xl__lite-xl-1895/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b27d53dc14cbbda76f6185c69a6b232feac82bfb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..cbeea267 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -442,9 +442,6 @@ function TreeView:draw() + self:draw_background(style.background2) + local _y, _h = self.position.y, self.size.y + +- local doc = core.active_view.doc +- local active_filename = doc and system.absolute_path(doc.filename or "") +- + for item, x,y,w,h in self:each_item() do + if y + h >= _y and y < _y + _h then + self:draw_item(item, diff --git a/tasks/lite-xl__lite-xl-1895/solution/solve.sh b/tasks/lite-xl__lite-xl-1895/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/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/lite-xl__lite-xl-1895/task.toml b/tasks/lite-xl__lite-xl-1895/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e955130f4bb8033f500388b949addd7b66ea33b5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1895" +description = "treeview: remove unused code" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "5b6c666652f6dfba8d8ad9c5298db65779cad31d" +reference = "https://github.com/lite-xl/lite-xl/pull/1895" +source_access = "auto" +built_at = "2026-11-16T16:09:56.343240+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:af1a74b23ff8f3a8ee299a541f056bafb6ab26c2664005575004dad8a447fc49" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-21T16:28:55Z" +diff_format = "unified" +context_files = [ + "data/plugins/treeview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.303505+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6fca5194657853e24dcd813510c5ffa568bf8651321852b0c211cc2b55853898" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1895/tests/capture.py b/tasks/lite-xl__lite-xl-1895/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/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/lite-xl__lite-xl-1895/tests/instruction.md b/tasks/lite-xl__lite-xl-1895/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47b534a38327c03b242dc73147b33a0d79a612f5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** treeview: remove unused code + +## Description + +It caused a lot of useless `system.absolute_path` calls. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5b6c666652f6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1895/tests/oracle.patch b/tasks/lite-xl__lite-xl-1895/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b27d53dc14cbbda76f6185c69a6b232feac82bfb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..cbeea267 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -442,9 +442,6 @@ function TreeView:draw() + self:draw_background(style.background2) + local _y, _h = self.position.y, self.size.y + +- local doc = core.active_view.doc +- local active_filename = doc and system.absolute_path(doc.filename or "") +- + for item, x,y,w,h in self:each_item() do + if y + h >= _y and y < _y + _h then + self:draw_item(item, diff --git a/tasks/lite-xl__lite-xl-1895/tests/test.sh b/tasks/lite-xl__lite-xl-1895/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5df0f792c960632a9290df6461c30b28a08a33dc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/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 5b6c666652f6dfba8d8ad9c5298db65779cad31d > "$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/lite-xl__lite-xl-1895/tests/verifier.py b/tasks/lite-xl__lite-xl-1895/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1895/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/lite-xl__lite-xl-1898/environment/Dockerfile b/tasks/lite-xl__lite-xl-1898/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1898/instruction.md b/tasks/lite-xl__lite-xl-1898/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24575aa3e35b27988c4d45aa2237a647a6d99f14 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** New-File ending in slash creates new folder instead + +## Description + +small creature comfort. but handy to have. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1898/solution/patch.diff b/tasks/lite-xl__lite-xl-1898/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cb50415cfe1223c117da430241acb165881f280d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/solution/patch.diff @@ -0,0 +1,53 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..0f56f2a6 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -775,6 +775,19 @@ command.add( + end + }) + ++local function create_new_file(filename) ++ core.log(filename) ++ local file = io.open(filename, "a+") ++ file:write("") ++ file:close() ++ core.root_view:open_doc(core.open_doc(filename)) ++ core.log("Created %s", filename) ++end ++ ++local function create_new_folder(dir_path) ++ common.mkdirp(dir_path) ++ core.log("Created %s", dir_path) ++end + + command.add( + function() +@@ -862,12 +875,12 @@ command.add( + text = text, + submit = function(filename) + local doc_filename = item.dir_name .. PATHSEP .. filename +- core.log(doc_filename) +- local file = io.open(doc_filename, "a+") +- file:write("") +- file:close() +- view:open_doc(doc_filename) +- core.log("Created %s", doc_filename) ++ local lastChar = filename:sub(#filename) ++ if lastChar == "/" or lastChar == "\\" then ++ create_new_folder(filename) ++ else ++ create_new_file(doc_filename) ++ end + end, + suggest = function(text) + return common.path_suggest(text, item.dir_name) +@@ -884,8 +897,7 @@ command.add( + text = text, + submit = function(filename) + local dir_path = item.dir_name .. PATHSEP .. filename +- common.mkdirp(dir_path) +- core.log("Created %s", dir_path) ++ create_new_folder(dir_path) + end, + suggest = function(text) + return common.path_suggest(text, item.dir_name) diff --git a/tasks/lite-xl__lite-xl-1898/solution/solve.sh b/tasks/lite-xl__lite-xl-1898/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/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/lite-xl__lite-xl-1898/task.toml b/tasks/lite-xl__lite-xl-1898/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..467c29411591e34b2fb8abcf89aba2d1aacde670 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1898" +description = "New-File ending in slash creates new folder instead" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1898" +source_access = "auto" +built_at = "2026-11-16T16:09:56.317285+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e9ef29254227844048d47568d29273da9c5836761e5e5cc793b0f9e1e3c9f434" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-02T07:32:39Z" +diff_format = "unified" +context_files = [ + "data/plugins/treeview.lua", +] +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:01.303951+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1898/tests/capture.py b/tasks/lite-xl__lite-xl-1898/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/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/lite-xl__lite-xl-1898/tests/instruction.md b/tasks/lite-xl__lite-xl-1898/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24575aa3e35b27988c4d45aa2237a647a6d99f14 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** New-File ending in slash creates new folder instead + +## Description + +small creature comfort. but handy to have. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1898/tests/oracle.patch b/tasks/lite-xl__lite-xl-1898/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cb50415cfe1223c117da430241acb165881f280d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/tests/oracle.patch @@ -0,0 +1,53 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..0f56f2a6 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -775,6 +775,19 @@ command.add( + end + }) + ++local function create_new_file(filename) ++ core.log(filename) ++ local file = io.open(filename, "a+") ++ file:write("") ++ file:close() ++ core.root_view:open_doc(core.open_doc(filename)) ++ core.log("Created %s", filename) ++end ++ ++local function create_new_folder(dir_path) ++ common.mkdirp(dir_path) ++ core.log("Created %s", dir_path) ++end + + command.add( + function() +@@ -862,12 +875,12 @@ command.add( + text = text, + submit = function(filename) + local doc_filename = item.dir_name .. PATHSEP .. filename +- core.log(doc_filename) +- local file = io.open(doc_filename, "a+") +- file:write("") +- file:close() +- view:open_doc(doc_filename) +- core.log("Created %s", doc_filename) ++ local lastChar = filename:sub(#filename) ++ if lastChar == "/" or lastChar == "\\" then ++ create_new_folder(filename) ++ else ++ create_new_file(doc_filename) ++ end + end, + suggest = function(text) + return common.path_suggest(text, item.dir_name) +@@ -884,8 +897,7 @@ command.add( + text = text, + submit = function(filename) + local dir_path = item.dir_name .. PATHSEP .. filename +- common.mkdirp(dir_path) +- core.log("Created %s", dir_path) ++ create_new_folder(dir_path) + end, + suggest = function(text) + return common.path_suggest(text, item.dir_name) diff --git a/tasks/lite-xl__lite-xl-1898/tests/test.sh b/tasks/lite-xl__lite-xl-1898/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1898/tests/verifier.py b/tasks/lite-xl__lite-xl-1898/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1898/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/lite-xl__lite-xl-1904/environment/Dockerfile b/tasks/lite-xl__lite-xl-1904/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..682b8c7315ca6b5e228e3943787f459f47273869 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 \ + && 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/lite-xl__lite-xl-1904/instruction.md b/tasks/lite-xl__lite-xl-1904/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87ea0da61fe531f7ca9baa4f4df68f3f1694576d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** check item type before creating input text + +## Description + +added a check to see if the selected item is a file or a directory. +if it is a file. we only prepend the parent directory path, and not the filename. + +this was necessary for both +`treeview:new-file` and `treeview:new-folder` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1904/solution/patch.diff b/tasks/lite-xl__lite-xl-1904/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c23b3ca2485d6f724415447bcecb9fd63a3dcaa1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..b2c7355a 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -856,7 +856,12 @@ command.add( + ["treeview:new-file"] = function(item) + local text + if not is_project_folder(item.abs_filename) then +- text = item.filename .. PATHSEP ++ if item.type == "dir" then ++ text = item.filename .. PATHSEP ++ elseif item.type == "file" then ++ local parent_dir = common.dirname(item.filename) ++ text = parent_dir and parent_dir .. PATHSEP ++ end + end + core.command_view:enter("Filename", { + text = text, +@@ -878,7 +883,12 @@ command.add( + ["treeview:new-folder"] = function(item) + local text + if not is_project_folder(item.abs_filename) then +- text = item.filename .. PATHSEP ++ if item.type == "dir" then ++ text = item.filename .. PATHSEP ++ elseif item.type == "file" then ++ local parent_dir = common.dirname(item.filename) ++ text = parent_dir and parent_dir .. PATHSEP ++ end + end + core.command_view:enter("Folder Name", { + text = text, diff --git a/tasks/lite-xl__lite-xl-1904/solution/solve.sh b/tasks/lite-xl__lite-xl-1904/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/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/lite-xl__lite-xl-1904/task.toml b/tasks/lite-xl__lite-xl-1904/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..218c4ebd4b47e2a6145a1022c780c11192c03434 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1904" +description = "check item type before creating input text" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "e8a4ed2a213cc441a36eadc914a71205eb2f8cd6" +reference = "https://github.com/lite-xl/lite-xl/pull/1904" +source_access = "auto" +built_at = "2026-11-16T16:09:56.315974+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c6a0758429b837e8b3b5500af612dc5422ad97c915a8c0f4142cbe84a93862bf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-02T07:38:06Z" +diff_format = "unified" +context_files = [ + "data/plugins/treeview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.304395+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:29ad650c11ff21d3e0ab5cd4dc603cf6ccd331d4b085a3f6f3a6345ef957bece" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1904/tests/capture.py b/tasks/lite-xl__lite-xl-1904/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/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/lite-xl__lite-xl-1904/tests/instruction.md b/tasks/lite-xl__lite-xl-1904/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87ea0da61fe531f7ca9baa4f4df68f3f1694576d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** check item type before creating input text + +## Description + +added a check to see if the selected item is a file or a directory. +if it is a file. we only prepend the parent directory path, and not the filename. + +this was necessary for both +`treeview:new-file` and `treeview:new-folder` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e8a4ed2a213c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1904/tests/oracle.patch b/tasks/lite-xl__lite-xl-1904/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c23b3ca2485d6f724415447bcecb9fd63a3dcaa1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/data/plugins/treeview.lua b/data/plugins/treeview.lua +index 9037d51a..b2c7355a 100644 +--- a/data/plugins/treeview.lua ++++ b/data/plugins/treeview.lua +@@ -856,7 +856,12 @@ command.add( + ["treeview:new-file"] = function(item) + local text + if not is_project_folder(item.abs_filename) then +- text = item.filename .. PATHSEP ++ if item.type == "dir" then ++ text = item.filename .. PATHSEP ++ elseif item.type == "file" then ++ local parent_dir = common.dirname(item.filename) ++ text = parent_dir and parent_dir .. PATHSEP ++ end + end + core.command_view:enter("Filename", { + text = text, +@@ -878,7 +883,12 @@ command.add( + ["treeview:new-folder"] = function(item) + local text + if not is_project_folder(item.abs_filename) then +- text = item.filename .. PATHSEP ++ if item.type == "dir" then ++ text = item.filename .. PATHSEP ++ elseif item.type == "file" then ++ local parent_dir = common.dirname(item.filename) ++ text = parent_dir and parent_dir .. PATHSEP ++ end + end + core.command_view:enter("Folder Name", { + text = text, diff --git a/tasks/lite-xl__lite-xl-1904/tests/test.sh b/tasks/lite-xl__lite-xl-1904/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d26631459a5557056b97dc84c867795b3717c00e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/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 e8a4ed2a213cc441a36eadc914a71205eb2f8cd6 > "$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/lite-xl__lite-xl-1904/tests/verifier.py b/tasks/lite-xl__lite-xl-1904/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1904/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/lite-xl__lite-xl-1906/environment/Dockerfile b/tasks/lite-xl__lite-xl-1906/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a2e9c0abef5898f969772406111df12190095e1e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 219dc55eaefe81a7b130831c14f8edd316bdc9d0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 219dc55eaefe81a7b130831c14f8edd316bdc9d0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 219dc55eaefe81a7b130831c14f8edd316bdc9d0 \ + && 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/lite-xl__lite-xl-1906/instruction.md b/tasks/lite-xl__lite-xl-1906/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91a2debc9522bb11c1b20b6215a50bc105fedf2f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** remove lhelper script, build configuration and dependency support + +## Description + +CI has not used lhelper in god knows how long and I'm not aware of any lhelper users outside of Franko, regardless I have kept some other references to lhelper, such as in the gitignore, to prevent any issues on existing setups. + +If there are any legit use-cases of lhelper this would be trivial to revert, if not the rest can be removed at a later date. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `219dc55eaefe`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1906/solution/patch.diff b/tasks/lite-xl__lite-xl-1906/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..895d9357a73be4b2d3aa507c587a92bb0d331677 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/solution/patch.diff @@ -0,0 +1,152 @@ +diff --git a/build.lhelper b/build.lhelper +deleted file mode 100644 +index 1fcdca3a..00000000 +--- a/build.lhelper ++++ /dev/null +@@ -1,8 +0,0 @@ +-CC="${CC:-gcc}" +-CXX="${CXX:-g++}" +-CFLAGS= +-CXXFLAGS= +-LDFLAGS= +-BUILD_TYPE=Release +- +-packages=(pcre2 freetype2 sdl2 lua) +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +index 00606944..fb593ca6 100644 +--- a/scripts/install-dependencies.sh ++++ b/scripts/install-dependencies.sh +@@ -14,20 +14,16 @@ show_help() { + echo + echo "Available options:" + echo +- echo "-l --lhelper Install tools required by LHelper and doesn't" +- echo " install external libraries." + echo " --debug Debug this script." + echo + } + + main() { +- local lhelper=false +- + for i in "$@"; do + case $i in + -s|--lhelper) +- lhelper=true +- shift ++ echo "error: support for lhelper has been deprecated" >> /dev/stderr ++ exit 1 + ;; + --debug) + set -x +@@ -45,27 +41,14 @@ main() { + fi + + if [[ "$OSTYPE" == "linux"* ]]; then +- if [[ $lhelper == true ]]; then +- sudo apt-get install -qq ninja-build +- else +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 +- fi ++ sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 + pip3 install meson + elif [[ "$OSTYPE" == "darwin"* ]]; then +- if [[ $lhelper == true ]]; then +- brew install bash md5sha1sum ninja +- else +- brew install bash ninja sdl2 +- fi ++ brew install bash ninja sdl2 + pip3 install meson dmgbuild + elif [[ "$OSTYPE" == "msys" ]]; then +- if [[ $lhelper == true ]]; then +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa} unzip +- else +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip +- fi ++ pacman --noconfirm -S \ ++ ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip + fi + } + +diff --git a/scripts/lhelper.sh b/scripts/lhelper.sh +deleted file mode 100644 +index 8d7ccded..00000000 +--- a/scripts/lhelper.sh ++++ /dev/null +@@ -1,73 +0,0 @@ +-#!/bin/bash +-set -e +- +-show_help() { +- echo +- echo "Usage: $0 " +- echo +- echo "Available options:" +- echo +- echo " --debug Debug this script." +- echo "-h --help Show this help and exit." +- echo "-p --prefix PREFIX Install directory prefix." +- echo " Default: '$HOME/.local'." +- echo +-} +- +-main() { +- local lhelper_prefix="$HOME/.local" +- +- for i in "$@"; do +- case $i in +- -h|--help) +- show_help +- exit 0 +- ;; +- -p|--prefix) +- lhelper_prefix="$2" +- echo "LHelper prefix set to: \"${lhelper_prefix}\"" +- shift +- shift +- ;; +- --debug) +- set -x +- shift +- ;; +- *) +- # unknown option +- ;; +- esac +- done +- +- if [[ -n $1 ]]; then show_help; exit 1; fi +- +- if [[ ! -f ${lhelper_prefix}/bin/lhelper ]]; then +- +- git clone https://github.com/franko/lhelper.git +- +- # FIXME: This should be set in ~/.bash_profile if not using CI +- # export PATH="${HOME}/.local/bin:${PATH}" +- mkdir -p "${lhelper_prefix}/bin" +- pushd lhelper; bash install "${lhelper_prefix}"; popd +- +- if [[ "$OSTYPE" == "darwin"* ]]; then +- CC=clang CXX=clang++ lhelper create build +- else +- lhelper create lite-xl build +- fi +- fi +- +- # Not using $(lhelper activate lite-xl) to support CI +- source "$(lhelper env-source build)" +- +- # Help MSYS2 to find the SDL2 include and lib directories to avoid errors +- # during build and linking when using lhelper. +- # Francesco: not sure why this is needed. I have never observed the problem when +- # building on window. +- # if [[ "$OSTYPE" == "msys" ]]; then +- # CFLAGS=-I${LHELPER_ENV_PREFIX}/include/SDL2 +- # LDFLAGS=-L${LHELPER_ENV_PREFIX}/lib +- # fi +-} +- +-main "$@" diff --git a/tasks/lite-xl__lite-xl-1906/solution/solve.sh b/tasks/lite-xl__lite-xl-1906/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/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/lite-xl__lite-xl-1906/task.toml b/tasks/lite-xl__lite-xl-1906/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..351e0e68c75cb0ca4a4601c3bb551a936fdd1bf1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1906" +description = "remove lhelper script, build configuration and dependency support" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "219dc55eaefe81a7b130831c14f8edd316bdc9d0" +reference = "https://github.com/lite-xl/lite-xl/pull/1906" +source_access = "auto" +built_at = "2026-11-16T16:09:56.340616+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:895ef187da79b43da6d7679749ad1eb65d1b61d842e9143194f97101895f81de" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-22T15:12:24Z" +diff_format = "unified" +context_files = [ + "build.lhelper", + "scripts/install-dependencies.sh", + "scripts/lhelper.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 110 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.304847+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d0bea3861322bd87848a0840214babd7662fb276a3b8409a507bf36ed37d2cff" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1906/tests/capture.py b/tasks/lite-xl__lite-xl-1906/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/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/lite-xl__lite-xl-1906/tests/instruction.md b/tasks/lite-xl__lite-xl-1906/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91a2debc9522bb11c1b20b6215a50bc105fedf2f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** remove lhelper script, build configuration and dependency support + +## Description + +CI has not used lhelper in god knows how long and I'm not aware of any lhelper users outside of Franko, regardless I have kept some other references to lhelper, such as in the gitignore, to prevent any issues on existing setups. + +If there are any legit use-cases of lhelper this would be trivial to revert, if not the rest can be removed at a later date. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `219dc55eaefe`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1906/tests/oracle.patch b/tasks/lite-xl__lite-xl-1906/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..895d9357a73be4b2d3aa507c587a92bb0d331677 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/tests/oracle.patch @@ -0,0 +1,152 @@ +diff --git a/build.lhelper b/build.lhelper +deleted file mode 100644 +index 1fcdca3a..00000000 +--- a/build.lhelper ++++ /dev/null +@@ -1,8 +0,0 @@ +-CC="${CC:-gcc}" +-CXX="${CXX:-g++}" +-CFLAGS= +-CXXFLAGS= +-LDFLAGS= +-BUILD_TYPE=Release +- +-packages=(pcre2 freetype2 sdl2 lua) +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +index 00606944..fb593ca6 100644 +--- a/scripts/install-dependencies.sh ++++ b/scripts/install-dependencies.sh +@@ -14,20 +14,16 @@ show_help() { + echo + echo "Available options:" + echo +- echo "-l --lhelper Install tools required by LHelper and doesn't" +- echo " install external libraries." + echo " --debug Debug this script." + echo + } + + main() { +- local lhelper=false +- + for i in "$@"; do + case $i in + -s|--lhelper) +- lhelper=true +- shift ++ echo "error: support for lhelper has been deprecated" >> /dev/stderr ++ exit 1 + ;; + --debug) + set -x +@@ -45,27 +41,14 @@ main() { + fi + + if [[ "$OSTYPE" == "linux"* ]]; then +- if [[ $lhelper == true ]]; then +- sudo apt-get install -qq ninja-build +- else +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 +- fi ++ sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 + pip3 install meson + elif [[ "$OSTYPE" == "darwin"* ]]; then +- if [[ $lhelper == true ]]; then +- brew install bash md5sha1sum ninja +- else +- brew install bash ninja sdl2 +- fi ++ brew install bash ninja sdl2 + pip3 install meson dmgbuild + elif [[ "$OSTYPE" == "msys" ]]; then +- if [[ $lhelper == true ]]; then +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa} unzip +- else +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip +- fi ++ pacman --noconfirm -S \ ++ ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip + fi + } + +diff --git a/scripts/lhelper.sh b/scripts/lhelper.sh +deleted file mode 100644 +index 8d7ccded..00000000 +--- a/scripts/lhelper.sh ++++ /dev/null +@@ -1,73 +0,0 @@ +-#!/bin/bash +-set -e +- +-show_help() { +- echo +- echo "Usage: $0 " +- echo +- echo "Available options:" +- echo +- echo " --debug Debug this script." +- echo "-h --help Show this help and exit." +- echo "-p --prefix PREFIX Install directory prefix." +- echo " Default: '$HOME/.local'." +- echo +-} +- +-main() { +- local lhelper_prefix="$HOME/.local" +- +- for i in "$@"; do +- case $i in +- -h|--help) +- show_help +- exit 0 +- ;; +- -p|--prefix) +- lhelper_prefix="$2" +- echo "LHelper prefix set to: \"${lhelper_prefix}\"" +- shift +- shift +- ;; +- --debug) +- set -x +- shift +- ;; +- *) +- # unknown option +- ;; +- esac +- done +- +- if [[ -n $1 ]]; then show_help; exit 1; fi +- +- if [[ ! -f ${lhelper_prefix}/bin/lhelper ]]; then +- +- git clone https://github.com/franko/lhelper.git +- +- # FIXME: This should be set in ~/.bash_profile if not using CI +- # export PATH="${HOME}/.local/bin:${PATH}" +- mkdir -p "${lhelper_prefix}/bin" +- pushd lhelper; bash install "${lhelper_prefix}"; popd +- +- if [[ "$OSTYPE" == "darwin"* ]]; then +- CC=clang CXX=clang++ lhelper create build +- else +- lhelper create lite-xl build +- fi +- fi +- +- # Not using $(lhelper activate lite-xl) to support CI +- source "$(lhelper env-source build)" +- +- # Help MSYS2 to find the SDL2 include and lib directories to avoid errors +- # during build and linking when using lhelper. +- # Francesco: not sure why this is needed. I have never observed the problem when +- # building on window. +- # if [[ "$OSTYPE" == "msys" ]]; then +- # CFLAGS=-I${LHELPER_ENV_PREFIX}/include/SDL2 +- # LDFLAGS=-L${LHELPER_ENV_PREFIX}/lib +- # fi +-} +- +-main "$@" diff --git a/tasks/lite-xl__lite-xl-1906/tests/test.sh b/tasks/lite-xl__lite-xl-1906/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d99c64e0147e06e12530bad0e4ca4ab90fe432fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/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 219dc55eaefe81a7b130831c14f8edd316bdc9d0 > "$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/lite-xl__lite-xl-1906/tests/verifier.py b/tasks/lite-xl__lite-xl-1906/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1906/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/lite-xl__lite-xl-1919/environment/Dockerfile b/tasks/lite-xl__lite-xl-1919/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..745e0d0886e56a60c435aaf80e951a9895d5666f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1659f63dfc6fec7893673e7e95bbcd844ec0bda4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1659f63dfc6fec7893673e7e95bbcd844ec0bda4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1659f63dfc6fec7893673e7e95bbcd844ec0bda4 \ + && 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/lite-xl__lite-xl-1919/instruction.md b/tasks/lite-xl__lite-xl-1919/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f4f545f574cc41023e9da295c2c256ec6b79a1f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** renderer: pass errors via SDL_SetError + +## Description + +This is a thing that everyone wants but it keeps delayed for no good reason. +This PR adds error messages by using SDL_GetError(). There are a few ways that we can pass error codes around the renderer: + +1. Use some error code. Unfortunately, SDL doesn't use it, and FreeType error codes are limited (can't open file? _why_?). There is also the question of which set of error codes to return - FreeType, our own, or what? Or we can do it like Windows, by indicating whether the error is generated by SDL or FreeType with the high byte? Wouldn't that still clash with FreeType? +2. Return some kind of error type that be casted to a string, directly or indirectly. This still raises questions regarding if that string should be statically allocated, or comes with a complementary free function, etc. +3. Just use SDL_SetError() and SDL_GetError(). I'm pretty sure this way of error handling is shunned by a lot of people, but face it - this is just the most flexible way when you have error messages from various sources, and in various formats. SDL_GetError() also stores the message in thread local storage, so no problems with multithreading either. + +Obviously, this PR uses approach 3. Finally we can get stuff like this: +![image](https://github.com/user-attachments/assets/f8306898-5afb-4697-8807-53026db12d04) + +Obviously that message is kinda long, but this beats not having a proper error message AT ALL. + +As a side note, this also implicitly implies that we should adopt a 0 for success and negative for failure convention, as used by SDL. I don't think this is much problem, since we partially use 0 for success already in various places in the codebase. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1659f63dfc6f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1919/solution/patch.diff b/tasks/lite-xl__lite-xl-1919/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f1f84dd85a8661d070b61e1e6c8700b75a678822 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/solution/patch.diff @@ -0,0 +1,132 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index 27d6f47f..d47704b5 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -97,7 +97,7 @@ static int f_font_load(lua_State *L) { + RenFont** font = lua_newuserdata(L, sizeof(RenFont*)); + *font = ren_font_load(filename, size, antialiasing, hinting, style); + if (!*font) +- return luaL_error(L, "failed to load font"); ++ return luaL_error(L, "failed to load font: %s", SDL_GetError()); + luaL_setmetatable(L, API_TYPE_FONT); + return 1; + } +@@ -143,7 +143,7 @@ static int f_font_copy(lua_State *L) { + RenFont** font = lua_newuserdata(L, sizeof(RenFont*)); + *font = ren_font_copy(fonts[i], size, antialiasing, hinting, style); + if (!*font) +- return luaL_error(L, "failed to copy font"); ++ return luaL_error(L, "failed to copy font: %s", SDL_GetError()); + luaL_setmetatable(L, API_TYPE_FONT); + if (table) + lua_rawseti(L, -2, i+1); +diff --git a/src/main.c b/src/main.c +index 68239541..154a911e 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -108,7 +108,7 @@ int main(int argc, char **argv) { + #endif + + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { +- fprintf(stderr, "Error initializing sdl: %s", SDL_GetError()); ++ fprintf(stderr, "Error initializing SDL: %s\n", SDL_GetError()); + exit(1); + } + SDL_EnableScreenSaver(); +@@ -145,8 +145,8 @@ int main(int argc, char **argv) { + + SDL_SetHint(SDL_HINT_RENDER_DRIVER, "software"); + +- if ( ren_init() ) { +- fprintf(stderr, "internal font error when starting the application\n"); ++ if (ren_init() != 0) { ++ fprintf(stderr, "Error initializing renderer: %s\n", SDL_GetError()); + } + + int has_restarted = 0; +diff --git a/src/renderer.c b/src/renderer.c +index 68687888..16b0a0c8 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -33,6 +33,16 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + return ptr; + } + ++// getting freetype error messages (https://freetype.org/freetype2/docs/reference/ft2-error_enumerations.html) ++static const char *const get_ft_error(FT_Error err) { ++#undef FTERRORS_H_ ++#define FT_ERROR_START_LIST switch (FT_ERROR_BASE(err)) { ++#define FT_ERRORDEF(e, v, s) case v: return s; ++#define FT_ERROR_END_LIST } ++#include FT_ERRORS_H ++ return "unknown error"; ++} ++ + /************************* Fonts *************************/ + + // approximate number of glyphs per atlas surface +@@ -444,12 +454,15 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + } + + RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { ++ FT_Error err = FT_Err_Ok; + SDL_RWops *file = NULL; RenFont *font = NULL; + FT_Face face = NULL; FT_Stream stream = NULL; + +- file = SDL_RWFromFile(path, "rb"); +- if (!file) return NULL; ++ SDL_ClearError(); + ++ file = SDL_RWFromFile(path, "rb"); ++ if (!file) return NULL; // error set by SDL_RWFromFile ++ + int len = strlen(path); + font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); + strcpy(font->path, path); +@@ -470,15 +483,16 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + stream->pos = 0; + stream->size = (unsigned long) SDL_RWsize(file); + +- if (FT_Open_Face(library, &(FT_Open_Args) { .flags = FT_OPEN_STREAM, .stream = stream }, 0, &face) != 0) ++ if ((err = FT_Open_Face(library, &(FT_Open_Args) { .flags = FT_OPEN_STREAM, .stream = stream }, 0, &face)) != 0) + goto failure; +- if (font_set_face_metrics(font, face) != 0) ++ if ((err = font_set_face_metrics(font, face)) != 0) + goto failure; + return font; + + stream_failure: + if (file) SDL_RWclose(file); + failure: ++ if (err != FT_Err_Ok) SDL_SetError("%s", get_ft_error(err)); + if (face) FT_Done_Face(face); + if (font) free(font); + return NULL; +@@ -489,7 +503,7 @@ RenFont* ren_font_copy(RenFont* font, float size, ERenFontAntialiasing antialias + hinting = hinting == -1 ? font->hinting : hinting; + style = style == -1 ? font->style : style; + +- return ren_font_load(font->path, size, antialiasing, hinting, style); ++ return ren_font_load(font->path, size, antialiasing, hinting, style); // SDL_SetError() will be called appropriately + } + + const char* ren_font_get_path(RenFont *font) { +@@ -744,13 +758,16 @@ static void ren_remove_window(RenWindow *window_renderer) { + } + + int ren_init(void) { +- int err; ++ FT_Error err; ++ SDL_ClearError(); + + draw_rect_surface = SDL_CreateRGBSurface(0, 1, 1, 32, + 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); ++ if (!draw_rect_surface) ++ return -1; // error set by SDL_CreateRGBSurface + + if ((err = FT_Init_FreeType(&library)) != 0) +- return err; ++ return SDL_SetError("%s", get_ft_error(err)); + + return 0; + } diff --git a/tasks/lite-xl__lite-xl-1919/solution/solve.sh b/tasks/lite-xl__lite-xl-1919/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/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/lite-xl__lite-xl-1919/task.toml b/tasks/lite-xl__lite-xl-1919/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..308ae75fb118315d7e1ea3f3d1c4e5f76578c617 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1919" +description = "renderer: pass errors via SDL_SetError" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "1659f63dfc6fec7893673e7e95bbcd844ec0bda4" +reference = "https://github.com/lite-xl/lite-xl/pull/1919" +source_access = "auto" +built_at = "2026-11-16T16:09:56.304657+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9bd7514dee97fdeca3390d1591b0bcbc3e045afd8483e8b77cfd9b36ec7b4e71" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T14:51:16Z" +diff_format = "unified" +context_files = [ + "src/api/renderer.c", + "src/main.c", + "src/renderer.c", +] +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:01.305331+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ba7d08f5e7f2b86e92e2594d973869ec84c6697c62ad828cd1bfddf9ac78eb38" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1919/tests/capture.py b/tasks/lite-xl__lite-xl-1919/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/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/lite-xl__lite-xl-1919/tests/instruction.md b/tasks/lite-xl__lite-xl-1919/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f4f545f574cc41023e9da295c2c256ec6b79a1f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** renderer: pass errors via SDL_SetError + +## Description + +This is a thing that everyone wants but it keeps delayed for no good reason. +This PR adds error messages by using SDL_GetError(). There are a few ways that we can pass error codes around the renderer: + +1. Use some error code. Unfortunately, SDL doesn't use it, and FreeType error codes are limited (can't open file? _why_?). There is also the question of which set of error codes to return - FreeType, our own, or what? Or we can do it like Windows, by indicating whether the error is generated by SDL or FreeType with the high byte? Wouldn't that still clash with FreeType? +2. Return some kind of error type that be casted to a string, directly or indirectly. This still raises questions regarding if that string should be statically allocated, or comes with a complementary free function, etc. +3. Just use SDL_SetError() and SDL_GetError(). I'm pretty sure this way of error handling is shunned by a lot of people, but face it - this is just the most flexible way when you have error messages from various sources, and in various formats. SDL_GetError() also stores the message in thread local storage, so no problems with multithreading either. + +Obviously, this PR uses approach 3. Finally we can get stuff like this: +![image](https://github.com/user-attachments/assets/f8306898-5afb-4697-8807-53026db12d04) + +Obviously that message is kinda long, but this beats not having a proper error message AT ALL. + +As a side note, this also implicitly implies that we should adopt a 0 for success and negative for failure convention, as used by SDL. I don't think this is much problem, since we partially use 0 for success already in various places in the codebase. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1659f63dfc6f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1919/tests/oracle.patch b/tasks/lite-xl__lite-xl-1919/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1f84dd85a8661d070b61e1e6c8700b75a678822 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/tests/oracle.patch @@ -0,0 +1,132 @@ +diff --git a/src/api/renderer.c b/src/api/renderer.c +index 27d6f47f..d47704b5 100644 +--- a/src/api/renderer.c ++++ b/src/api/renderer.c +@@ -97,7 +97,7 @@ static int f_font_load(lua_State *L) { + RenFont** font = lua_newuserdata(L, sizeof(RenFont*)); + *font = ren_font_load(filename, size, antialiasing, hinting, style); + if (!*font) +- return luaL_error(L, "failed to load font"); ++ return luaL_error(L, "failed to load font: %s", SDL_GetError()); + luaL_setmetatable(L, API_TYPE_FONT); + return 1; + } +@@ -143,7 +143,7 @@ static int f_font_copy(lua_State *L) { + RenFont** font = lua_newuserdata(L, sizeof(RenFont*)); + *font = ren_font_copy(fonts[i], size, antialiasing, hinting, style); + if (!*font) +- return luaL_error(L, "failed to copy font"); ++ return luaL_error(L, "failed to copy font: %s", SDL_GetError()); + luaL_setmetatable(L, API_TYPE_FONT); + if (table) + lua_rawseti(L, -2, i+1); +diff --git a/src/main.c b/src/main.c +index 68239541..154a911e 100644 +--- a/src/main.c ++++ b/src/main.c +@@ -108,7 +108,7 @@ int main(int argc, char **argv) { + #endif + + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { +- fprintf(stderr, "Error initializing sdl: %s", SDL_GetError()); ++ fprintf(stderr, "Error initializing SDL: %s\n", SDL_GetError()); + exit(1); + } + SDL_EnableScreenSaver(); +@@ -145,8 +145,8 @@ int main(int argc, char **argv) { + + SDL_SetHint(SDL_HINT_RENDER_DRIVER, "software"); + +- if ( ren_init() ) { +- fprintf(stderr, "internal font error when starting the application\n"); ++ if (ren_init() != 0) { ++ fprintf(stderr, "Error initializing renderer: %s\n", SDL_GetError()); + } + + int has_restarted = 0; +diff --git a/src/renderer.c b/src/renderer.c +index 68687888..16b0a0c8 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -33,6 +33,16 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + return ptr; + } + ++// getting freetype error messages (https://freetype.org/freetype2/docs/reference/ft2-error_enumerations.html) ++static const char *const get_ft_error(FT_Error err) { ++#undef FTERRORS_H_ ++#define FT_ERROR_START_LIST switch (FT_ERROR_BASE(err)) { ++#define FT_ERRORDEF(e, v, s) case v: return s; ++#define FT_ERROR_END_LIST } ++#include FT_ERRORS_H ++ return "unknown error"; ++} ++ + /************************* Fonts *************************/ + + // approximate number of glyphs per atlas surface +@@ -444,12 +454,15 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + } + + RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antialiasing, ERenFontHinting hinting, unsigned char style) { ++ FT_Error err = FT_Err_Ok; + SDL_RWops *file = NULL; RenFont *font = NULL; + FT_Face face = NULL; FT_Stream stream = NULL; + +- file = SDL_RWFromFile(path, "rb"); +- if (!file) return NULL; ++ SDL_ClearError(); + ++ file = SDL_RWFromFile(path, "rb"); ++ if (!file) return NULL; // error set by SDL_RWFromFile ++ + int len = strlen(path); + font = check_alloc(calloc(1, sizeof(RenFont) + len + 1)); + strcpy(font->path, path); +@@ -470,15 +483,16 @@ RenFont* ren_font_load(const char* path, float size, ERenFontAntialiasing antial + stream->pos = 0; + stream->size = (unsigned long) SDL_RWsize(file); + +- if (FT_Open_Face(library, &(FT_Open_Args) { .flags = FT_OPEN_STREAM, .stream = stream }, 0, &face) != 0) ++ if ((err = FT_Open_Face(library, &(FT_Open_Args) { .flags = FT_OPEN_STREAM, .stream = stream }, 0, &face)) != 0) + goto failure; +- if (font_set_face_metrics(font, face) != 0) ++ if ((err = font_set_face_metrics(font, face)) != 0) + goto failure; + return font; + + stream_failure: + if (file) SDL_RWclose(file); + failure: ++ if (err != FT_Err_Ok) SDL_SetError("%s", get_ft_error(err)); + if (face) FT_Done_Face(face); + if (font) free(font); + return NULL; +@@ -489,7 +503,7 @@ RenFont* ren_font_copy(RenFont* font, float size, ERenFontAntialiasing antialias + hinting = hinting == -1 ? font->hinting : hinting; + style = style == -1 ? font->style : style; + +- return ren_font_load(font->path, size, antialiasing, hinting, style); ++ return ren_font_load(font->path, size, antialiasing, hinting, style); // SDL_SetError() will be called appropriately + } + + const char* ren_font_get_path(RenFont *font) { +@@ -744,13 +758,16 @@ static void ren_remove_window(RenWindow *window_renderer) { + } + + int ren_init(void) { +- int err; ++ FT_Error err; ++ SDL_ClearError(); + + draw_rect_surface = SDL_CreateRGBSurface(0, 1, 1, 32, + 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); ++ if (!draw_rect_surface) ++ return -1; // error set by SDL_CreateRGBSurface + + if ((err = FT_Init_FreeType(&library)) != 0) +- return err; ++ return SDL_SetError("%s", get_ft_error(err)); + + return 0; + } diff --git a/tasks/lite-xl__lite-xl-1919/tests/test.sh b/tasks/lite-xl__lite-xl-1919/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9d417d7bf27a9af29a17fc8ba86f91a7f7eb55e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/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 1659f63dfc6fec7893673e7e95bbcd844ec0bda4 > "$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/lite-xl__lite-xl-1919/tests/verifier.py b/tasks/lite-xl__lite-xl-1919/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1919/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/lite-xl__lite-xl-1921/environment/Dockerfile b/tasks/lite-xl__lite-xl-1921/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9b5e9fe0a51e81345b600b10d48674638157e5a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efa257ddbdd9ade1cad588918c62f091493ccb1b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && 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/lite-xl__lite-xl-1921/instruction.md b/tasks/lite-xl__lite-xl-1921/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7256f048f66a0004e02a9a14edbd73d9ff5453f7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Format renderer font scale code to be actually readable + +## Description + +previously this code has misleading indention, resulting in FT_IS_SCALABLE being called twice + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1921/solution/patch.diff b/tasks/lite-xl__lite-xl-1921/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3bb0ba6904e0e260d913de2358fc60e71322cf9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/renderer.c b/src/renderer.c +index abd9a35c..38ed486a 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -401,10 +401,8 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + + font->face = face; + if(FT_IS_SCALABLE(face)) { +- font->height = (short)((face->height / (float)face->units_per_EM) * font->size); +- font->baseline = (short)((face->ascender / (float)face->units_per_EM) * font->size); +- +- if(FT_IS_SCALABLE(face)) ++ font->height = (short)((face->height / (float)face->units_per_EM) * font->size); ++ font->baseline = (short)((face->ascender / (float)face->units_per_EM) * font->size); + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); + } else { + font->height = (short) font->face->size->metrics.height / 64.0f; diff --git a/tasks/lite-xl__lite-xl-1921/solution/solve.sh b/tasks/lite-xl__lite-xl-1921/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/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/lite-xl__lite-xl-1921/task.toml b/tasks/lite-xl__lite-xl-1921/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eb298d8a243ae1ada6d2a46866338d19b913991f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1921" +description = "Format renderer font scale code to be actually readable" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "efa257ddbdd9ade1cad588918c62f091493ccb1b" +reference = "https://github.com/lite-xl/lite-xl/pull/1921" +source_access = "auto" +built_at = "2026-11-16T16:09:56.329672+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9ab85899154cae0edeff88c2afad73eed75461c4f925cee089a42b9e95ad0417" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-31T08:00:36Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.305789+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e471019fc62f655a2609323e51e42ae2bc2456a7a8e3dcf0a0d756b495639e90" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1921/tests/capture.py b/tasks/lite-xl__lite-xl-1921/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/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/lite-xl__lite-xl-1921/tests/instruction.md b/tasks/lite-xl__lite-xl-1921/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7256f048f66a0004e02a9a14edbd73d9ff5453f7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Format renderer font scale code to be actually readable + +## Description + +previously this code has misleading indention, resulting in FT_IS_SCALABLE being called twice + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1921/tests/oracle.patch b/tasks/lite-xl__lite-xl-1921/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a3bb0ba6904e0e260d913de2358fc60e71322cf9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/src/renderer.c b/src/renderer.c +index abd9a35c..38ed486a 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -401,10 +401,8 @@ static int font_set_face_metrics(RenFont *font, FT_Face face) { + + font->face = face; + if(FT_IS_SCALABLE(face)) { +- font->height = (short)((face->height / (float)face->units_per_EM) * font->size); +- font->baseline = (short)((face->ascender / (float)face->units_per_EM) * font->size); +- +- if(FT_IS_SCALABLE(face)) ++ font->height = (short)((face->height / (float)face->units_per_EM) * font->size); ++ font->baseline = (short)((face->ascender / (float)face->units_per_EM) * font->size); + font->underline_thickness = (unsigned short)((face->underline_thickness / (float)face->units_per_EM) * font->size); + } else { + font->height = (short) font->face->size->metrics.height / 64.0f; diff --git a/tasks/lite-xl__lite-xl-1921/tests/test.sh b/tasks/lite-xl__lite-xl-1921/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a86f795051b02c6b6d05fc262010882539f3b57f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/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 efa257ddbdd9ade1cad588918c62f091493ccb1b > "$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/lite-xl__lite-xl-1921/tests/verifier.py b/tasks/lite-xl__lite-xl-1921/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1921/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/lite-xl__lite-xl-1922/environment/Dockerfile b/tasks/lite-xl__lite-xl-1922/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9b5e9fe0a51e81345b600b10d48674638157e5a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efa257ddbdd9ade1cad588918c62f091493ccb1b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efa257ddbdd9ade1cad588918c62f091493ccb1b \ + && 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/lite-xl__lite-xl-1922/instruction.md b/tasks/lite-xl__lite-xl-1922/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a71405e9e4cbe1b5dce54dfbb4034836d0f9a0e3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/instruction.md @@ -0,0 +1,80 @@ +# Issue + +**Title:** build(deps): bump softprops/action-gh-release from 1 to 2 in the github-actions group + +## Description + +Bumps the github-actions group with 1 update: [softprops/action-gh-release](https://github.com/softprops/action-gh-release). + +Updates `softprops/action-gh-release` from 1 to 2 +
+Release notes +

Sourced from softprops/action-gh-release's releases.

+
+

v2.0.0

+
    +
  • update actions.yml declaration to node20 to address warnings
  • +
+
+
+
+Changelog +

Sourced from softprops/action-gh-release's changelog.

+
+

0.1.12

+
    +
  • fix bug leading to empty strings subsituted for inputs users don't provide breaking api calls #144
  • +
+
+
+
+Commits +
    +
  • c062e08 release 2.0.8
  • +
  • 380635c chore(deps): bump @​actions/github from 5.1.1 to 6.0.0 (#470)
  • +
  • 20adb42 refactor: write jest config in ts (#485)
  • +
  • f808f15 chore(deps): bump glob from 10.4.2 to 11.0.0 (#477)
  • +
  • 6145241 chore(deps): bump @​octokit/plugin-throttling from 9.3.0 to 9.3.1 (#484)
  • +
  • 4ac522d chore(deps): bump @​types/node from 20.14.9 to 20.14.11 (#483)
  • +
  • 25849b1 chore(deps): bump prettier from 2.8.0 to 3.3.3 (#480)
  • +
  • 6206056 chore: update dependabot commit msg
  • +
  • 39aadf1 chore: run frizbee actions .github/workflows/
  • +
  • 6f3ab65 chore: update dist file
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=softprops/action-gh-release&package-manager=github_actions&previous-version=1&new-version=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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1922/solution/patch.diff b/tasks/lite-xl__lite-xl-1922/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..50a74c4535be57ba272ac1f7a3b78686c3cfefec --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index dcf97f0f..154676ca 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -263,7 +263,7 @@ jobs: + pattern: lite-xl-*-release + path: . + - name: Versioned Release +- uses: softprops/action-gh-release@v1 ++ uses: softprops/action-gh-release@v2 + if: ${{ needs.version.outputs.release }} + with: + tag_name: ${{ needs.version.outputs.release }} +@@ -285,7 +285,7 @@ jobs: + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Continuous Release +- uses: softprops/action-gh-release@v1 ++ uses: softprops/action-gh-release@v2 + if: github.ref == 'refs/heads/master' + with: + name: Lite XL Continuous Release diff --git a/tasks/lite-xl__lite-xl-1922/solution/solve.sh b/tasks/lite-xl__lite-xl-1922/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/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/lite-xl__lite-xl-1922/task.toml b/tasks/lite-xl__lite-xl-1922/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1517df6a2f86c314b7ecedc684b9c2862048de02 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1922" +description = "build(deps): bump softprops/action-gh-release from 1 to 2 in the github-actions group" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "efa257ddbdd9ade1cad588918c62f091493ccb1b" +reference = "https://github.com/lite-xl/lite-xl/pull/1922" +source_access = "auto" +built_at = "2026-11-16T16:09:56.331405+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cff5ba9977eb9a8b67bec4faf4f3d2e0be44636d637b1de7011c53cd59a1fa2e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-10-31T07:59:49Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.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:01.306232+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e471019fc62f655a2609323e51e42ae2bc2456a7a8e3dcf0a0d756b495639e90" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1922/tests/capture.py b/tasks/lite-xl__lite-xl-1922/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/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/lite-xl__lite-xl-1922/tests/instruction.md b/tasks/lite-xl__lite-xl-1922/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a71405e9e4cbe1b5dce54dfbb4034836d0f9a0e3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/tests/instruction.md @@ -0,0 +1,80 @@ +# Issue + +**Title:** build(deps): bump softprops/action-gh-release from 1 to 2 in the github-actions group + +## Description + +Bumps the github-actions group with 1 update: [softprops/action-gh-release](https://github.com/softprops/action-gh-release). + +Updates `softprops/action-gh-release` from 1 to 2 +
+Release notes +

Sourced from softprops/action-gh-release's releases.

+
+

v2.0.0

+
    +
  • update actions.yml declaration to node20 to address warnings
  • +
+
+
+
+Changelog +

Sourced from softprops/action-gh-release's changelog.

+
+

0.1.12

+
    +
  • fix bug leading to empty strings subsituted for inputs users don't provide breaking api calls #144
  • +
+
+
+
+Commits +
    +
  • c062e08 release 2.0.8
  • +
  • 380635c chore(deps): bump @​actions/github from 5.1.1 to 6.0.0 (#470)
  • +
  • 20adb42 refactor: write jest config in ts (#485)
  • +
  • f808f15 chore(deps): bump glob from 10.4.2 to 11.0.0 (#477)
  • +
  • 6145241 chore(deps): bump @​octokit/plugin-throttling from 9.3.0 to 9.3.1 (#484)
  • +
  • 4ac522d chore(deps): bump @​types/node from 20.14.9 to 20.14.11 (#483)
  • +
  • 25849b1 chore(deps): bump prettier from 2.8.0 to 3.3.3 (#480)
  • +
  • 6206056 chore: update dependabot commit msg
  • +
  • 39aadf1 chore: run frizbee actions .github/workflows/
  • +
  • 6f3ab65 chore: update dist file
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=softprops/action-gh-release&package-manager=github_actions&previous-version=1&new-version=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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efa257ddbdd9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1922/tests/oracle.patch b/tasks/lite-xl__lite-xl-1922/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..50a74c4535be57ba272ac1f7a3b78686c3cfefec --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index dcf97f0f..154676ca 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -263,7 +263,7 @@ jobs: + pattern: lite-xl-*-release + path: . + - name: Versioned Release +- uses: softprops/action-gh-release@v1 ++ uses: softprops/action-gh-release@v2 + if: ${{ needs.version.outputs.release }} + with: + tag_name: ${{ needs.version.outputs.release }} +@@ -285,7 +285,7 @@ jobs: + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Continuous Release +- uses: softprops/action-gh-release@v1 ++ uses: softprops/action-gh-release@v2 + if: github.ref == 'refs/heads/master' + with: + name: Lite XL Continuous Release diff --git a/tasks/lite-xl__lite-xl-1922/tests/test.sh b/tasks/lite-xl__lite-xl-1922/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a86f795051b02c6b6d05fc262010882539f3b57f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/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 efa257ddbdd9ade1cad588918c62f091493ccb1b > "$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/lite-xl__lite-xl-1922/tests/verifier.py b/tasks/lite-xl__lite-xl-1922/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1922/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/lite-xl__lite-xl-1923/environment/Dockerfile b/tasks/lite-xl__lite-xl-1923/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4eaff8e957ff6f01c13134e27ca31b64f584f20b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3fe64609e70c98a6606968312d34827dc32f2ad4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3fe64609e70c98a6606968312d34827dc32f2ad4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3fe64609e70c98a6606968312d34827dc32f2ad4 \ + && 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/lite-xl__lite-xl-1923/instruction.md b/tasks/lite-xl__lite-xl-1923/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b94592991a2334a62bc546b436a3c485999f70b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** generate metainfo release tag using git tags + +## Description + +- rename appdata to metainfo ([appdata is the legacy name](https://www.freedesktop.org/software/appstream/docs/sect-Metadata-Application.html)) +- fill optional releases section with info from git, if available + - this skips the versions `1.01` to `1.09` because they break the versioning scheme, I could implement a workaround however these versions are old and can probably be left out + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fe64609e70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1923/solution/patch.diff b/tasks/lite-xl__lite-xl-1923/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..de06b809bc11d7c2d39a3a21d5abad63d755b9ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/solution/patch.diff @@ -0,0 +1,88 @@ +diff --git a/meson.build b/meson.build +index 7f2dfb9f..883e4b78 100644 +--- a/meson.build ++++ b/meson.build +@@ -210,21 +210,64 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + install_dir : 'Contents' + ) + else +- message() + lite_bindir = 'bin' + lite_docdir = get_option('datadir') / 'doc' / 'lite-xl' + lite_datadir = get_option('datadir') / 'lite-xl' + lpm_userdir = 'lite-xl' + lpm_install_dir = get_option('datadir') + if host_machine.system() == 'linux' ++ git_command = find_program('git', required : false) ++ ++ if git_command.found() ++ git_tags = run_command( ++ [git_command, 'tag', '-l', '--sort=-version:refname', '--format=%(refname:strip=2) %(creatordate:short)'], ++ check : false ++ ).stdout().split('\n') ++ ++ releases = [] ++ ++ foreach tag : git_tags ++ taga = tag.split(' ') ++ if taga.length() != 2 ++ continue ++ endif ++ ++ ref = taga[0] ++ date = taga[1] ++ if not ref.startswith('v') or ref.contains('-') ++ continue ++ endif ++ ++ if ref.startswith('v1.0') ++ # releases 1.01 to 1.09 used an invalid versioning scheme so we ignore them ++ continue ++ endif ++ ++ releases += ''.format(ref, date) ++ endforeach ++ ++ releases_tag = '' ++ if releases.length() > 0 ++ releases_tag = '\n@0@\n'.format('\n'.join(releases)) ++ endif ++ ++ conf_data.set('METAINFO_RELEASES', releases_tag) ++ else ++ conf_data.set('METAINFO_RELEASES', '') ++ endif ++ + install_data('resources' / 'icons' / 'lite-xl.svg', + install_dir : get_option('datadir') / 'icons' / 'hicolor' / 'scalable' / 'apps' + ) + install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.desktop', + install_dir : get_option('datadir') / 'applications' + ) +- install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.appdata.xml', +- install_dir : get_option('datadir') / 'metainfo' ++ configure_file( ++ input : 'resources' / 'linux' / 'com.lite_xl.LiteXL.metainfo.xml.in', ++ output : 'com.lite_xl.LiteXL.metainfo.xml', ++ configuration : conf_data, ++ install : true, ++ install_dir : 'share/metainfo' + ) + endif + endif +diff --git a/resources/linux/com.lite_xl.LiteXL.appdata.xml b/resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +similarity index 91% +rename from resources/linux/com.lite_xl.LiteXL.appdata.xml +rename to resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +index 6b8f1350..2550d95f 100644 +--- a/resources/linux/com.lite_xl.LiteXL.appdata.xml ++++ b/resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +@@ -28,7 +28,5 @@ + lite-xl + + +- +- +- ++ @METAINFO_RELEASES@ + diff --git a/tasks/lite-xl__lite-xl-1923/solution/solve.sh b/tasks/lite-xl__lite-xl-1923/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/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/lite-xl__lite-xl-1923/task.toml b/tasks/lite-xl__lite-xl-1923/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..919e08b63e161d8b8ab666b4996ec1b6102d3cde --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1923" +description = "generate metainfo release tag using git tags" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "3fe64609e70c98a6606968312d34827dc32f2ad4" +reference = "https://github.com/lite-xl/lite-xl/pull/1923" +source_access = "auto" +built_at = "2026-11-16T16:09:56.321385+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:87f8232b0b53b73343803eb35dec2b4d4372be369626abe4ed69442c088f6eb9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-29T07:37:43Z" +diff_format = "unified" +context_files = [ + "meson.build", + "resources/linux/com.lite_xl.LiteXL.metainfo.xml.in", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 53 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.306686+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6e54b49771a5975ee0238c2ffb7f850a57377b4eeca2efd37f8000032637c5ce" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1923/tests/capture.py b/tasks/lite-xl__lite-xl-1923/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/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/lite-xl__lite-xl-1923/tests/instruction.md b/tasks/lite-xl__lite-xl-1923/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b94592991a2334a62bc546b436a3c485999f70b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** generate metainfo release tag using git tags + +## Description + +- rename appdata to metainfo ([appdata is the legacy name](https://www.freedesktop.org/software/appstream/docs/sect-Metadata-Application.html)) +- fill optional releases section with info from git, if available + - this skips the versions `1.01` to `1.09` because they break the versioning scheme, I could implement a workaround however these versions are old and can probably be left out + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fe64609e70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1923/tests/oracle.patch b/tasks/lite-xl__lite-xl-1923/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..de06b809bc11d7c2d39a3a21d5abad63d755b9ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/tests/oracle.patch @@ -0,0 +1,88 @@ +diff --git a/meson.build b/meson.build +index 7f2dfb9f..883e4b78 100644 +--- a/meson.build ++++ b/meson.build +@@ -210,21 +210,64 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + install_dir : 'Contents' + ) + else +- message() + lite_bindir = 'bin' + lite_docdir = get_option('datadir') / 'doc' / 'lite-xl' + lite_datadir = get_option('datadir') / 'lite-xl' + lpm_userdir = 'lite-xl' + lpm_install_dir = get_option('datadir') + if host_machine.system() == 'linux' ++ git_command = find_program('git', required : false) ++ ++ if git_command.found() ++ git_tags = run_command( ++ [git_command, 'tag', '-l', '--sort=-version:refname', '--format=%(refname:strip=2) %(creatordate:short)'], ++ check : false ++ ).stdout().split('\n') ++ ++ releases = [] ++ ++ foreach tag : git_tags ++ taga = tag.split(' ') ++ if taga.length() != 2 ++ continue ++ endif ++ ++ ref = taga[0] ++ date = taga[1] ++ if not ref.startswith('v') or ref.contains('-') ++ continue ++ endif ++ ++ if ref.startswith('v1.0') ++ # releases 1.01 to 1.09 used an invalid versioning scheme so we ignore them ++ continue ++ endif ++ ++ releases += ''.format(ref, date) ++ endforeach ++ ++ releases_tag = '' ++ if releases.length() > 0 ++ releases_tag = '\n@0@\n'.format('\n'.join(releases)) ++ endif ++ ++ conf_data.set('METAINFO_RELEASES', releases_tag) ++ else ++ conf_data.set('METAINFO_RELEASES', '') ++ endif ++ + install_data('resources' / 'icons' / 'lite-xl.svg', + install_dir : get_option('datadir') / 'icons' / 'hicolor' / 'scalable' / 'apps' + ) + install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.desktop', + install_dir : get_option('datadir') / 'applications' + ) +- install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.appdata.xml', +- install_dir : get_option('datadir') / 'metainfo' ++ configure_file( ++ input : 'resources' / 'linux' / 'com.lite_xl.LiteXL.metainfo.xml.in', ++ output : 'com.lite_xl.LiteXL.metainfo.xml', ++ configuration : conf_data, ++ install : true, ++ install_dir : 'share/metainfo' + ) + endif + endif +diff --git a/resources/linux/com.lite_xl.LiteXL.appdata.xml b/resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +similarity index 91% +rename from resources/linux/com.lite_xl.LiteXL.appdata.xml +rename to resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +index 6b8f1350..2550d95f 100644 +--- a/resources/linux/com.lite_xl.LiteXL.appdata.xml ++++ b/resources/linux/com.lite_xl.LiteXL.metainfo.xml.in +@@ -28,7 +28,5 @@ + lite-xl + + +- +- +- ++ @METAINFO_RELEASES@ + diff --git a/tasks/lite-xl__lite-xl-1923/tests/test.sh b/tasks/lite-xl__lite-xl-1923/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee216001a34603b41dbc01e93b6991f13d1a45e9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/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 3fe64609e70c98a6606968312d34827dc32f2ad4 > "$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/lite-xl__lite-xl-1923/tests/verifier.py b/tasks/lite-xl__lite-xl-1923/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1923/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/lite-xl__lite-xl-1924/environment/Dockerfile b/tasks/lite-xl__lite-xl-1924/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3709399aa4d1412eb6eb9e597e3c1acc3742739 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1345e9f34526e893ad55e903894891dd056b3dab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1345e9f34526e893ad55e903894891dd056b3dab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1345e9f34526e893ad55e903894891dd056b3dab \ + && 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/lite-xl__lite-xl-1924/instruction.md b/tasks/lite-xl__lite-xl-1924/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44faa1164d641c5a638bd7362529e9c36e56d0fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix appimage cd error and use static appimage runtime + +## Description + +However this won't fix the issue that the new builds of lite-xl don't use my user settings for some reason. + +----------------------------------------------------------------- + +I also updated the appimage to use the new [appimagetool](https://github.com/AppImage/appimagetool) that deploys the static appimage runtime, which gets rid of the libfuse2 dependency, **however this means that the appimage will no longer work with appimagelauncher is right now it does not support the static appimage runtime.** + +I think the issue with libfuse2 is much more important since distros now don't ship libfuse2, but if you don't want that just let me know anyway. (Several other projects are switching to the static runtime regardless, most notably Cemu did it 2 years ago). + +Also I removed the download of the generic AppRun and instead just made a simple one in the script, this is to avoid issues with the generic AppRun setting a lot of env variables that don't need to be set and would propagate to everything launched by lite-xl, like the terminal plugin, this is also why I changed the indentation to tabs to make the HEREDOC 😅 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1345e9f34526`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1924/solution/patch.diff b/tasks/lite-xl__lite-xl-1924/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5c98d67441bf52fd7381b00e71fef8e97402a4b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/solution/patch.diff @@ -0,0 +1,82 @@ +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +index d6bb83ee..41e4f7ae 100755 +--- a/scripts/install-dependencies.sh ++++ b/scripts/install-dependencies.sh +@@ -41,7 +41,7 @@ main() { + fi + + if [[ "$OSTYPE" == "linux"* ]]; then +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 ++ sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 desktop-file-utils + pip3 install meson + elif [[ "$OSTYPE" == "darwin"* ]]; then + brew install bash ninja sdl2 +diff --git a/scripts/package-appimage.sh b/scripts/package-appimage.sh +index f3e98e92..090f7912 100755 +--- a/scripts/package-appimage.sh ++++ b/scripts/package-appimage.sh +@@ -55,7 +55,7 @@ done + + setup_appimagetool() { + if [ ! -e appimagetool ]; then +- if ! wget -O appimagetool "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-${ARCH}.AppImage" ; then ++ if ! wget -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${ARCH}.AppImage" ; then + echo "Could not download the appimagetool for the arch '${ARCH}'." + exit 1 + else +@@ -64,17 +64,6 @@ setup_appimagetool() { + fi + } + +-download_appimage_apprun() { +- if [ ! -e AppRun ]; then +- if ! wget -O AppRun "https://github.com/AppImage/AppImageKit/releases/download/continuous/AppRun-${ARCH}" ; then +- echo "Could not download AppRun for the arch '${ARCH}'." +- exit 1 +- else +- chmod 0755 AppRun +- fi +- fi +-} +- + generate_appimage() { + [[ ! -e $BUILD_DIR ]] && scripts/build.sh $@ + +@@ -85,21 +74,33 @@ generate_appimage() { + echo "Creating LiteXL.AppDir..." + + DESTDIR="$(realpath LiteXL.AppDir)" meson install -C ${BUILD_DIR} +- mv AppRun LiteXL.AppDir/ +- # These could be symlinks but it seems they doesn't work with AppimageLauncher ++ + cp resources/icons/lite-xl.svg LiteXL.AppDir/ + cp resources/linux/com.lite_xl.LiteXL.desktop LiteXL.AppDir/ + ++ # https://github.com/lite-xl/lite-xl/issues/1912 ++ mkdir -p ./LiteXL.AppDir/usr/share/../bin ++ mv ./LiteXL.AppDir/lite-xl ./LiteXL.AppDir/usr/bin ++ mv ./LiteXL.AppDir/data ./LiteXL.AppDir/usr/share/lite-xl ++ rm -rf ./LiteXL.AppDir/lib64 ./LiteXL.AppDir/include ++ ++ echo "Creating AppRun..." ++ cat >> LiteXL.AppDir/AppRun <<- 'EOF' ++ #!/bin/sh ++ CURRENTDIR="$(dirname "$(readlink -f "$0")")" ++ exec "$CURRENTDIR/usr/bin/lite-xl" "$@" ++ EOF ++ chmod +x LiteXL.AppDir/AppRun ++ + echo "Generating AppImage..." + local version="" + if [ -n "$VERSION" ]; then + version="-$VERSION" + fi + +- ./appimagetool --appimage-extract-and-run LiteXL.AppDir LiteXL${version}-${ARCH}-linux.AppImage ++ APPIMAGE_EXTRACT_AND_RUN=1 ./appimagetool LiteXL.AppDir LiteXL${version}-${ARCH}-linux.AppImage + rm -rf LiteXL.AppDir + } + + setup_appimagetool +-download_appimage_apprun + generate_appimage diff --git a/tasks/lite-xl__lite-xl-1924/solution/solve.sh b/tasks/lite-xl__lite-xl-1924/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/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/lite-xl__lite-xl-1924/task.toml b/tasks/lite-xl__lite-xl-1924/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9234760aae4a8be6eb67e9aa8dc5a2ac03535e61 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1924" +description = "fix appimage cd error and use static appimage runtime" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "1345e9f34526e893ad55e903894891dd056b3dab" +reference = "https://github.com/lite-xl/lite-xl/pull/1924" +source_access = "auto" +built_at = "2026-11-16T16:09:56.326023+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:63838aee47bcc7a6253e4b0ca180eda02213bd9e0f17ec640b580b5e4f327829" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-15T02:39:11Z" +diff_format = "unified" +context_files = [ + "scripts/install-dependencies.sh", + "scripts/package-appimage.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 35 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.307172+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bb05502f125b01cba9b763930676e6fd0251b5ab4056299cdb470b75ff2912f1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1924/tests/capture.py b/tasks/lite-xl__lite-xl-1924/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/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/lite-xl__lite-xl-1924/tests/instruction.md b/tasks/lite-xl__lite-xl-1924/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44faa1164d641c5a638bd7362529e9c36e56d0fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix appimage cd error and use static appimage runtime + +## Description + +However this won't fix the issue that the new builds of lite-xl don't use my user settings for some reason. + +----------------------------------------------------------------- + +I also updated the appimage to use the new [appimagetool](https://github.com/AppImage/appimagetool) that deploys the static appimage runtime, which gets rid of the libfuse2 dependency, **however this means that the appimage will no longer work with appimagelauncher is right now it does not support the static appimage runtime.** + +I think the issue with libfuse2 is much more important since distros now don't ship libfuse2, but if you don't want that just let me know anyway. (Several other projects are switching to the static runtime regardless, most notably Cemu did it 2 years ago). + +Also I removed the download of the generic AppRun and instead just made a simple one in the script, this is to avoid issues with the generic AppRun setting a lot of env variables that don't need to be set and would propagate to everything launched by lite-xl, like the terminal plugin, this is also why I changed the indentation to tabs to make the HEREDOC 😅 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1345e9f34526`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1924/tests/oracle.patch b/tasks/lite-xl__lite-xl-1924/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5c98d67441bf52fd7381b00e71fef8e97402a4b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/tests/oracle.patch @@ -0,0 +1,82 @@ +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +index d6bb83ee..41e4f7ae 100755 +--- a/scripts/install-dependencies.sh ++++ b/scripts/install-dependencies.sh +@@ -41,7 +41,7 @@ main() { + fi + + if [[ "$OSTYPE" == "linux"* ]]; then +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 ++ sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 desktop-file-utils + pip3 install meson + elif [[ "$OSTYPE" == "darwin"* ]]; then + brew install bash ninja sdl2 +diff --git a/scripts/package-appimage.sh b/scripts/package-appimage.sh +index f3e98e92..090f7912 100755 +--- a/scripts/package-appimage.sh ++++ b/scripts/package-appimage.sh +@@ -55,7 +55,7 @@ done + + setup_appimagetool() { + if [ ! -e appimagetool ]; then +- if ! wget -O appimagetool "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-${ARCH}.AppImage" ; then ++ if ! wget -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${ARCH}.AppImage" ; then + echo "Could not download the appimagetool for the arch '${ARCH}'." + exit 1 + else +@@ -64,17 +64,6 @@ setup_appimagetool() { + fi + } + +-download_appimage_apprun() { +- if [ ! -e AppRun ]; then +- if ! wget -O AppRun "https://github.com/AppImage/AppImageKit/releases/download/continuous/AppRun-${ARCH}" ; then +- echo "Could not download AppRun for the arch '${ARCH}'." +- exit 1 +- else +- chmod 0755 AppRun +- fi +- fi +-} +- + generate_appimage() { + [[ ! -e $BUILD_DIR ]] && scripts/build.sh $@ + +@@ -85,21 +74,33 @@ generate_appimage() { + echo "Creating LiteXL.AppDir..." + + DESTDIR="$(realpath LiteXL.AppDir)" meson install -C ${BUILD_DIR} +- mv AppRun LiteXL.AppDir/ +- # These could be symlinks but it seems they doesn't work with AppimageLauncher ++ + cp resources/icons/lite-xl.svg LiteXL.AppDir/ + cp resources/linux/com.lite_xl.LiteXL.desktop LiteXL.AppDir/ + ++ # https://github.com/lite-xl/lite-xl/issues/1912 ++ mkdir -p ./LiteXL.AppDir/usr/share/../bin ++ mv ./LiteXL.AppDir/lite-xl ./LiteXL.AppDir/usr/bin ++ mv ./LiteXL.AppDir/data ./LiteXL.AppDir/usr/share/lite-xl ++ rm -rf ./LiteXL.AppDir/lib64 ./LiteXL.AppDir/include ++ ++ echo "Creating AppRun..." ++ cat >> LiteXL.AppDir/AppRun <<- 'EOF' ++ #!/bin/sh ++ CURRENTDIR="$(dirname "$(readlink -f "$0")")" ++ exec "$CURRENTDIR/usr/bin/lite-xl" "$@" ++ EOF ++ chmod +x LiteXL.AppDir/AppRun ++ + echo "Generating AppImage..." + local version="" + if [ -n "$VERSION" ]; then + version="-$VERSION" + fi + +- ./appimagetool --appimage-extract-and-run LiteXL.AppDir LiteXL${version}-${ARCH}-linux.AppImage ++ APPIMAGE_EXTRACT_AND_RUN=1 ./appimagetool LiteXL.AppDir LiteXL${version}-${ARCH}-linux.AppImage + rm -rf LiteXL.AppDir + } + + setup_appimagetool +-download_appimage_apprun + generate_appimage diff --git a/tasks/lite-xl__lite-xl-1924/tests/test.sh b/tasks/lite-xl__lite-xl-1924/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97b069362eb035a91aae9a800df2c6ee34498d2c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/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 1345e9f34526e893ad55e903894891dd056b3dab > "$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/lite-xl__lite-xl-1924/tests/verifier.py b/tasks/lite-xl__lite-xl-1924/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1924/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/lite-xl__lite-xl-1927/environment/Dockerfile b/tasks/lite-xl__lite-xl-1927/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a3709399aa4d1412eb6eb9e597e3c1acc3742739 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1345e9f34526e893ad55e903894891dd056b3dab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1345e9f34526e893ad55e903894891dd056b3dab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1345e9f34526e893ad55e903894891dd056b3dab \ + && 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/lite-xl__lite-xl-1927/instruction.md b/tasks/lite-xl__lite-xl-1927/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45a8386a3a1d39c9712473854a677c7dd1586fa3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update PCRE2 wrap + +## Description + +fixes configuration issues on systems that don't support the sealloc jit + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1345e9f34526`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1927/solution/patch.diff b/tasks/lite-xl__lite-xl-1927/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..23e0845fc0ed4d32ff3b8ba2c305b51522e54c6f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/subprojects/pcre2.wrap b/subprojects/pcre2.wrap +index 73b727ec..7e184472 100644 +--- a/subprojects/pcre2.wrap ++++ b/subprojects/pcre2.wrap +@@ -3,11 +3,11 @@ directory = pcre2-10.44 + source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.bz2 + source_filename = pcre2-10.44.tar.bz2 + source_hash = d34f02e113cf7193a1ebf2770d3ac527088d485d4e047ed10e5d217c6ef5de96 +-patch_filename = pcre2_10.44-1_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-1/get_patch +-patch_hash = 947ee4d309302024f780a5839e779674309c94c05bb5a0618d201979b424002f +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-1/pcre2-10.44.tar.bz2 +-wrapdb_version = 10.44-1 ++patch_filename = pcre2_10.44-2_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-2/get_patch ++patch_hash = 4336d422ee9043847e5e10dbbbd01940d4c9e5027f31ccdc33a7898a1ca94009 ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-2/pcre2-10.44.tar.bz2 ++wrapdb_version = 10.44-2 + + [provide] + libpcre2-8 = libpcre2_8 diff --git a/tasks/lite-xl__lite-xl-1927/solution/solve.sh b/tasks/lite-xl__lite-xl-1927/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/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/lite-xl__lite-xl-1927/task.toml b/tasks/lite-xl__lite-xl-1927/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba392d5e47d1fb0ffdd30b2033e9f9b4f3849e6a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1927" +description = "Update PCRE2 wrap" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "1345e9f34526e893ad55e903894891dd056b3dab" +reference = "https://github.com/lite-xl/lite-xl/pull/1927" +source_access = "auto" +built_at = "2026-11-16T16:09:56.328518+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b020d7998d0870ba5ed1c5d697b44016f280cf05e63216ee98ff68a6b60b427b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-03T10:20:38Z" +diff_format = "unified" +context_files = [ + "subprojects/pcre2.wrap", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.307628+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bb05502f125b01cba9b763930676e6fd0251b5ab4056299cdb470b75ff2912f1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1927/tests/capture.py b/tasks/lite-xl__lite-xl-1927/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/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/lite-xl__lite-xl-1927/tests/instruction.md b/tasks/lite-xl__lite-xl-1927/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45a8386a3a1d39c9712473854a677c7dd1586fa3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update PCRE2 wrap + +## Description + +fixes configuration issues on systems that don't support the sealloc jit + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1345e9f34526`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1927/tests/oracle.patch b/tasks/lite-xl__lite-xl-1927/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..23e0845fc0ed4d32ff3b8ba2c305b51522e54c6f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/subprojects/pcre2.wrap b/subprojects/pcre2.wrap +index 73b727ec..7e184472 100644 +--- a/subprojects/pcre2.wrap ++++ b/subprojects/pcre2.wrap +@@ -3,11 +3,11 @@ directory = pcre2-10.44 + source_url = https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.bz2 + source_filename = pcre2-10.44.tar.bz2 + source_hash = d34f02e113cf7193a1ebf2770d3ac527088d485d4e047ed10e5d217c6ef5de96 +-patch_filename = pcre2_10.44-1_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-1/get_patch +-patch_hash = 947ee4d309302024f780a5839e779674309c94c05bb5a0618d201979b424002f +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-1/pcre2-10.44.tar.bz2 +-wrapdb_version = 10.44-1 ++patch_filename = pcre2_10.44-2_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/pcre2_10.44-2/get_patch ++patch_hash = 4336d422ee9043847e5e10dbbbd01940d4c9e5027f31ccdc33a7898a1ca94009 ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/pcre2_10.44-2/pcre2-10.44.tar.bz2 ++wrapdb_version = 10.44-2 + + [provide] + libpcre2-8 = libpcre2_8 diff --git a/tasks/lite-xl__lite-xl-1927/tests/test.sh b/tasks/lite-xl__lite-xl-1927/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..97b069362eb035a91aae9a800df2c6ee34498d2c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/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 1345e9f34526e893ad55e903894891dd056b3dab > "$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/lite-xl__lite-xl-1927/tests/verifier.py b/tasks/lite-xl__lite-xl-1927/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1927/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/lite-xl__lite-xl-1929/environment/Dockerfile b/tasks/lite-xl__lite-xl-1929/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5623605c97dc8d4c3ce430f2c8811e77e0ff4e6c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin beb9c58084ea60eadc9b72184088e6a2325e66cf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && 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/lite-xl__lite-xl-1929/instruction.md b/tasks/lite-xl__lite-xl-1929/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4954b6fceb108a44f949fefe138e238febadbe0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add Storage Class + +## Description + +This PR depends on the project rework This is the reversion of a commit that pulled out the storage class. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1929/solution/patch.diff b/tasks/lite-xl__lite-xl-1929/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a7194a76e0bd411d9c6fa54fe54413523dd320f6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/solution/patch.diff @@ -0,0 +1,191 @@ +diff --git a/data/core/storage.lua b/data/core/storage.lua +new file mode 100644 +index 00000000..77ed4354 +--- /dev/null ++++ b/data/core/storage.lua +@@ -0,0 +1,78 @@ ++local core = require "core" ++local common = require "core.common" ++ ++local function module_key_to_path(module, key) ++ return USERDIR .. PATHSEP .. "storage" .. (module and (PATHSEP .. module .. (key and (PATHSEP .. key:gsub("[\\/]", "-")) or "")) or "") ++end ++ ++ ++---Provides persistent storage between restarts of the application. ++---@class storage ++local storage = {} ++ ++ ++---Loads data from a persistent storage file. ++--- ++---@param module string The module under which the data is stored. ++---@param key string The key under which the data is stored. ++---@return string|table|number? data The stored data present for this module, at this key. ++function storage.load(module, key) ++ local path = module_key_to_path(module, key) ++ if system.get_file_info(path) then ++ local func, err = loadfile(path) ++ if func then ++ return func() ++ else ++ core.error("error loading storage file for %s[%s]: %s", module, key, err) ++ end ++ end ++ return nil ++end ++ ++ ++---Saves data to a persistent storage file. ++--- ++---@param module string The module under which the data is stored. ++---@param key string The key under which the data is stored. ++---@param value table|string|number The value to store. ++function storage.save(module, key, value) ++ local path = module_key_to_path(module, key) ++ local dir = common.dirname(path) ++ if not system.get_file_info(dir) then ++ local status, err = common.mkdirp(dir) ++ if not status then ++ core.error("error creating storage directory for %s at %s: %s", module, dir, err) ++ end ++ end ++ local f, err = io.open(path, "wb") ++ if f then ++ f:write("return " .. common.serialize(value)) ++ f:flush() ++ else ++ core.error("error opening storage file %s for writing: %s", path, err) ++ end ++end ++ ++ ++---Gets the list of keys saved under a module. ++--- ++---@param module string The module under which the data is stored. ++---@return table A table of keys under which data is stored for this module. ++function storage.keys(module) ++ return system.list_dir(module_key_to_path(module)) or {} ++end ++ ++ ++---Clears data for a particular module and optionally key. ++--- ++---@param module string The module under which the data is stored. ++---@param key? string The key under which the data is stored. If omitted, will clear the entire store for this module. ++function storage.clear(module, key) ++ local path = module_key_to_path(module, key) ++ if system.get_file_info(path) then ++ common.rm(path, true) ++ end ++end ++ ++ ++return storage +diff --git a/data/plugins/workspace.lua b/data/plugins/workspace.lua +index 13782956..40d50ecc 100644 +--- a/data/plugins/workspace.lua ++++ b/data/plugins/workspace.lua +@@ -3,26 +3,18 @@ local core = require "core" + local common = require "core.common" + local DocView = require "core.docview" + local LogView = require "core.logview" ++local storage = require "core.storage" + ++local STORAGE_MODULE = "ws" + +-local function workspace_files_for(project_dir) ++local function workspace_keys_for(project_dir) + local basename = common.basename(project_dir) +- local workspace_dir = USERDIR .. PATHSEP .. "ws" +- local info_wsdir = system.get_file_info(workspace_dir) +- if not info_wsdir then +- local ok, err = system.mkdir(workspace_dir) +- if not ok then +- error("cannot create workspace directory: \"" .. err .. "\"") +- end +- end + return coroutine.wrap(function() +- local files = system.list_dir(workspace_dir) or {} +- local n = #basename +- for _, file in ipairs(files) do +- if file:sub(1, n) == basename then +- local id = tonumber(file:sub(n + 1):match("^-(%d+)$")) ++ for _, key in ipairs(storage.keys(STORAGE_MODULE) or {}) do ++ if key:sub(1, #basename) == basename then ++ local id = tonumber(key:sub(#basename + 1):match("^-(%d+)$")) + if id then +- coroutine.yield(workspace_dir .. PATHSEP .. file, id) ++ coroutine.yield(key, id) + end + end + end +@@ -30,32 +22,17 @@ local function workspace_files_for(project_dir) + end + + +-local function consume_workspace_file(project_dir) +- for filename, id in workspace_files_for(project_dir) do +- local load_f = loadfile(filename) +- local workspace = load_f and load_f() ++local function consume_workspace(project_dir) ++ for key, id in workspace_keys_for(project_dir) do ++ local workspace = storage.load(STORAGE_MODULE, key) + if workspace and workspace.path == project_dir then +- os.remove(filename) ++ storage.clear(STORAGE_MODULE, key) + return workspace + end + end + end + + +-local function get_workspace_filename(project_dir) +- local id_list = {} +- for filename, id in workspace_files_for(project_dir) do +- id_list[id] = true +- end +- local id = 1 +- while id_list[id] do +- id = id + 1 +- end +- local basename = common.basename(project_dir) +- return USERDIR .. PATHSEP .. "ws" .. PATHSEP .. basename .. "-" .. tostring(id) +-end +- +- + local function has_no_locked_children(node) + if node.locked then return false end + if node.type == "leaf" then return true end +@@ -195,20 +172,22 @@ end + + + local function save_workspace() +- local root = get_unlocked_root(core.root_view.root_node) +- local workspace_filename = get_workspace_filename(core.root_project().path) +- local fp = io.open(workspace_filename, "w") +- if fp then +- local node_text = common.serialize(save_node(root)) +- local dir_text = common.serialize(save_directories()) +- fp:write(string.format("return { path = %q, documents = %s, directories = %s }\n", core.root_project().path, node_text, dir_text)) +- fp:close() ++ local project_dir = common.basename(core.root_project().path) ++ local id_list = {} ++ for filename, id in workspace_keys_for(project_dir) do ++ id_list[id] = true + end ++ local id = 1 ++ while id_list[id] do ++ id = id + 1 ++ end ++ local root = get_unlocked_root(core.root_view.root_node) ++ storage.save(STORAGE_MODULE, project_dir .. "-" .. id, { path = core.root_project().path, documents = save_node(root), directories = save_directories() }) + end + + + local function load_workspace() +- local workspace = consume_workspace_file(core.root_project().path) ++ local workspace = consume_workspace(core.root_project().path) + if workspace then + local root = get_unlocked_root(core.root_view.root_node) + local active_view = load_node(root, workspace.documents) diff --git a/tasks/lite-xl__lite-xl-1929/solution/solve.sh b/tasks/lite-xl__lite-xl-1929/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/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/lite-xl__lite-xl-1929/task.toml b/tasks/lite-xl__lite-xl-1929/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cc6de7e685ce4810d33cd50bd452395965943067 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1929" +description = "Add Storage Class" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "beb9c58084ea60eadc9b72184088e6a2325e66cf" +reference = "https://github.com/lite-xl/lite-xl/pull/1929" +source_access = "auto" +built_at = "2026-11-16T16:09:56.176502+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2392c60bc184fd6ee80b101edb2360d9f562421e87ae771c5daa8108223ec9f0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-08-29T15:38:24Z" +diff_format = "unified" +context_files = [ + "data/core/storage.lua", + "data/plugins/workspace.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 143 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.308115+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:41289b24a16f7e138a7bcddb2669c2b475a76295db329b260eb1f05eb3d8be9f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1929/tests/capture.py b/tasks/lite-xl__lite-xl-1929/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/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/lite-xl__lite-xl-1929/tests/instruction.md b/tasks/lite-xl__lite-xl-1929/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4954b6fceb108a44f949fefe138e238febadbe0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add Storage Class + +## Description + +This PR depends on the project rework This is the reversion of a commit that pulled out the storage class. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1929/tests/oracle.patch b/tasks/lite-xl__lite-xl-1929/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a7194a76e0bd411d9c6fa54fe54413523dd320f6 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/tests/oracle.patch @@ -0,0 +1,191 @@ +diff --git a/data/core/storage.lua b/data/core/storage.lua +new file mode 100644 +index 00000000..77ed4354 +--- /dev/null ++++ b/data/core/storage.lua +@@ -0,0 +1,78 @@ ++local core = require "core" ++local common = require "core.common" ++ ++local function module_key_to_path(module, key) ++ return USERDIR .. PATHSEP .. "storage" .. (module and (PATHSEP .. module .. (key and (PATHSEP .. key:gsub("[\\/]", "-")) or "")) or "") ++end ++ ++ ++---Provides persistent storage between restarts of the application. ++---@class storage ++local storage = {} ++ ++ ++---Loads data from a persistent storage file. ++--- ++---@param module string The module under which the data is stored. ++---@param key string The key under which the data is stored. ++---@return string|table|number? data The stored data present for this module, at this key. ++function storage.load(module, key) ++ local path = module_key_to_path(module, key) ++ if system.get_file_info(path) then ++ local func, err = loadfile(path) ++ if func then ++ return func() ++ else ++ core.error("error loading storage file for %s[%s]: %s", module, key, err) ++ end ++ end ++ return nil ++end ++ ++ ++---Saves data to a persistent storage file. ++--- ++---@param module string The module under which the data is stored. ++---@param key string The key under which the data is stored. ++---@param value table|string|number The value to store. ++function storage.save(module, key, value) ++ local path = module_key_to_path(module, key) ++ local dir = common.dirname(path) ++ if not system.get_file_info(dir) then ++ local status, err = common.mkdirp(dir) ++ if not status then ++ core.error("error creating storage directory for %s at %s: %s", module, dir, err) ++ end ++ end ++ local f, err = io.open(path, "wb") ++ if f then ++ f:write("return " .. common.serialize(value)) ++ f:flush() ++ else ++ core.error("error opening storage file %s for writing: %s", path, err) ++ end ++end ++ ++ ++---Gets the list of keys saved under a module. ++--- ++---@param module string The module under which the data is stored. ++---@return table A table of keys under which data is stored for this module. ++function storage.keys(module) ++ return system.list_dir(module_key_to_path(module)) or {} ++end ++ ++ ++---Clears data for a particular module and optionally key. ++--- ++---@param module string The module under which the data is stored. ++---@param key? string The key under which the data is stored. If omitted, will clear the entire store for this module. ++function storage.clear(module, key) ++ local path = module_key_to_path(module, key) ++ if system.get_file_info(path) then ++ common.rm(path, true) ++ end ++end ++ ++ ++return storage +diff --git a/data/plugins/workspace.lua b/data/plugins/workspace.lua +index 13782956..40d50ecc 100644 +--- a/data/plugins/workspace.lua ++++ b/data/plugins/workspace.lua +@@ -3,26 +3,18 @@ local core = require "core" + local common = require "core.common" + local DocView = require "core.docview" + local LogView = require "core.logview" ++local storage = require "core.storage" + ++local STORAGE_MODULE = "ws" + +-local function workspace_files_for(project_dir) ++local function workspace_keys_for(project_dir) + local basename = common.basename(project_dir) +- local workspace_dir = USERDIR .. PATHSEP .. "ws" +- local info_wsdir = system.get_file_info(workspace_dir) +- if not info_wsdir then +- local ok, err = system.mkdir(workspace_dir) +- if not ok then +- error("cannot create workspace directory: \"" .. err .. "\"") +- end +- end + return coroutine.wrap(function() +- local files = system.list_dir(workspace_dir) or {} +- local n = #basename +- for _, file in ipairs(files) do +- if file:sub(1, n) == basename then +- local id = tonumber(file:sub(n + 1):match("^-(%d+)$")) ++ for _, key in ipairs(storage.keys(STORAGE_MODULE) or {}) do ++ if key:sub(1, #basename) == basename then ++ local id = tonumber(key:sub(#basename + 1):match("^-(%d+)$")) + if id then +- coroutine.yield(workspace_dir .. PATHSEP .. file, id) ++ coroutine.yield(key, id) + end + end + end +@@ -30,32 +22,17 @@ local function workspace_files_for(project_dir) + end + + +-local function consume_workspace_file(project_dir) +- for filename, id in workspace_files_for(project_dir) do +- local load_f = loadfile(filename) +- local workspace = load_f and load_f() ++local function consume_workspace(project_dir) ++ for key, id in workspace_keys_for(project_dir) do ++ local workspace = storage.load(STORAGE_MODULE, key) + if workspace and workspace.path == project_dir then +- os.remove(filename) ++ storage.clear(STORAGE_MODULE, key) + return workspace + end + end + end + + +-local function get_workspace_filename(project_dir) +- local id_list = {} +- for filename, id in workspace_files_for(project_dir) do +- id_list[id] = true +- end +- local id = 1 +- while id_list[id] do +- id = id + 1 +- end +- local basename = common.basename(project_dir) +- return USERDIR .. PATHSEP .. "ws" .. PATHSEP .. basename .. "-" .. tostring(id) +-end +- +- + local function has_no_locked_children(node) + if node.locked then return false end + if node.type == "leaf" then return true end +@@ -195,20 +172,22 @@ end + + + local function save_workspace() +- local root = get_unlocked_root(core.root_view.root_node) +- local workspace_filename = get_workspace_filename(core.root_project().path) +- local fp = io.open(workspace_filename, "w") +- if fp then +- local node_text = common.serialize(save_node(root)) +- local dir_text = common.serialize(save_directories()) +- fp:write(string.format("return { path = %q, documents = %s, directories = %s }\n", core.root_project().path, node_text, dir_text)) +- fp:close() ++ local project_dir = common.basename(core.root_project().path) ++ local id_list = {} ++ for filename, id in workspace_keys_for(project_dir) do ++ id_list[id] = true + end ++ local id = 1 ++ while id_list[id] do ++ id = id + 1 ++ end ++ local root = get_unlocked_root(core.root_view.root_node) ++ storage.save(STORAGE_MODULE, project_dir .. "-" .. id, { path = core.root_project().path, documents = save_node(root), directories = save_directories() }) + end + + + local function load_workspace() +- local workspace = consume_workspace_file(core.root_project().path) ++ local workspace = consume_workspace(core.root_project().path) + if workspace then + local root = get_unlocked_root(core.root_view.root_node) + local active_view = load_node(root, workspace.documents) diff --git a/tasks/lite-xl__lite-xl-1929/tests/test.sh b/tasks/lite-xl__lite-xl-1929/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aaaad4268f194f343f357f481b99487d38a2f6bc --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/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 beb9c58084ea60eadc9b72184088e6a2325e66cf > "$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/lite-xl__lite-xl-1929/tests/verifier.py b/tasks/lite-xl__lite-xl-1929/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1929/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/lite-xl__lite-xl-1937/environment/Dockerfile b/tasks/lite-xl__lite-xl-1937/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e3f17efb4e5dd9027e24f1817af4419609659b0b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin de13b6da2b36e47fbfadf3c491da1f2769e8234d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard de13b6da2b36e47fbfadf3c491da1f2769e8234d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base de13b6da2b36e47fbfadf3c491da1f2769e8234d \ + && 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/lite-xl__lite-xl-1937/instruction.md b/tasks/lite-xl__lite-xl-1937/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c426c25e9a8e4bc24c3c28a9d136935d262d106 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** move dependency resolving into src meson + +## Description + +These are only needed for building the actual project and not for managing resources or setting various flags. Gets rid of the double `source-only` check and moves it closer to the consumer + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `de13b6da2b36`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1937/solution/patch.diff b/tasks/lite-xl__lite-xl-1937/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..173010550c7651f4cb06e6b4515a6031ab683396 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/solution/patch.diff @@ -0,0 +1,260 @@ +diff --git a/meson.build b/meson.build +index 93fe8fa2..cddf194a 100644 +--- a/meson.build ++++ b/meson.build +@@ -40,10 +40,6 @@ conf_data.set('PROJECT_ASSEMBLY_VERSION', meson.project_version() + '.0') + #=============================================================================== + # Compiler Settings + #=============================================================================== +-if host_machine.system() == 'darwin' +- add_languages('objc') +-endif +- + cc = meson.get_compiler('c') + + lite_includes = [] +@@ -67,116 +63,6 @@ if host_machine.system() == 'darwin' + lite_link_args += ['-framework', 'CoreServices', '-framework', 'Foundation'] + endif + #=============================================================================== +-# Dependencies +-#=============================================================================== +-if not get_option('source-only') +- libm = cc.find_library('m', required : false) +- libdl = cc.find_library('dl', required : false) +- +- default_fallback_options = ['warning_level=0', 'werror=false'] +- +- # Lua has no official .pc file +- # so distros come up with their own names +- lua_names = [ +- 'lua5.4', # Debian +- 'lua-5.4', # FreeBSD +- 'lua', # Fedora +- ] +- +- if get_option('use_system_lua') +- foreach lua : lua_names +- last_lua = (lua == lua_names[-1] or get_option('wrap_mode') == 'forcefallback') +- lua_dep = dependency(lua, required : false, +- ) +- if lua_dep.found() +- break +- endif +- +- if last_lua +- # If we could not find lua on the system and fallbacks are disabled +- # try the compiler as a last ditch effort, since Lua has no official +- # pkg-config support. +- lua_dep = cc.find_library('lua', required : true) +- endif +- endforeach +- else +- lua_dep = dependency('', fallback: ['lua', 'lua_dep'], required : true, +- default_options: default_fallback_options + ['default_library=static', 'line_editing=disabled', 'interpreter=false'] +- ) +- endif +- +- pcre2_dep = dependency('libpcre2-8', fallback: ['pcre2', 'libpcre2_8'], +- default_options: default_fallback_options + ['default_library=static', 'grep=false', 'test=false'] +- ) +- +- freetype_dep = dependency('freetype2', fallback: ['freetype2', 'freetype_dep'], +- default_options: default_fallback_options + ['default_library=static', 'zlib=disabled', 'bzip2=disabled', 'png=disabled', 'harfbuzz=disabled', 'brotli=disabled'] +- ) +- +- +- sdl_options = ['default_library=static'] +- +- # we explicitly need these +- sdl_options += 'use_loadso=enabled' +- sdl_options += 'prefer_dlopen=true' +- sdl_options += 'use_video=enabled' +- sdl_options += 'use_atomic=enabled' +- sdl_options += 'use_threads=enabled' +- sdl_options += 'use_timers=enabled' +- # investigate if this is truly needed +- # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released +- sdl_options += 'use_events=enabled' +- +- if host_machine.system() == 'darwin' or host_machine.system() == 'windows' +- sdl_options += 'use_video_x11=disabled' +- sdl_options += 'use_video_wayland=disabled' +- else +- sdl_options += 'use_render=enabled' +- sdl_options += 'use_video_x11=auto' +- sdl_options += 'use_video_wayland=auto' +- endif +- +- # we leave this up to what the host system has except on windows +- if host_machine.system() != 'windows' +- sdl_options += 'use_video_opengl=auto' +- sdl_options += 'use_video_openglesv2=auto' +- else +- sdl_options += 'use_video_opengl=disabled' +- sdl_options += 'use_video_openglesv2=disabled' +- endif +- +- # we don't need these +- sdl_options += 'test=false' +- sdl_options += 'use_sensor=disabled' +- sdl_options += 'use_haptic=disabled' +- sdl_options += 'use_hidapi=disabled' +- sdl_options += 'use_audio=disabled' +- sdl_options += 'use_cpuinfo=disabled' +- sdl_options += 'use_joystick=disabled' +- sdl_options += 'use_joystick_xinput=disabled' +- sdl_options += 'use_video_vulkan=disabled' +- sdl_options += 'use_video_offscreen=disabled' +- sdl_options += 'use_power=disabled' +- sdl_options += 'system_iconv=disabled' +- +- sdl_dep = dependency('sdl2', fallback: ['sdl2', 'sdl2_dep'], +- default_options: default_fallback_options + sdl_options +- ) +- +- if host_machine.system() == 'windows' +- if sdl_dep.type_name() == 'internal' +- sdlmain_dep = dependency('sdl2main', fallback: ['sdl2main_dep']) +- else +- sdlmain_dep = cc.find_library('SDL2main') +- endif +- else +- sdlmain_dep = dependency('', required: false) +- assert(not sdlmain_dep.found(), 'checking if fake dependency has been found') +- endif +- +- lite_deps = [lua_dep, sdl_dep, sdlmain_dep, freetype_dep, pcre2_dep, libm, libdl] +-endif +-#=============================================================================== + # Install Configuration + #=============================================================================== + if get_option('portable') or host_machine.system() == 'windows' +diff --git a/src/meson.build b/src/meson.build +index 76ac1c89..6264d45f 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -13,6 +13,115 @@ lite_sources = [ + 'main.c', + ] + ++#=============================================================================== ++# Dependencies ++#=============================================================================== ++libm = cc.find_library('m', required : false) ++libdl = cc.find_library('dl', required : false) ++ ++default_fallback_options = ['warning_level=0', 'werror=false'] ++ ++# Lua has no official .pc file ++# so distros come up with their own names ++lua_names = [ ++ 'lua5.4', # Debian ++ 'lua-5.4', # FreeBSD ++ 'lua', # Fedora ++] ++ ++if get_option('use_system_lua') ++ foreach lua : lua_names ++ last_lua = (lua == lua_names[-1] or get_option('wrap_mode') == 'forcefallback') ++ lua_dep = dependency(lua, required : false, ++ ) ++ if lua_dep.found() ++ break ++ endif ++ ++ if last_lua ++ # If we could not find lua on the system and fallbacks are disabled ++ # try the compiler as a last ditch effort, since Lua has no official ++ # pkg-config support. ++ lua_dep = cc.find_library('lua', required : true) ++ endif ++ endforeach ++else ++ lua_dep = dependency('', fallback: ['lua', 'lua_dep'], required : true, ++ default_options: default_fallback_options + ['default_library=static', 'line_editing=disabled', 'interpreter=false'] ++ ) ++endif ++ ++pcre2_dep = dependency('libpcre2-8', fallback: ['pcre2', 'libpcre2_8'], ++ default_options: default_fallback_options + ['default_library=static', 'grep=false', 'test=false'] ++) ++ ++freetype_dep = dependency('freetype2', fallback: ['freetype2', 'freetype_dep'], ++ default_options: default_fallback_options + ['default_library=static', 'zlib=disabled', 'bzip2=disabled', 'png=disabled', 'harfbuzz=disabled', 'brotli=disabled'] ++) ++ ++ ++sdl_options = ['default_library=static'] ++ ++# we explicitly need these ++sdl_options += 'use_loadso=enabled' ++sdl_options += 'prefer_dlopen=true' ++sdl_options += 'use_video=enabled' ++sdl_options += 'use_atomic=enabled' ++sdl_options += 'use_threads=enabled' ++sdl_options += 'use_timers=enabled' ++# investigate if this is truly needed ++# Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released ++sdl_options += 'use_events=enabled' ++ ++if host_machine.system() == 'darwin' or host_machine.system() == 'windows' ++ sdl_options += 'use_video_x11=disabled' ++ sdl_options += 'use_video_wayland=disabled' ++else ++ sdl_options += 'use_render=enabled' ++ sdl_options += 'use_video_x11=auto' ++ sdl_options += 'use_video_wayland=auto' ++endif ++ ++# we leave this up to what the host system has except on windows ++if host_machine.system() != 'windows' ++ sdl_options += 'use_video_opengl=auto' ++ sdl_options += 'use_video_openglesv2=auto' ++else ++ sdl_options += 'use_video_opengl=disabled' ++ sdl_options += 'use_video_openglesv2=disabled' ++endif ++ ++# we don't need these ++sdl_options += 'test=false' ++sdl_options += 'use_sensor=disabled' ++sdl_options += 'use_haptic=disabled' ++sdl_options += 'use_hidapi=disabled' ++sdl_options += 'use_audio=disabled' ++sdl_options += 'use_cpuinfo=disabled' ++sdl_options += 'use_joystick=disabled' ++sdl_options += 'use_joystick_xinput=disabled' ++sdl_options += 'use_video_vulkan=disabled' ++sdl_options += 'use_video_offscreen=disabled' ++sdl_options += 'use_power=disabled' ++sdl_options += 'system_iconv=disabled' ++ ++sdl_dep = dependency('sdl2', fallback: ['sdl2', 'sdl2_dep'], ++ default_options: default_fallback_options + sdl_options ++) ++ ++if host_machine.system() == 'windows' ++ if sdl_dep.type_name() == 'internal' ++ sdlmain_dep = dependency('sdl2main', fallback: ['sdl2main_dep']) ++ else ++ sdlmain_dep = cc.find_library('SDL2main') ++ endif ++else ++ sdlmain_dep = dependency('', required: false) ++ assert(not sdlmain_dep.found(), 'checking if fake dependency has been found') ++endif ++ ++lite_deps = [lua_dep, sdl_dep, sdlmain_dep, freetype_dep, pcre2_dep, libm, libdl] ++ + lite_sources += 'api/dirmonitor.c' + # dirmonitor backend + if get_option('dirmonitor_backend') == '' +@@ -63,6 +172,7 @@ if host_machine.system() == 'windows' + lite_rc += windows.compile_resources('../resources/icons/icon.rc') + lite_rc += windows.compile_resources('../resources/windows/manifest.rc') + elif host_machine.system() == 'darwin' ++ add_languages('objc') + lite_sources += 'bundle_open.m' + endif + diff --git a/tasks/lite-xl__lite-xl-1937/solution/solve.sh b/tasks/lite-xl__lite-xl-1937/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/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/lite-xl__lite-xl-1937/task.toml b/tasks/lite-xl__lite-xl-1937/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..35fe77d457fe9e89633bf5c643aea4b11ac1f1df --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1937" +description = "move dependency resolving into src meson" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "de13b6da2b36e47fbfadf3c491da1f2769e8234d" +reference = "https://github.com/lite-xl/lite-xl/pull/1937" +source_access = "auto" +built_at = "2026-11-16T16:09:56.303021+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e3c9cf59d903a8db294741fe52061682b2d788511490b83ee2b823f9fc248ca9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T14:54:59Z" +diff_format = "unified" +context_files = [ + "meson.build", + "src/meson.build", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 224 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.308613+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2422bb973834b3108c0b2ad308bb849692572a02b93b6c6ce4d2a11082b3f93" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1937/tests/capture.py b/tasks/lite-xl__lite-xl-1937/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/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/lite-xl__lite-xl-1937/tests/instruction.md b/tasks/lite-xl__lite-xl-1937/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c426c25e9a8e4bc24c3c28a9d136935d262d106 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** move dependency resolving into src meson + +## Description + +These are only needed for building the actual project and not for managing resources or setting various flags. Gets rid of the double `source-only` check and moves it closer to the consumer + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `de13b6da2b36`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1937/tests/oracle.patch b/tasks/lite-xl__lite-xl-1937/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..173010550c7651f4cb06e6b4515a6031ab683396 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/tests/oracle.patch @@ -0,0 +1,260 @@ +diff --git a/meson.build b/meson.build +index 93fe8fa2..cddf194a 100644 +--- a/meson.build ++++ b/meson.build +@@ -40,10 +40,6 @@ conf_data.set('PROJECT_ASSEMBLY_VERSION', meson.project_version() + '.0') + #=============================================================================== + # Compiler Settings + #=============================================================================== +-if host_machine.system() == 'darwin' +- add_languages('objc') +-endif +- + cc = meson.get_compiler('c') + + lite_includes = [] +@@ -67,116 +63,6 @@ if host_machine.system() == 'darwin' + lite_link_args += ['-framework', 'CoreServices', '-framework', 'Foundation'] + endif + #=============================================================================== +-# Dependencies +-#=============================================================================== +-if not get_option('source-only') +- libm = cc.find_library('m', required : false) +- libdl = cc.find_library('dl', required : false) +- +- default_fallback_options = ['warning_level=0', 'werror=false'] +- +- # Lua has no official .pc file +- # so distros come up with their own names +- lua_names = [ +- 'lua5.4', # Debian +- 'lua-5.4', # FreeBSD +- 'lua', # Fedora +- ] +- +- if get_option('use_system_lua') +- foreach lua : lua_names +- last_lua = (lua == lua_names[-1] or get_option('wrap_mode') == 'forcefallback') +- lua_dep = dependency(lua, required : false, +- ) +- if lua_dep.found() +- break +- endif +- +- if last_lua +- # If we could not find lua on the system and fallbacks are disabled +- # try the compiler as a last ditch effort, since Lua has no official +- # pkg-config support. +- lua_dep = cc.find_library('lua', required : true) +- endif +- endforeach +- else +- lua_dep = dependency('', fallback: ['lua', 'lua_dep'], required : true, +- default_options: default_fallback_options + ['default_library=static', 'line_editing=disabled', 'interpreter=false'] +- ) +- endif +- +- pcre2_dep = dependency('libpcre2-8', fallback: ['pcre2', 'libpcre2_8'], +- default_options: default_fallback_options + ['default_library=static', 'grep=false', 'test=false'] +- ) +- +- freetype_dep = dependency('freetype2', fallback: ['freetype2', 'freetype_dep'], +- default_options: default_fallback_options + ['default_library=static', 'zlib=disabled', 'bzip2=disabled', 'png=disabled', 'harfbuzz=disabled', 'brotli=disabled'] +- ) +- +- +- sdl_options = ['default_library=static'] +- +- # we explicitly need these +- sdl_options += 'use_loadso=enabled' +- sdl_options += 'prefer_dlopen=true' +- sdl_options += 'use_video=enabled' +- sdl_options += 'use_atomic=enabled' +- sdl_options += 'use_threads=enabled' +- sdl_options += 'use_timers=enabled' +- # investigate if this is truly needed +- # Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released +- sdl_options += 'use_events=enabled' +- +- if host_machine.system() == 'darwin' or host_machine.system() == 'windows' +- sdl_options += 'use_video_x11=disabled' +- sdl_options += 'use_video_wayland=disabled' +- else +- sdl_options += 'use_render=enabled' +- sdl_options += 'use_video_x11=auto' +- sdl_options += 'use_video_wayland=auto' +- endif +- +- # we leave this up to what the host system has except on windows +- if host_machine.system() != 'windows' +- sdl_options += 'use_video_opengl=auto' +- sdl_options += 'use_video_openglesv2=auto' +- else +- sdl_options += 'use_video_opengl=disabled' +- sdl_options += 'use_video_openglesv2=disabled' +- endif +- +- # we don't need these +- sdl_options += 'test=false' +- sdl_options += 'use_sensor=disabled' +- sdl_options += 'use_haptic=disabled' +- sdl_options += 'use_hidapi=disabled' +- sdl_options += 'use_audio=disabled' +- sdl_options += 'use_cpuinfo=disabled' +- sdl_options += 'use_joystick=disabled' +- sdl_options += 'use_joystick_xinput=disabled' +- sdl_options += 'use_video_vulkan=disabled' +- sdl_options += 'use_video_offscreen=disabled' +- sdl_options += 'use_power=disabled' +- sdl_options += 'system_iconv=disabled' +- +- sdl_dep = dependency('sdl2', fallback: ['sdl2', 'sdl2_dep'], +- default_options: default_fallback_options + sdl_options +- ) +- +- if host_machine.system() == 'windows' +- if sdl_dep.type_name() == 'internal' +- sdlmain_dep = dependency('sdl2main', fallback: ['sdl2main_dep']) +- else +- sdlmain_dep = cc.find_library('SDL2main') +- endif +- else +- sdlmain_dep = dependency('', required: false) +- assert(not sdlmain_dep.found(), 'checking if fake dependency has been found') +- endif +- +- lite_deps = [lua_dep, sdl_dep, sdlmain_dep, freetype_dep, pcre2_dep, libm, libdl] +-endif +-#=============================================================================== + # Install Configuration + #=============================================================================== + if get_option('portable') or host_machine.system() == 'windows' +diff --git a/src/meson.build b/src/meson.build +index 76ac1c89..6264d45f 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -13,6 +13,115 @@ lite_sources = [ + 'main.c', + ] + ++#=============================================================================== ++# Dependencies ++#=============================================================================== ++libm = cc.find_library('m', required : false) ++libdl = cc.find_library('dl', required : false) ++ ++default_fallback_options = ['warning_level=0', 'werror=false'] ++ ++# Lua has no official .pc file ++# so distros come up with their own names ++lua_names = [ ++ 'lua5.4', # Debian ++ 'lua-5.4', # FreeBSD ++ 'lua', # Fedora ++] ++ ++if get_option('use_system_lua') ++ foreach lua : lua_names ++ last_lua = (lua == lua_names[-1] or get_option('wrap_mode') == 'forcefallback') ++ lua_dep = dependency(lua, required : false, ++ ) ++ if lua_dep.found() ++ break ++ endif ++ ++ if last_lua ++ # If we could not find lua on the system and fallbacks are disabled ++ # try the compiler as a last ditch effort, since Lua has no official ++ # pkg-config support. ++ lua_dep = cc.find_library('lua', required : true) ++ endif ++ endforeach ++else ++ lua_dep = dependency('', fallback: ['lua', 'lua_dep'], required : true, ++ default_options: default_fallback_options + ['default_library=static', 'line_editing=disabled', 'interpreter=false'] ++ ) ++endif ++ ++pcre2_dep = dependency('libpcre2-8', fallback: ['pcre2', 'libpcre2_8'], ++ default_options: default_fallback_options + ['default_library=static', 'grep=false', 'test=false'] ++) ++ ++freetype_dep = dependency('freetype2', fallback: ['freetype2', 'freetype_dep'], ++ default_options: default_fallback_options + ['default_library=static', 'zlib=disabled', 'bzip2=disabled', 'png=disabled', 'harfbuzz=disabled', 'brotli=disabled'] ++) ++ ++ ++sdl_options = ['default_library=static'] ++ ++# we explicitly need these ++sdl_options += 'use_loadso=enabled' ++sdl_options += 'prefer_dlopen=true' ++sdl_options += 'use_video=enabled' ++sdl_options += 'use_atomic=enabled' ++sdl_options += 'use_threads=enabled' ++sdl_options += 'use_timers=enabled' ++# investigate if this is truly needed ++# Do not remove before https://github.com/libsdl-org/SDL/issues/5413 is released ++sdl_options += 'use_events=enabled' ++ ++if host_machine.system() == 'darwin' or host_machine.system() == 'windows' ++ sdl_options += 'use_video_x11=disabled' ++ sdl_options += 'use_video_wayland=disabled' ++else ++ sdl_options += 'use_render=enabled' ++ sdl_options += 'use_video_x11=auto' ++ sdl_options += 'use_video_wayland=auto' ++endif ++ ++# we leave this up to what the host system has except on windows ++if host_machine.system() != 'windows' ++ sdl_options += 'use_video_opengl=auto' ++ sdl_options += 'use_video_openglesv2=auto' ++else ++ sdl_options += 'use_video_opengl=disabled' ++ sdl_options += 'use_video_openglesv2=disabled' ++endif ++ ++# we don't need these ++sdl_options += 'test=false' ++sdl_options += 'use_sensor=disabled' ++sdl_options += 'use_haptic=disabled' ++sdl_options += 'use_hidapi=disabled' ++sdl_options += 'use_audio=disabled' ++sdl_options += 'use_cpuinfo=disabled' ++sdl_options += 'use_joystick=disabled' ++sdl_options += 'use_joystick_xinput=disabled' ++sdl_options += 'use_video_vulkan=disabled' ++sdl_options += 'use_video_offscreen=disabled' ++sdl_options += 'use_power=disabled' ++sdl_options += 'system_iconv=disabled' ++ ++sdl_dep = dependency('sdl2', fallback: ['sdl2', 'sdl2_dep'], ++ default_options: default_fallback_options + sdl_options ++) ++ ++if host_machine.system() == 'windows' ++ if sdl_dep.type_name() == 'internal' ++ sdlmain_dep = dependency('sdl2main', fallback: ['sdl2main_dep']) ++ else ++ sdlmain_dep = cc.find_library('SDL2main') ++ endif ++else ++ sdlmain_dep = dependency('', required: false) ++ assert(not sdlmain_dep.found(), 'checking if fake dependency has been found') ++endif ++ ++lite_deps = [lua_dep, sdl_dep, sdlmain_dep, freetype_dep, pcre2_dep, libm, libdl] ++ + lite_sources += 'api/dirmonitor.c' + # dirmonitor backend + if get_option('dirmonitor_backend') == '' +@@ -63,6 +172,7 @@ if host_machine.system() == 'windows' + lite_rc += windows.compile_resources('../resources/icons/icon.rc') + lite_rc += windows.compile_resources('../resources/windows/manifest.rc') + elif host_machine.system() == 'darwin' ++ add_languages('objc') + lite_sources += 'bundle_open.m' + endif + diff --git a/tasks/lite-xl__lite-xl-1937/tests/test.sh b/tasks/lite-xl__lite-xl-1937/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d97ed111e85b1b8dadfa1b940003eca9035e7a3c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/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 de13b6da2b36e47fbfadf3c491da1f2769e8234d > "$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/lite-xl__lite-xl-1937/tests/verifier.py b/tasks/lite-xl__lite-xl-1937/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1937/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/lite-xl__lite-xl-1938/environment/Dockerfile b/tasks/lite-xl__lite-xl-1938/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a2fb04354a8874f8036bc6d4cac2412e9943d6f1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin dcedce8e6a2c6be788a815470bb3e42988792a07 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard dcedce8e6a2c6be788a815470bb3e42988792a07 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base dcedce8e6a2c6be788a815470bb3e42988792a07 \ + && 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/lite-xl__lite-xl-1938/instruction.md b/tasks/lite-xl__lite-xl-1938/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3229fefbdfc9f130bb94da38784d7487d0ee1ae9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** convert unix style paths literals into meson path segments + +## Description + +While thus far everything has been working without a problem this is mostly due to various translations happening in meson, python and the underlying Windows APIs and we cannot guarantee that nothing will ever change in this translation on any layer + +This PR simply replaces the string literals with path segments that form an OS native path + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dcedce8e6a2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1938/solution/patch.diff b/tasks/lite-xl__lite-xl-1938/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..86c5e6f5c7782ca2aaed87068faed7dd5e3bab07 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/solution/patch.diff @@ -0,0 +1,122 @@ +diff --git a/meson.build b/meson.build +index 470b34c6..deb5353f 100644 +--- a/meson.build ++++ b/meson.build +@@ -184,54 +184,55 @@ if get_option('portable') or host_machine.system() == 'windows' + lite_docdir = '/doc' + lite_datadir = '/data' + configure_file( +- input: 'resources/windows/lite-xl.exe.manifest.in', ++ input: 'resources' / 'windows' / 'lite-xl.exe.manifest.in', + output: 'lite-xl.exe.manifest', + configuration: conf_data + ) + elif get_option('bundle') and host_machine.system() == 'darwin' + lite_cargs += '-DMACOS_USE_BUNDLE' +- lite_bindir = 'Contents/MacOS' +- lite_docdir = 'Contents/Resources' +- lite_datadir = 'Contents/Resources' ++ lite_bindir = 'Contents' / 'MacOS' ++ lite_docdir = 'Contents' / 'Resources' ++ lite_datadir = 'Contents' / 'Resources' + conf_data.set( + 'CURRENT_YEAR', + run_command('date', '+%Y', capture: true).stdout().strip() + ) +- install_data('resources/icons/icon.icns', install_dir : 'Contents/Resources') ++ install_data('resources' / 'icons' / 'icon.icns', install_dir : 'Contents' / 'Resources') + configure_file( +- input : 'resources/macos/Info.plist.in', ++ input : 'resources' / 'macos' / 'Info.plist.in', + output : 'Info.plist', + configuration : conf_data, + install : true, + install_dir : 'Contents' + ) + else ++ message() + lite_bindir = 'bin' +- lite_docdir = get_option('datadir') + '/doc/lite-xl' +- lite_datadir = get_option('datadir') + '/lite-xl' ++ lite_docdir = get_option('datadir') / 'doc' / 'lite-xl' ++ lite_datadir = get_option('datadir') / 'lite-xl' + if host_machine.system() == 'linux' +- install_data('resources/icons/lite-xl.svg', +- install_dir : get_option('datadir') + '/icons/hicolor/scalable/apps' ++ install_data('resources' / 'icons' / 'lite-xl.svg', ++ install_dir : get_option('datadir') / 'icons' / 'hicolor' / 'scalable' / 'apps' + ) +- install_data('resources/linux/com.lite_xl.LiteXL.desktop', +- install_dir : get_option('datadir') + '/applications' ++ install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.desktop', ++ install_dir : get_option('datadir') / 'applications' + ) +- install_data('resources/linux/com.lite_xl.LiteXL.appdata.xml', +- install_dir : get_option('datadir') + '/metainfo' ++ install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.appdata.xml', ++ install_dir : get_option('datadir') / 'metainfo' + ) + endif + endif + +-install_data('licenses/licenses.md', install_dir : lite_docdir) ++install_data('licenses' / 'licenses.md', install_dir : lite_docdir) + +-install_subdir('docs/api' , install_dir : lite_datadir, strip_directory: true) +-install_subdir('data/core' , install_dir : lite_datadir, exclude_files : 'start.lua') ++install_subdir('docs' / 'api' , install_dir : lite_datadir, strip_directory: true) ++install_subdir('data' / 'core' , install_dir : lite_datadir, exclude_files : 'start.lua') + foreach data_module : ['fonts', 'plugins', 'colors'] + install_subdir(join_paths('data', data_module), install_dir : lite_datadir) + endforeach + + configure_file( +- input : 'data/core/start.lua', ++ input : 'data' / 'core' / 'start.lua', + output : 'start.lua', + configuration : conf_data, + install_dir : join_paths(lite_datadir, 'core'), +diff --git a/src/meson.build b/src/meson.build +index 76ac1c89..bcb19a19 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -37,22 +37,22 @@ else + endif + + if dirmonitor_backend == 'inotify' +- lite_sources += 'api/dirmonitor/inotify.c' ++ lite_sources += 'api' / 'dirmonitor' / 'inotify.c' + elif dirmonitor_backend == 'fsevents' +- lite_sources += 'api/dirmonitor/fsevents.c' ++ lite_sources += 'api' / 'dirmonitor' / 'fsevents.c' + elif dirmonitor_backend == 'kqueue' +- lite_sources += 'api/dirmonitor/kqueue.c' ++ lite_sources += 'api' / 'dirmonitor' / 'kqueue.c' + libkqueue_dep = dependency('libkqueue', required : false) + if libkqueue_dep.found() + lite_deps += libkqueue_dep + endif + elif dirmonitor_backend == 'inodewatcher' + add_languages('cpp') +- lite_sources += 'api/dirmonitor/inodewatcher.cpp' ++ lite_sources += 'api' / 'dirmonitor' / 'inodewatcher.cpp' + elif dirmonitor_backend == 'win32' +- lite_sources += 'api/dirmonitor/win32.c' ++ lite_sources += 'api' / 'dirmonitor' / 'win32.c' + else +- lite_sources += 'api/dirmonitor/dummy.c' ++ lite_sources += 'api' / 'dirmonitor' / 'dummy.c' + endif + + message('dirmonitor_backend: @0@'.format(dirmonitor_backend)) +@@ -60,8 +60,8 @@ message('dirmonitor_backend: @0@'.format(dirmonitor_backend)) + lite_rc = [] + if host_machine.system() == 'windows' + windows = import('windows') +- lite_rc += windows.compile_resources('../resources/icons/icon.rc') +- lite_rc += windows.compile_resources('../resources/windows/manifest.rc') ++ lite_rc += windows.compile_resources('..' / 'resources' / 'icons' / 'icon.rc') ++ lite_rc += windows.compile_resources('..' / 'resources' / 'windows' / 'manifest.rc') + elif host_machine.system() == 'darwin' + lite_sources += 'bundle_open.m' + endif diff --git a/tasks/lite-xl__lite-xl-1938/solution/solve.sh b/tasks/lite-xl__lite-xl-1938/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/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/lite-xl__lite-xl-1938/task.toml b/tasks/lite-xl__lite-xl-1938/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..862c69a47faadbd5980a03cc754d61bdb5ccc928 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1938" +description = "convert unix style paths literals into meson path segments" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "dcedce8e6a2c6be788a815470bb3e42988792a07" +reference = "https://github.com/lite-xl/lite-xl/pull/1938" +source_access = "auto" +built_at = "2026-11-16T16:09:56.323107+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c844cb0bcf468829f0da0916e471391d9a6325ebd676a3d7dabfdcd4c732a2c9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-15T09:41:57Z" +diff_format = "unified" +context_files = [ + "meson.build", + "src/meson.build", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 53 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.309053+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9dad37be99b967d7328cbabc1e12b8c7e8440e51e345370a53c35b511ab05750" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1938/tests/capture.py b/tasks/lite-xl__lite-xl-1938/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/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/lite-xl__lite-xl-1938/tests/instruction.md b/tasks/lite-xl__lite-xl-1938/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3229fefbdfc9f130bb94da38784d7487d0ee1ae9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** convert unix style paths literals into meson path segments + +## Description + +While thus far everything has been working without a problem this is mostly due to various translations happening in meson, python and the underlying Windows APIs and we cannot guarantee that nothing will ever change in this translation on any layer + +This PR simply replaces the string literals with path segments that form an OS native path + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dcedce8e6a2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1938/tests/oracle.patch b/tasks/lite-xl__lite-xl-1938/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..86c5e6f5c7782ca2aaed87068faed7dd5e3bab07 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/tests/oracle.patch @@ -0,0 +1,122 @@ +diff --git a/meson.build b/meson.build +index 470b34c6..deb5353f 100644 +--- a/meson.build ++++ b/meson.build +@@ -184,54 +184,55 @@ if get_option('portable') or host_machine.system() == 'windows' + lite_docdir = '/doc' + lite_datadir = '/data' + configure_file( +- input: 'resources/windows/lite-xl.exe.manifest.in', ++ input: 'resources' / 'windows' / 'lite-xl.exe.manifest.in', + output: 'lite-xl.exe.manifest', + configuration: conf_data + ) + elif get_option('bundle') and host_machine.system() == 'darwin' + lite_cargs += '-DMACOS_USE_BUNDLE' +- lite_bindir = 'Contents/MacOS' +- lite_docdir = 'Contents/Resources' +- lite_datadir = 'Contents/Resources' ++ lite_bindir = 'Contents' / 'MacOS' ++ lite_docdir = 'Contents' / 'Resources' ++ lite_datadir = 'Contents' / 'Resources' + conf_data.set( + 'CURRENT_YEAR', + run_command('date', '+%Y', capture: true).stdout().strip() + ) +- install_data('resources/icons/icon.icns', install_dir : 'Contents/Resources') ++ install_data('resources' / 'icons' / 'icon.icns', install_dir : 'Contents' / 'Resources') + configure_file( +- input : 'resources/macos/Info.plist.in', ++ input : 'resources' / 'macos' / 'Info.plist.in', + output : 'Info.plist', + configuration : conf_data, + install : true, + install_dir : 'Contents' + ) + else ++ message() + lite_bindir = 'bin' +- lite_docdir = get_option('datadir') + '/doc/lite-xl' +- lite_datadir = get_option('datadir') + '/lite-xl' ++ lite_docdir = get_option('datadir') / 'doc' / 'lite-xl' ++ lite_datadir = get_option('datadir') / 'lite-xl' + if host_machine.system() == 'linux' +- install_data('resources/icons/lite-xl.svg', +- install_dir : get_option('datadir') + '/icons/hicolor/scalable/apps' ++ install_data('resources' / 'icons' / 'lite-xl.svg', ++ install_dir : get_option('datadir') / 'icons' / 'hicolor' / 'scalable' / 'apps' + ) +- install_data('resources/linux/com.lite_xl.LiteXL.desktop', +- install_dir : get_option('datadir') + '/applications' ++ install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.desktop', ++ install_dir : get_option('datadir') / 'applications' + ) +- install_data('resources/linux/com.lite_xl.LiteXL.appdata.xml', +- install_dir : get_option('datadir') + '/metainfo' ++ install_data('resources' / 'linux' / 'com.lite_xl.LiteXL.appdata.xml', ++ install_dir : get_option('datadir') / 'metainfo' + ) + endif + endif + +-install_data('licenses/licenses.md', install_dir : lite_docdir) ++install_data('licenses' / 'licenses.md', install_dir : lite_docdir) + +-install_subdir('docs/api' , install_dir : lite_datadir, strip_directory: true) +-install_subdir('data/core' , install_dir : lite_datadir, exclude_files : 'start.lua') ++install_subdir('docs' / 'api' , install_dir : lite_datadir, strip_directory: true) ++install_subdir('data' / 'core' , install_dir : lite_datadir, exclude_files : 'start.lua') + foreach data_module : ['fonts', 'plugins', 'colors'] + install_subdir(join_paths('data', data_module), install_dir : lite_datadir) + endforeach + + configure_file( +- input : 'data/core/start.lua', ++ input : 'data' / 'core' / 'start.lua', + output : 'start.lua', + configuration : conf_data, + install_dir : join_paths(lite_datadir, 'core'), +diff --git a/src/meson.build b/src/meson.build +index 76ac1c89..bcb19a19 100644 +--- a/src/meson.build ++++ b/src/meson.build +@@ -37,22 +37,22 @@ else + endif + + if dirmonitor_backend == 'inotify' +- lite_sources += 'api/dirmonitor/inotify.c' ++ lite_sources += 'api' / 'dirmonitor' / 'inotify.c' + elif dirmonitor_backend == 'fsevents' +- lite_sources += 'api/dirmonitor/fsevents.c' ++ lite_sources += 'api' / 'dirmonitor' / 'fsevents.c' + elif dirmonitor_backend == 'kqueue' +- lite_sources += 'api/dirmonitor/kqueue.c' ++ lite_sources += 'api' / 'dirmonitor' / 'kqueue.c' + libkqueue_dep = dependency('libkqueue', required : false) + if libkqueue_dep.found() + lite_deps += libkqueue_dep + endif + elif dirmonitor_backend == 'inodewatcher' + add_languages('cpp') +- lite_sources += 'api/dirmonitor/inodewatcher.cpp' ++ lite_sources += 'api' / 'dirmonitor' / 'inodewatcher.cpp' + elif dirmonitor_backend == 'win32' +- lite_sources += 'api/dirmonitor/win32.c' ++ lite_sources += 'api' / 'dirmonitor' / 'win32.c' + else +- lite_sources += 'api/dirmonitor/dummy.c' ++ lite_sources += 'api' / 'dirmonitor' / 'dummy.c' + endif + + message('dirmonitor_backend: @0@'.format(dirmonitor_backend)) +@@ -60,8 +60,8 @@ message('dirmonitor_backend: @0@'.format(dirmonitor_backend)) + lite_rc = [] + if host_machine.system() == 'windows' + windows = import('windows') +- lite_rc += windows.compile_resources('../resources/icons/icon.rc') +- lite_rc += windows.compile_resources('../resources/windows/manifest.rc') ++ lite_rc += windows.compile_resources('..' / 'resources' / 'icons' / 'icon.rc') ++ lite_rc += windows.compile_resources('..' / 'resources' / 'windows' / 'manifest.rc') + elif host_machine.system() == 'darwin' + lite_sources += 'bundle_open.m' + endif diff --git a/tasks/lite-xl__lite-xl-1938/tests/test.sh b/tasks/lite-xl__lite-xl-1938/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..49a9aed3fadbdecb83a791baa722bdf2c340b7e7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/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 dcedce8e6a2c6be788a815470bb3e42988792a07 > "$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/lite-xl__lite-xl-1938/tests/verifier.py b/tasks/lite-xl__lite-xl-1938/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1938/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/lite-xl__lite-xl-1939/environment/Dockerfile b/tasks/lite-xl__lite-xl-1939/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..51e15cb4719e381a7ffd8480ad8d6775e08fc5e2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 532cd0d06aaabba349e3d2b877ab5e9494e4d84a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 532cd0d06aaabba349e3d2b877ab5e9494e4d84a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 532cd0d06aaabba349e3d2b877ab5e9494e4d84a \ + && 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/lite-xl__lite-xl-1939/instruction.md b/tasks/lite-xl__lite-xl-1939/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29357f34dc1ec8c1f173d2c945a45e300958e4b9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** use meson datadir as lite_datadir base + +## Description + +`meson setup` has a flag to set the datadir, this PR makes it so lite-xl respects it and works relatively from it + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532cd0d06aaa`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1939/solution/patch.diff b/tasks/lite-xl__lite-xl-1939/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0e3266e95201e8340c1090eb7734909b8be23181 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/meson.build b/meson.build +index 93fe8fa2..470b34c6 100644 +--- a/meson.build ++++ b/meson.build +@@ -207,17 +207,17 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + ) + else + lite_bindir = 'bin' +- lite_docdir = 'share/doc/lite-xl' +- lite_datadir = 'share/lite-xl' ++ lite_docdir = get_option('datadir') + '/doc/lite-xl' ++ lite_datadir = get_option('datadir') + '/lite-xl' + if host_machine.system() == 'linux' + install_data('resources/icons/lite-xl.svg', +- install_dir : 'share/icons/hicolor/scalable/apps' ++ install_dir : get_option('datadir') + '/icons/hicolor/scalable/apps' + ) + install_data('resources/linux/com.lite_xl.LiteXL.desktop', +- install_dir : 'share/applications' ++ install_dir : get_option('datadir') + '/applications' + ) + install_data('resources/linux/com.lite_xl.LiteXL.appdata.xml', +- install_dir : 'share/metainfo' ++ install_dir : get_option('datadir') + '/metainfo' + ) + endif + endif diff --git a/tasks/lite-xl__lite-xl-1939/solution/solve.sh b/tasks/lite-xl__lite-xl-1939/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/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/lite-xl__lite-xl-1939/task.toml b/tasks/lite-xl__lite-xl-1939/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fa3667534fb45cdad51e796bc3fae8c560aff6e8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1939" +description = "use meson datadir as lite_datadir base" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "532cd0d06aaabba349e3d2b877ab5e9494e4d84a" +reference = "https://github.com/lite-xl/lite-xl/pull/1939" +source_access = "auto" +built_at = "2026-11-16T16:09:56.324545+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e9cd0fd944635ae6880b69d8338a6620dbae7dd40eb5e7e3b959c0a3d61a1768" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-15T09:35:41Z" +diff_format = "unified" +context_files = [ + "meson.build", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.309491+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ed52ee6726163d4fe1dec22ac4c231fd79183bd570d87c77771e918ef221764d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1939/tests/capture.py b/tasks/lite-xl__lite-xl-1939/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/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/lite-xl__lite-xl-1939/tests/instruction.md b/tasks/lite-xl__lite-xl-1939/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29357f34dc1ec8c1f173d2c945a45e300958e4b9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** use meson datadir as lite_datadir base + +## Description + +`meson setup` has a flag to set the datadir, this PR makes it so lite-xl respects it and works relatively from it + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532cd0d06aaa`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1939/tests/oracle.patch b/tasks/lite-xl__lite-xl-1939/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0e3266e95201e8340c1090eb7734909b8be23181 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/meson.build b/meson.build +index 93fe8fa2..470b34c6 100644 +--- a/meson.build ++++ b/meson.build +@@ -207,17 +207,17 @@ elif get_option('bundle') and host_machine.system() == 'darwin' + ) + else + lite_bindir = 'bin' +- lite_docdir = 'share/doc/lite-xl' +- lite_datadir = 'share/lite-xl' ++ lite_docdir = get_option('datadir') + '/doc/lite-xl' ++ lite_datadir = get_option('datadir') + '/lite-xl' + if host_machine.system() == 'linux' + install_data('resources/icons/lite-xl.svg', +- install_dir : 'share/icons/hicolor/scalable/apps' ++ install_dir : get_option('datadir') + '/icons/hicolor/scalable/apps' + ) + install_data('resources/linux/com.lite_xl.LiteXL.desktop', +- install_dir : 'share/applications' ++ install_dir : get_option('datadir') + '/applications' + ) + install_data('resources/linux/com.lite_xl.LiteXL.appdata.xml', +- install_dir : 'share/metainfo' ++ install_dir : get_option('datadir') + '/metainfo' + ) + endif + endif diff --git a/tasks/lite-xl__lite-xl-1939/tests/test.sh b/tasks/lite-xl__lite-xl-1939/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d13c98c7ec823fb6c6a708ecde8b4903ad7c7e2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/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 532cd0d06aaabba349e3d2b877ab5e9494e4d84a > "$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/lite-xl__lite-xl-1939/tests/verifier.py b/tasks/lite-xl__lite-xl-1939/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1939/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/lite-xl__lite-xl-1940/environment/Dockerfile b/tasks/lite-xl__lite-xl-1940/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..51e15cb4719e381a7ffd8480ad8d6775e08fc5e2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 532cd0d06aaabba349e3d2b877ab5e9494e4d84a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 532cd0d06aaabba349e3d2b877ab5e9494e4d84a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 532cd0d06aaabba349e3d2b877ab5e9494e4d84a \ + && 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/lite-xl__lite-xl-1940/instruction.md b/tasks/lite-xl__lite-xl-1940/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43ab0411cb8bb6b45601ae866910a10441e5ec96 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update lua wrap + +## Description + +lua wrap no longer makes bad assumptions allowing me to port it to more esoteric systems + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532cd0d06aaa`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1940/solution/patch.diff b/tasks/lite-xl__lite-xl-1940/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3add8035f4029eb8b3f44b9445fb936c3be09034 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/subprojects/lua.wrap b/subprojects/lua.wrap +index b186f2cf..94494c8c 100644 +--- a/subprojects/lua.wrap ++++ b/subprojects/lua.wrap +@@ -3,11 +3,11 @@ directory = lua-5.4.6 + source_url = https://www.lua.org/ftp/lua-5.4.6.tar.gz + source_filename = lua-5.4.6.tar.gz + source_hash = 7d5ea1b9cb6aa0b59ca3dde1c6adcb57ef83a1ba8e5432c0ecd06bf439b3ad88 +-patch_filename = lua_5.4.6-4_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-4/get_patch +-patch_hash = b5a8c9b3673fbe58afaf842041bc9551f1f742c363fd3be8d47db2e6a483b54c +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-4/lua-5.4.6.tar.gz +-wrapdb_version = 5.4.6-4 ++patch_filename = lua_5.4.6-5_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-5/get_patch ++patch_hash = 755ec591b6b4739650ba6bb11b4feca2d221ab7f80f024dd625f50c8932ad76f ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-5/lua-5.4.6.tar.gz ++wrapdb_version = 5.4.6-5 + diff_files = lua/lua-unicode.diff + + [provide] diff --git a/tasks/lite-xl__lite-xl-1940/solution/solve.sh b/tasks/lite-xl__lite-xl-1940/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/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/lite-xl__lite-xl-1940/task.toml b/tasks/lite-xl__lite-xl-1940/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08cf927ca970a415798f228f568eff72514ac2ab --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1940" +description = "Update lua wrap" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "532cd0d06aaabba349e3d2b877ab5e9494e4d84a" +reference = "https://github.com/lite-xl/lite-xl/pull/1940" +source_access = "auto" +built_at = "2026-11-16T16:09:56.327360+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3038c2a5081494d62e922df21e841b6f2a4f4509f937adf98727148c2e648720" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-13T03:21:51Z" +diff_format = "unified" +context_files = [ + "subprojects/lua.wrap", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.309935+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ed52ee6726163d4fe1dec22ac4c231fd79183bd570d87c77771e918ef221764d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1940/tests/capture.py b/tasks/lite-xl__lite-xl-1940/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/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/lite-xl__lite-xl-1940/tests/instruction.md b/tasks/lite-xl__lite-xl-1940/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43ab0411cb8bb6b45601ae866910a10441e5ec96 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Update lua wrap + +## Description + +lua wrap no longer makes bad assumptions allowing me to port it to more esoteric systems + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532cd0d06aaa`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1940/tests/oracle.patch b/tasks/lite-xl__lite-xl-1940/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3add8035f4029eb8b3f44b9445fb936c3be09034 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/subprojects/lua.wrap b/subprojects/lua.wrap +index b186f2cf..94494c8c 100644 +--- a/subprojects/lua.wrap ++++ b/subprojects/lua.wrap +@@ -3,11 +3,11 @@ directory = lua-5.4.6 + source_url = https://www.lua.org/ftp/lua-5.4.6.tar.gz + source_filename = lua-5.4.6.tar.gz + source_hash = 7d5ea1b9cb6aa0b59ca3dde1c6adcb57ef83a1ba8e5432c0ecd06bf439b3ad88 +-patch_filename = lua_5.4.6-4_patch.zip +-patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-4/get_patch +-patch_hash = b5a8c9b3673fbe58afaf842041bc9551f1f742c363fd3be8d47db2e6a483b54c +-source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-4/lua-5.4.6.tar.gz +-wrapdb_version = 5.4.6-4 ++patch_filename = lua_5.4.6-5_patch.zip ++patch_url = https://wrapdb.mesonbuild.com/v2/lua_5.4.6-5/get_patch ++patch_hash = 755ec591b6b4739650ba6bb11b4feca2d221ab7f80f024dd625f50c8932ad76f ++source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/lua_5.4.6-5/lua-5.4.6.tar.gz ++wrapdb_version = 5.4.6-5 + diff_files = lua/lua-unicode.diff + + [provide] diff --git a/tasks/lite-xl__lite-xl-1940/tests/test.sh b/tasks/lite-xl__lite-xl-1940/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d13c98c7ec823fb6c6a708ecde8b4903ad7c7e2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/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 532cd0d06aaabba349e3d2b877ab5e9494e4d84a > "$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/lite-xl__lite-xl-1940/tests/verifier.py b/tasks/lite-xl__lite-xl-1940/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1940/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/lite-xl__lite-xl-1946/environment/Dockerfile b/tasks/lite-xl__lite-xl-1946/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f6e67461a1da1d87a4bba91b6eaecafdc069761 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 64420f4366a290b3c3f48f0131a8f77312def595 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 64420f4366a290b3c3f48f0131a8f77312def595 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 64420f4366a290b3c3f48f0131a8f77312def595 \ + && 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/lite-xl__lite-xl-1946/instruction.md b/tasks/lite-xl__lite-xl-1946/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13edad13999d5027324b65b6d6b8a0d560f63d45 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: use current char to determine `col` in `DocView:get_x_offset_col` + +## Description + +Previously it would use the last char position, which resulted in incorrect values when the next char had a different size than the current one. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64420f4366a2`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1946/solution/patch.diff b/tasks/lite-xl__lite-xl-1946/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1b0160313fc164e75f30ee5d92cd2c2368bd0bdb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/data/core/docview.lua b/data/core/docview.lua +index 2dfd76d8..808bf318 100644 +--- a/data/core/docview.lua ++++ b/data/core/docview.lua +@@ -203,7 +203,7 @@ end + function DocView:get_x_offset_col(line, x) + local line_text = self.doc.lines[line] + +- local xoffset, last_i, i = 0, 1, 1 ++ local xoffset, i = 0, 1 + local default_font = self:get_font() + local _, indent_size = self.doc:get_indent_info() + default_font:set_tab_size(indent_size) +@@ -219,11 +219,10 @@ function DocView:get_x_offset_col(line, x) + else + for char in common.utf8_chars(text) do + local w = font:get_width(char, {tab_offset = xoffset}) +- if xoffset >= x then +- return (xoffset - x > w / 2) and last_i or i ++ if xoffset + w >= x then ++ return (x <= xoffset + (w / 2)) and i or i + #char + end + xoffset = xoffset + w +- last_i = i + i = i + #char + end + end diff --git a/tasks/lite-xl__lite-xl-1946/solution/solve.sh b/tasks/lite-xl__lite-xl-1946/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/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/lite-xl__lite-xl-1946/task.toml b/tasks/lite-xl__lite-xl-1946/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..409dec136ec634b8c3c4ba8980ccfcc910312026 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1946" +description = "fix: use current char to determine `col` in `DocView:get_x_offset_col`" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "64420f4366a290b3c3f48f0131a8f77312def595" +reference = "https://github.com/lite-xl/lite-xl/pull/1946" +source_access = "auto" +built_at = "2026-11-16T16:09:56.301734+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d33bc9781a97d3163226152ed2321ddbd35e7f18b7978cac4558070b0db2d0e1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T15:03:52Z" +diff_format = "unified" +context_files = [ + "data/core/docview.lua", +] +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:01.310364+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7858ce982589567d3de0af6c82e43e5251e9f6b7c457595b9aeca323bc83bf38" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1946/tests/capture.py b/tasks/lite-xl__lite-xl-1946/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/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/lite-xl__lite-xl-1946/tests/instruction.md b/tasks/lite-xl__lite-xl-1946/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13edad13999d5027324b65b6d6b8a0d560f63d45 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: use current char to determine `col` in `DocView:get_x_offset_col` + +## Description + +Previously it would use the last char position, which resulted in incorrect values when the next char had a different size than the current one. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `64420f4366a2`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1946/tests/oracle.patch b/tasks/lite-xl__lite-xl-1946/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1b0160313fc164e75f30ee5d92cd2c2368bd0bdb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/data/core/docview.lua b/data/core/docview.lua +index 2dfd76d8..808bf318 100644 +--- a/data/core/docview.lua ++++ b/data/core/docview.lua +@@ -203,7 +203,7 @@ end + function DocView:get_x_offset_col(line, x) + local line_text = self.doc.lines[line] + +- local xoffset, last_i, i = 0, 1, 1 ++ local xoffset, i = 0, 1 + local default_font = self:get_font() + local _, indent_size = self.doc:get_indent_info() + default_font:set_tab_size(indent_size) +@@ -219,11 +219,10 @@ function DocView:get_x_offset_col(line, x) + else + for char in common.utf8_chars(text) do + local w = font:get_width(char, {tab_offset = xoffset}) +- if xoffset >= x then +- return (xoffset - x > w / 2) and last_i or i ++ if xoffset + w >= x then ++ return (x <= xoffset + (w / 2)) and i or i + #char + end + xoffset = xoffset + w +- last_i = i + i = i + #char + end + end diff --git a/tasks/lite-xl__lite-xl-1946/tests/test.sh b/tasks/lite-xl__lite-xl-1946/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..58430a6bed3ceeea2b9e1bd8125ee134fe56e090 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/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 64420f4366a290b3c3f48f0131a8f77312def595 > "$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/lite-xl__lite-xl-1946/tests/verifier.py b/tasks/lite-xl__lite-xl-1946/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1946/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/lite-xl__lite-xl-1948/environment/Dockerfile b/tasks/lite-xl__lite-xl-1948/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66e29408ae768851994a0b7c83e4d28997071c1b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c15910856a2340db471c5ed9f0a09d5d36d775d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c15910856a2340db471c5ed9f0a09d5d36d775d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c15910856a2340db471c5ed9f0a09d5d36d775d8 \ + && 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/lite-xl__lite-xl-1948/instruction.md b/tasks/lite-xl__lite-xl-1948/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f47411915eee274c62f35ace6d216993db6c8da3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix multiple continuous release binaries + +## Description + +This PR removes unused Lua patching code and fixes the continuous releases having old binaries from previous runs. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c15910856a23`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1948/solution/patch.diff b/tasks/lite-xl__lite-xl-1948/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bae96ab66e06cf2b8a6e616b0d31e90b9ee2c3ff --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/solution/patch.diff @@ -0,0 +1,278 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 154676ca..4b9eff42 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -29,6 +29,8 @@ jobs: + outputs: + release: ${{ steps.check_release.outputs.release }} + ref: ${{ steps.check_release.outputs.ref }} ++ permissions: ++ contents: write + steps: + - name: Update Tag + uses: richardsimko/update-tag@v1 +@@ -58,10 +60,8 @@ jobs: + strategy: + matrix: + config: +- - { runner: macos-13, type: bundle, arch: x86_64-darwin } +- - { runner: macos-13, type: portable, arch: x86_64-darwin } +- - { runner: macos-14, type: bundle, arch: aarch64-darwin } +- - { runner: macos-14, type: portable, arch: aarch64-darwin } ++ - { runner: macos-13, arch: x86_64-darwin } ++ - { runner: macos-14, arch: aarch64-darwin } + runs-on: ${{ matrix.config.runner }} + steps: + - name: System Information +@@ -80,24 +80,23 @@ jobs: + - name: Install Dependencies + run: scripts/install-dependencies.sh + +- - name: Build +- run: scripts/build.sh --addons --debug --forcefallback --${{ matrix.config.type }} -b build +- +- - name: Package Mac (Bundle) +- if: ${{ matrix.config.type == 'bundle' }} +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}}-${{ matrix.config.type }}.tar.gz lite-xl Info.plist ++ - name: Build & Package Mac (Bundle) ++ run: | ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --bundle -b build ++ tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-bundle.tar.gz lite-xl Info.plist + +- - name: Package Mac (Portable) +- if: ${{ matrix.config.type == 'portable' }} +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}}-${{ matrix.config.type }}.tar.gz lite-xl ++ - name: Build & Package Mac (Portable) ++ run: | ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --portable -b build ++ tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-portable.tar.gz lite-xl + + - name: Upload (Intermediate) + uses: actions/upload-artifact@v4 + with: +- name: lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-${{ matrix.config.type }} ++ name: lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }} + path: | + *.tar.gz +- ++ + + build_darwin_universal: + name: Darwin (Universal) +@@ -117,12 +116,14 @@ jobs: + uses: actions/download-artifact@v4 + with: + pattern: '*darwin*' ++ merge-multiple: true + + - name: Create Universal Binaries + run: | + for TYPE in bundle portable; do +- mkdir -p lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl +- cd lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE && tar -zxvf *.tar.gz && cd .. && cd lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE && tar -zxvf *.tar.gz && cd .. ++ mkdir -p lite-xl-${{ needs.version.outputs.ref }}-{x86_64,aarch64,universal}-darwin-$TYPE/lite-xl ++ tar -C lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE -zxvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE.tar.gz ++ tar -C lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE -zxvf lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE.tar.gz + cp -r lite-xl-${{ needs.version.outputs.ref }}-*-$TYPE/lite-xl/data lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl + lipo -create -output lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl/lite-xl lite-xl-${{ needs.version.outputs.ref }}-*-darwin-$TYPE/lite-xl/lite-xl + done +@@ -139,8 +140,8 @@ jobs: + with: + name: lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-release + path: | +- *.dmg +- *.tar.gz ++ lite-xl-${{ needs.version.outputs.ref }}-universal-darwin.dmg ++ lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable.tar.gz + + + build_linux: +@@ -187,7 +188,7 @@ jobs: + run: bash scripts/install-dependencies.sh + + - name: Build +- run: bash scripts/build.sh -U --addons --debug --forcefallback --portable -b build ++ run: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + + - name: Package Windows (Portable) + run: cd build && zip -r ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows-portable.zip lite-xl && cd .. +@@ -203,6 +204,7 @@ jobs: + *.zip + *.exe + ++ + build_windows_msvc: + name: Windows (x86_64) (MSVC) + needs: [version] +@@ -222,25 +224,15 @@ jobs: + - name: Install meson and ninja + run: pip install meson ninja + +- - name: Set up environment variables +- run: | +- "LUA_SUBPROJECT_PATH=subprojects/$(awk -F ' *= *' '/directory/ { printf $2 }' subprojects/lua.wrap)" >> $env:GITHUB_ENV +- +- - name: Download subprojects +- shell: bash +- run: | +- meson subprojects download +- + - name: Configure + run: meson setup --wrap-mode=forcefallback build + + - name: Build +- run: meson install -C build --destdir="../lite-xl" ++ run: meson install -C build --skip-subprojects --destdir="../lite-xl" + + - name: Package +- run: | +- Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" +- Compress-Archive -Path lite-xl -DestinationPath "lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows.zip" ++ shell: powershell {0} ++ run: Compress-Archive -Path lite-xl -DestinationPath "lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows.zip" + + - name: Upload Artifacts (Intermediate) + uses: actions/upload-artifact@v4 +@@ -255,28 +247,31 @@ jobs: + name: Create Release + needs: [version, build_linux, build_windows, build_darwin_universal] + runs-on: ubuntu-latest ++ permissions: ++ contents: write + steps: + - uses: actions/checkout@v4 + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: + pattern: lite-xl-*-release +- path: . ++ merge-multiple: true ++ path: releases ++ - name: Generate Release Notes ++ if: needs.version.outputs.release ++ env: ++ GH_TOKEN: ${{ github.token }} ++ run: bash scripts/generate-release-notes.sh --version ${{ needs.version.outputs.release }} + - name: Versioned Release +- uses: softprops/action-gh-release@v2 ++ uses: ncipollo/release-action@v1 + if: ${{ needs.version.outputs.release }} + with: +- tag_name: ${{ needs.version.outputs.release }} ++ tag: ${{ needs.version.outputs.release }} + name: Lite XL ${{ needs.version.outputs.release }} + draft: true +- body_path: changelog.md +- generate_release_notes: true +- files: | +- */*.tar.gz +- */*.zip +- */*.exe +- */*.dmg +- */*.AppImage ++ allowUpdates: true ++ bodyFile: release-notes.md ++ artifacts: "releases/*.*" + - name: Update Tag + uses: richardsimko/update-tag@v1 + if: github.ref == 'refs/heads/master' +@@ -285,15 +280,13 @@ jobs: + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Continuous Release +- uses: softprops/action-gh-release@v2 ++ uses: ncipollo/release-action@v1 + if: github.ref == 'refs/heads/master' + with: + name: Lite XL Continuous Release +- tag_name: continuous ++ tag: continuous + prerelease: true +- files: | +- */*.tar.gz +- */*.zip +- */*.exe +- */*.dmg +- */*.AppImage ++ allowUpdates: true ++ removeArtifacts: true ++ generateReleaseNotes: true ++ artifacts: "releases/*.*" +diff --git a/scripts/build.sh b/scripts/build.sh +index 62873978..851342bf 100755 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -23,8 +23,9 @@ show_help() { + echo "-B --bundle Create an App bundle (macOS only)" + echo "-A --addons Add in addons" + echo "-P --portable Create a portable binary package." ++ echo "-r --reconfigure Tries to reuse the meson build directory, if possible." ++ echo " Default: Deletes the build directory and recreates it." + echo "-O --pgo Use profile guided optimizations (pgo)." +- echo "-U --windows-lua-utf Use the UTF8 patch for Lua." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." + echo " --cross-platform PLATFORM Cross compile for this platform." +@@ -49,13 +50,12 @@ main() { + local bundle + local portable + local pgo +- local patch_lua + local cross + local cross_platform + local cross_arch + local cross_file +- +- local lua_subproject_path ++ local reconfigure ++ local should_reconfigure + + for i in "$@"; do + case $i in +@@ -72,6 +72,10 @@ main() { + build_type="debug" + shift + ;; ++ -r|--reconfigure) ++ should_reconfigure=true ++ shift ++ ;; + --debug) + set -x + shift +@@ -105,10 +109,6 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; +- -U|--windows-lua-utf) +- patch_lua="true" +- shift +- ;; + --cross-arch) + cross="true" + cross_arch="$2" +@@ -186,12 +186,10 @@ main() { + export LDFLAGS="-mmacosx-version-min=$macos_version_min" + fi + +- rm -rf "${build_dir}" +- +- if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]]; then +- # download the subprojects so we can start patching before configure. +- # this will prevent reconfiguring the project. +- meson subprojects download ++ if [[ $should_reconfigure == true ]] && [[ -d "${build_dir}" ]]; then ++ reconfigure="--reconfigure" ++ elif [[ -d "${build_dir}" ]]; then ++ rm -rf "${build_dir}" + fi + + CFLAGS=$CFLAGS LDFLAGS=$LDFLAGS meson setup \ +@@ -203,6 +201,7 @@ main() { + $bundle \ + $portable \ + $pgo \ ++ $reconfigure + + meson compile -C "${build_dir}" + diff --git a/tasks/lite-xl__lite-xl-1948/solution/solve.sh b/tasks/lite-xl__lite-xl-1948/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/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/lite-xl__lite-xl-1948/task.toml b/tasks/lite-xl__lite-xl-1948/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..015c94b19e2e01daa9ab6a85b3cde47fa25f2a3a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1948" +description = "Fix multiple continuous release binaries" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c15910856a2340db471c5ed9f0a09d5d36d775d8" +reference = "https://github.com/lite-xl/lite-xl/pull/1948" +source_access = "auto" +built_at = "2026-11-16T16:09:56.198110+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6adc6cf4945767060250b214afe70067d65e05d5e0f21a58f37e1c59ae58832f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-16T06:10:24Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + "scripts/build.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 124 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.310838+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:40df5cd56f724af5798c61125b993ce27ff74d10054ba9b8c25b3e865da1e9af" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1948/tests/capture.py b/tasks/lite-xl__lite-xl-1948/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/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/lite-xl__lite-xl-1948/tests/instruction.md b/tasks/lite-xl__lite-xl-1948/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f47411915eee274c62f35ace6d216993db6c8da3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix multiple continuous release binaries + +## Description + +This PR removes unused Lua patching code and fixes the continuous releases having old binaries from previous runs. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c15910856a23`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1948/tests/oracle.patch b/tasks/lite-xl__lite-xl-1948/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bae96ab66e06cf2b8a6e616b0d31e90b9ee2c3ff --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/tests/oracle.patch @@ -0,0 +1,278 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 154676ca..4b9eff42 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -29,6 +29,8 @@ jobs: + outputs: + release: ${{ steps.check_release.outputs.release }} + ref: ${{ steps.check_release.outputs.ref }} ++ permissions: ++ contents: write + steps: + - name: Update Tag + uses: richardsimko/update-tag@v1 +@@ -58,10 +60,8 @@ jobs: + strategy: + matrix: + config: +- - { runner: macos-13, type: bundle, arch: x86_64-darwin } +- - { runner: macos-13, type: portable, arch: x86_64-darwin } +- - { runner: macos-14, type: bundle, arch: aarch64-darwin } +- - { runner: macos-14, type: portable, arch: aarch64-darwin } ++ - { runner: macos-13, arch: x86_64-darwin } ++ - { runner: macos-14, arch: aarch64-darwin } + runs-on: ${{ matrix.config.runner }} + steps: + - name: System Information +@@ -80,24 +80,23 @@ jobs: + - name: Install Dependencies + run: scripts/install-dependencies.sh + +- - name: Build +- run: scripts/build.sh --addons --debug --forcefallback --${{ matrix.config.type }} -b build +- +- - name: Package Mac (Bundle) +- if: ${{ matrix.config.type == 'bundle' }} +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}}-${{ matrix.config.type }}.tar.gz lite-xl Info.plist ++ - name: Build & Package Mac (Bundle) ++ run: | ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --bundle -b build ++ tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-bundle.tar.gz lite-xl Info.plist + +- - name: Package Mac (Portable) +- if: ${{ matrix.config.type == 'portable' }} +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}}-${{ matrix.config.type }}.tar.gz lite-xl ++ - name: Build & Package Mac (Portable) ++ run: | ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --portable -b build ++ tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-portable.tar.gz lite-xl + + - name: Upload (Intermediate) + uses: actions/upload-artifact@v4 + with: +- name: lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-${{ matrix.config.type }} ++ name: lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }} + path: | + *.tar.gz +- ++ + + build_darwin_universal: + name: Darwin (Universal) +@@ -117,12 +116,14 @@ jobs: + uses: actions/download-artifact@v4 + with: + pattern: '*darwin*' ++ merge-multiple: true + + - name: Create Universal Binaries + run: | + for TYPE in bundle portable; do +- mkdir -p lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl +- cd lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE && tar -zxvf *.tar.gz && cd .. && cd lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE && tar -zxvf *.tar.gz && cd .. ++ mkdir -p lite-xl-${{ needs.version.outputs.ref }}-{x86_64,aarch64,universal}-darwin-$TYPE/lite-xl ++ tar -C lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE -zxvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-darwin-$TYPE.tar.gz ++ tar -C lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE -zxvf lite-xl-${{ needs.version.outputs.ref }}-aarch64-darwin-$TYPE.tar.gz + cp -r lite-xl-${{ needs.version.outputs.ref }}-*-$TYPE/lite-xl/data lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl + lipo -create -output lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-$TYPE/lite-xl/lite-xl lite-xl-${{ needs.version.outputs.ref }}-*-darwin-$TYPE/lite-xl/lite-xl + done +@@ -139,8 +140,8 @@ jobs: + with: + name: lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-release + path: | +- *.dmg +- *.tar.gz ++ lite-xl-${{ needs.version.outputs.ref }}-universal-darwin.dmg ++ lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable.tar.gz + + + build_linux: +@@ -187,7 +188,7 @@ jobs: + run: bash scripts/install-dependencies.sh + + - name: Build +- run: bash scripts/build.sh -U --addons --debug --forcefallback --portable -b build ++ run: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + + - name: Package Windows (Portable) + run: cd build && zip -r ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows-portable.zip lite-xl && cd .. +@@ -203,6 +204,7 @@ jobs: + *.zip + *.exe + ++ + build_windows_msvc: + name: Windows (x86_64) (MSVC) + needs: [version] +@@ -222,25 +224,15 @@ jobs: + - name: Install meson and ninja + run: pip install meson ninja + +- - name: Set up environment variables +- run: | +- "LUA_SUBPROJECT_PATH=subprojects/$(awk -F ' *= *' '/directory/ { printf $2 }' subprojects/lua.wrap)" >> $env:GITHUB_ENV +- +- - name: Download subprojects +- shell: bash +- run: | +- meson subprojects download +- + - name: Configure + run: meson setup --wrap-mode=forcefallback build + + - name: Build +- run: meson install -C build --destdir="../lite-xl" ++ run: meson install -C build --skip-subprojects --destdir="../lite-xl" + + - name: Package +- run: | +- Remove-Item -Recurse -Force -Path "lite-xl/lib","lite-xl/include" +- Compress-Archive -Path lite-xl -DestinationPath "lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows.zip" ++ shell: powershell {0} ++ run: Compress-Archive -Path lite-xl -DestinationPath "lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows.zip" + + - name: Upload Artifacts (Intermediate) + uses: actions/upload-artifact@v4 +@@ -255,28 +247,31 @@ jobs: + name: Create Release + needs: [version, build_linux, build_windows, build_darwin_universal] + runs-on: ubuntu-latest ++ permissions: ++ contents: write + steps: + - uses: actions/checkout@v4 + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: + pattern: lite-xl-*-release +- path: . ++ merge-multiple: true ++ path: releases ++ - name: Generate Release Notes ++ if: needs.version.outputs.release ++ env: ++ GH_TOKEN: ${{ github.token }} ++ run: bash scripts/generate-release-notes.sh --version ${{ needs.version.outputs.release }} + - name: Versioned Release +- uses: softprops/action-gh-release@v2 ++ uses: ncipollo/release-action@v1 + if: ${{ needs.version.outputs.release }} + with: +- tag_name: ${{ needs.version.outputs.release }} ++ tag: ${{ needs.version.outputs.release }} + name: Lite XL ${{ needs.version.outputs.release }} + draft: true +- body_path: changelog.md +- generate_release_notes: true +- files: | +- */*.tar.gz +- */*.zip +- */*.exe +- */*.dmg +- */*.AppImage ++ allowUpdates: true ++ bodyFile: release-notes.md ++ artifacts: "releases/*.*" + - name: Update Tag + uses: richardsimko/update-tag@v1 + if: github.ref == 'refs/heads/master' +@@ -285,15 +280,13 @@ jobs: + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Continuous Release +- uses: softprops/action-gh-release@v2 ++ uses: ncipollo/release-action@v1 + if: github.ref == 'refs/heads/master' + with: + name: Lite XL Continuous Release +- tag_name: continuous ++ tag: continuous + prerelease: true +- files: | +- */*.tar.gz +- */*.zip +- */*.exe +- */*.dmg +- */*.AppImage ++ allowUpdates: true ++ removeArtifacts: true ++ generateReleaseNotes: true ++ artifacts: "releases/*.*" +diff --git a/scripts/build.sh b/scripts/build.sh +index 62873978..851342bf 100755 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -23,8 +23,9 @@ show_help() { + echo "-B --bundle Create an App bundle (macOS only)" + echo "-A --addons Add in addons" + echo "-P --portable Create a portable binary package." ++ echo "-r --reconfigure Tries to reuse the meson build directory, if possible." ++ echo " Default: Deletes the build directory and recreates it." + echo "-O --pgo Use profile guided optimizations (pgo)." +- echo "-U --windows-lua-utf Use the UTF8 patch for Lua." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." + echo " --cross-platform PLATFORM Cross compile for this platform." +@@ -49,13 +50,12 @@ main() { + local bundle + local portable + local pgo +- local patch_lua + local cross + local cross_platform + local cross_arch + local cross_file +- +- local lua_subproject_path ++ local reconfigure ++ local should_reconfigure + + for i in "$@"; do + case $i in +@@ -72,6 +72,10 @@ main() { + build_type="debug" + shift + ;; ++ -r|--reconfigure) ++ should_reconfigure=true ++ shift ++ ;; + --debug) + set -x + shift +@@ -105,10 +109,6 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; +- -U|--windows-lua-utf) +- patch_lua="true" +- shift +- ;; + --cross-arch) + cross="true" + cross_arch="$2" +@@ -186,12 +186,10 @@ main() { + export LDFLAGS="-mmacosx-version-min=$macos_version_min" + fi + +- rm -rf "${build_dir}" +- +- if [[ $patch_lua == "true" ]] && [[ ! -z $force_fallback ]]; then +- # download the subprojects so we can start patching before configure. +- # this will prevent reconfiguring the project. +- meson subprojects download ++ if [[ $should_reconfigure == true ]] && [[ -d "${build_dir}" ]]; then ++ reconfigure="--reconfigure" ++ elif [[ -d "${build_dir}" ]]; then ++ rm -rf "${build_dir}" + fi + + CFLAGS=$CFLAGS LDFLAGS=$LDFLAGS meson setup \ +@@ -203,6 +201,7 @@ main() { + $bundle \ + $portable \ + $pgo \ ++ $reconfigure + + meson compile -C "${build_dir}" + diff --git a/tasks/lite-xl__lite-xl-1948/tests/test.sh b/tasks/lite-xl__lite-xl-1948/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f47ade685743e83882e91dee294774572b2d18fa --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/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 c15910856a2340db471c5ed9f0a09d5d36d775d8 > "$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/lite-xl__lite-xl-1948/tests/verifier.py b/tasks/lite-xl__lite-xl-1948/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1948/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/lite-xl__lite-xl-1950/environment/Dockerfile b/tasks/lite-xl__lite-xl-1950/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9abc6667278eaf4c605d9c2da753ec546b088d71 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7d457f8fc5ed44558bd2f8241c21f67a31ec14dd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7d457f8fc5ed44558bd2f8241c21f67a31ec14dd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7d457f8fc5ed44558bd2f8241c21f67a31ec14dd \ + && 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/lite-xl__lite-xl-1950/instruction.md b/tasks/lite-xl__lite-xl-1950/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a748055ec4a188fb14e325c431d6a3cfb5a619a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Remove install-dependencies.sh + +## Description + +We've discussed this before and the conclusion is that listing out the dependencies is more preferrable instead of having a script automagically install them for you. + +The thing is that the script is never gonna support multiple package-managers, etc, can be outdated easily (it still installs dependencies with apt and we've already move on to build-box with manylinux (yum)), and is generally not very transparent unless the user knows where to find them. + +This PR lists out the dependencies in the README, as well as remove mentions to `build-package.sh` as that script is removed. it also lists out the dependencies directly in the CI. + +. +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7d457f8fc5ed`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1950/solution/patch.diff b/tasks/lite-xl__lite-xl-1950/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c3e5a78b90337982e79a738d14325117e30aa6bd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/solution/patch.diff @@ -0,0 +1,247 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 4b9eff42..976270ff 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -78,7 +78,9 @@ jobs: + with: { python-version: "3.11" } + + - name: Install Dependencies +- run: scripts/install-dependencies.sh ++ run: | ++ brew install bash ++ pip3 install meson ninja + + - name: Build & Package Mac (Bundle) + run: | +@@ -110,7 +112,9 @@ jobs: + with: { python-version: "3.11" } + + - name: Install Dependencies +- run: scripts/install-dependencies.sh ++ run: | ++ brew install bash ++ pip3 install dmgbuild + + - name: Download Artifacts + uses: actions/download-artifact@v4 +@@ -148,19 +152,23 @@ jobs: + name: Linux (x86_64) + needs: [version] + runs-on: ubuntu-latest +- env: +- BUILDER: docker run -v .:/build -w /build ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 -- /entrypoint.sh + steps: + - uses: actions/checkout@v4 + + - name: Build +- run: $BUILDER scripts/build.sh --addons --debug --forcefallback --portable -b build ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3 ++ with: ++ entrypoint: /entrypoint.sh ++ args: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + + - name: Package Linux (Portable) +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl && cd .. ++ run: tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl + + - name: Package Linux (AppImage) +- run: $BUILDER scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3 ++ with: ++ entrypoint: /entrypoint.sh ++ run: bash scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build + + - name: Upload (Release) + uses: actions/upload-artifact@v4 +@@ -180,13 +188,21 @@ jobs: + needs: [version] + steps: + - uses: msys2/setup-msys2@v2 +- with: { msystem: MINGW64 } +- ++ with: ++ msystem: MINGW64 ++ install: >- ++ git ++ zip ++ patch ++ pacboy: >- ++ gcc:p ++ meson:p ++ ca-certificates:p ++ ninja:p ++ pkg-config:p ++ + - uses: actions/checkout@v4 + +- - name: Install Dependencies +- run: bash scripts/install-dependencies.sh +- + - name: Build + run: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + +diff --git a/README.md b/README.md +index 0dceeb46..fcb19735 100644 +--- a/README.md ++++ b/README.md +@@ -45,19 +45,85 @@ These color themes are bundled with all releases of Lite XL by default. + + ## Quick Build Guide + +-If you compile Lite XL yourself, it is recommended to use the script +-`build-packages.sh`: ++To compile Lite XL yourself, you must have the following dependencies installed ++via your desired package manager, or manually. ++ ++### Prerequisites ++ ++- Meson (>=0.63) ++- Ninja ++- SDL2 ++- PCRE2 ++- FreeType2 ++- Lua 5.4 ++- A working C compiler (GCC / Clang / MSVC) ++ ++SDL2, PCRE2, FreeType2 and Lua will be downloaded by Meson ++if `--wrap-mode=forcefallback` or `--wrap-mode=default` is specified. ++ ++> [!NOTE] ++> MSVC is used in the CI, but MSVC-compiled binaries are not distributed officially ++> or tested extensively for bugs. ++ ++On Linux, you may install the following dependencies for the SDL2 X11 and/or Wayland backend to work properly: ++ ++- `libX11-devel` ++- `libXi-devel` ++- `libXcursor-devel` ++- `libxkbcommon-devel` ++- `libXrandr-devel` ++- `wayland-devel` ++- `wayland-protocols-devel` ++- `dbus-devel` ++- `ibus-devel` ++ ++The following command can be used to install the dependencies in Ubuntu: + + ```sh +-bash build-packages.sh -h ++apt-get install python3.8 python3-pip build-essential git cmake wayland-protocols libsdl2-dev ++pip3 install meson ninja + ``` + +-The script will run Meson and create a tar compressed archive with the application or, +-for Windows, a zip file. Lite XL can be easily installed +-by unpacking the archive in any directory of your choice. ++Please refer to [lite-xl-build-box] for a working Linux build environment used to package official Lite XL releases. ++ ++On macOS, you must install bash via Brew, as the default bash version on macOS is antiquated ++and may not run the build script correctly. ++ ++### Building ++ ++You can use `scripts/build.sh` to set up Lite XL and build it. ++ ++```sh ++$ bash build.sh --help ++# Usage: scripts/build.sh ++# ++# Available options: ++# ++# -b --builddir DIRNAME Sets the name of the build directory (not path). ++# Default: 'build-x86_64-linux'. ++# --debug Debug this script. ++# -f --forcefallback Force to build dependencies statically. ++# -h --help Show this help and exit. ++# -d --debug-build Builds a debug build. ++# -p --prefix PREFIX Install directory prefix. Default: '/'. ++# -B --bundle Create an App bundle (macOS only) ++# -A --addons Add in addons ++# -P --portable Create a portable binary package. ++# -r --reconfigure Tries to reuse the meson build directory, if possible. ++# Default: Deletes the build directory and recreates it. ++# -O --pgo Use profile guided optimizations (pgo). ++# macOS: disabled when used with --bundle, ++# Windows: Implicit being the only option. ++# --cross-platform PLATFORM Cross compile for this platform. ++# The script will find the appropriate ++# cross file in 'resources/cross'. ++# --cross-arch ARCH Cross compile for this architecture. ++# The script will find the appropriate ++# cross file in 'resources/cross'. ++# --cross-file CROSS_FILE Cross compile with the given cross file. ++``` + +-Otherwise the following is an example of basic commands if you want to customize +-the build: ++Alternatively, you can use the following commands to customize the build: + + ```sh + meson setup --buildtype=release --prefix build +@@ -237,3 +303,4 @@ See the [licenses] file for details on licenses used by the required dependencie + [colors repository]: https://github.com/lite-xl/lite-xl-colors + [LICENSE]: LICENSE + [licenses]: licenses/licenses.md ++[lite-xl-build-box]: https://github.com/lite-xl/lite-xl-build-box +\ No newline at end of file +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +deleted file mode 100755 +index 41e4f7ae..00000000 +--- a/scripts/install-dependencies.sh ++++ /dev/null +@@ -1,55 +0,0 @@ +-#!/bin/bash +-set -ex +- +-if [ ! -e "src/api/api.h" ]; then +- echo "Please run this script from the root directory of Lite XL."; exit 1 +-fi +- +-show_help() { +- echo +- echo "Lite XL dependecies installer. Mainly used for CI but can also work on users systems." +- echo "USE IT AT YOUR OWN RISK!" +- echo +- echo "Usage: $0 " +- echo +- echo "Available options:" +- echo +- echo " --debug Debug this script." +- echo +-} +- +-main() { +- for i in "$@"; do +- case $i in +- -s|--lhelper) +- echo "error: support for lhelper has been deprecated" >> /dev/stderr +- exit 1 +- ;; +- --debug) +- set -x +- shift +- ;; +- *) +- # unknown option +- ;; +- esac +- done +- +- if [[ -n $1 ]]; then +- show_help +- exit 1 +- fi +- +- if [[ "$OSTYPE" == "linux"* ]]; then +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 desktop-file-utils +- pip3 install meson +- elif [[ "$OSTYPE" == "darwin"* ]]; then +- brew install bash ninja sdl2 +- pip3 install meson dmgbuild +- elif [[ "$OSTYPE" == "msys" ]]; then +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip patch zip +- fi +-} +- +-main "$@" diff --git a/tasks/lite-xl__lite-xl-1950/solution/solve.sh b/tasks/lite-xl__lite-xl-1950/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/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/lite-xl__lite-xl-1950/task.toml b/tasks/lite-xl__lite-xl-1950/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffdd90e710b4e06edd88261cc40a0710fa0cdf0c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1950" +description = "Remove install-dependencies.sh" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "7d457f8fc5ed44558bd2f8241c21f67a31ec14dd" +reference = "https://github.com/lite-xl/lite-xl/pull/1950" +source_access = "auto" +built_at = "2026-11-16T16:09:56.196517+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d4dc837028bbe18547f8caac9ec90b4a17dd9aea69f63653863adb5d7d624a3a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-25T12:32:21Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + "README.md", + "scripts/install-dependencies.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 178 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.311311+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3fa0bcdd6cb6a0f4962f3af72a93345986501b89c9c2374d33a828d794aa6020" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1950/tests/capture.py b/tasks/lite-xl__lite-xl-1950/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/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/lite-xl__lite-xl-1950/tests/instruction.md b/tasks/lite-xl__lite-xl-1950/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a748055ec4a188fb14e325c431d6a3cfb5a619a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Remove install-dependencies.sh + +## Description + +We've discussed this before and the conclusion is that listing out the dependencies is more preferrable instead of having a script automagically install them for you. + +The thing is that the script is never gonna support multiple package-managers, etc, can be outdated easily (it still installs dependencies with apt and we've already move on to build-box with manylinux (yum)), and is generally not very transparent unless the user knows where to find them. + +This PR lists out the dependencies in the README, as well as remove mentions to `build-package.sh` as that script is removed. it also lists out the dependencies directly in the CI. + +. +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7d457f8fc5ed`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1950/tests/oracle.patch b/tasks/lite-xl__lite-xl-1950/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c3e5a78b90337982e79a738d14325117e30aa6bd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/tests/oracle.patch @@ -0,0 +1,247 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 4b9eff42..976270ff 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -78,7 +78,9 @@ jobs: + with: { python-version: "3.11" } + + - name: Install Dependencies +- run: scripts/install-dependencies.sh ++ run: | ++ brew install bash ++ pip3 install meson ninja + + - name: Build & Package Mac (Bundle) + run: | +@@ -110,7 +112,9 @@ jobs: + with: { python-version: "3.11" } + + - name: Install Dependencies +- run: scripts/install-dependencies.sh ++ run: | ++ brew install bash ++ pip3 install dmgbuild + + - name: Download Artifacts + uses: actions/download-artifact@v4 +@@ -148,19 +152,23 @@ jobs: + name: Linux (x86_64) + needs: [version] + runs-on: ubuntu-latest +- env: +- BUILDER: docker run -v .:/build -w /build ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3.0.2 -- /entrypoint.sh + steps: + - uses: actions/checkout@v4 + + - name: Build +- run: $BUILDER scripts/build.sh --addons --debug --forcefallback --portable -b build ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3 ++ with: ++ entrypoint: /entrypoint.sh ++ args: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + + - name: Package Linux (Portable) +- run: cd build && tar -czvf ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl && cd .. ++ run: tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl + + - name: Package Linux (AppImage) +- run: $BUILDER scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build ++ uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v3 ++ with: ++ entrypoint: /entrypoint.sh ++ run: bash scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build + + - name: Upload (Release) + uses: actions/upload-artifact@v4 +@@ -180,13 +188,21 @@ jobs: + needs: [version] + steps: + - uses: msys2/setup-msys2@v2 +- with: { msystem: MINGW64 } +- ++ with: ++ msystem: MINGW64 ++ install: >- ++ git ++ zip ++ patch ++ pacboy: >- ++ gcc:p ++ meson:p ++ ca-certificates:p ++ ninja:p ++ pkg-config:p ++ + - uses: actions/checkout@v4 + +- - name: Install Dependencies +- run: bash scripts/install-dependencies.sh +- + - name: Build + run: bash scripts/build.sh --addons --debug --forcefallback --portable -b build + +diff --git a/README.md b/README.md +index 0dceeb46..fcb19735 100644 +--- a/README.md ++++ b/README.md +@@ -45,19 +45,85 @@ These color themes are bundled with all releases of Lite XL by default. + + ## Quick Build Guide + +-If you compile Lite XL yourself, it is recommended to use the script +-`build-packages.sh`: ++To compile Lite XL yourself, you must have the following dependencies installed ++via your desired package manager, or manually. ++ ++### Prerequisites ++ ++- Meson (>=0.63) ++- Ninja ++- SDL2 ++- PCRE2 ++- FreeType2 ++- Lua 5.4 ++- A working C compiler (GCC / Clang / MSVC) ++ ++SDL2, PCRE2, FreeType2 and Lua will be downloaded by Meson ++if `--wrap-mode=forcefallback` or `--wrap-mode=default` is specified. ++ ++> [!NOTE] ++> MSVC is used in the CI, but MSVC-compiled binaries are not distributed officially ++> or tested extensively for bugs. ++ ++On Linux, you may install the following dependencies for the SDL2 X11 and/or Wayland backend to work properly: ++ ++- `libX11-devel` ++- `libXi-devel` ++- `libXcursor-devel` ++- `libxkbcommon-devel` ++- `libXrandr-devel` ++- `wayland-devel` ++- `wayland-protocols-devel` ++- `dbus-devel` ++- `ibus-devel` ++ ++The following command can be used to install the dependencies in Ubuntu: + + ```sh +-bash build-packages.sh -h ++apt-get install python3.8 python3-pip build-essential git cmake wayland-protocols libsdl2-dev ++pip3 install meson ninja + ``` + +-The script will run Meson and create a tar compressed archive with the application or, +-for Windows, a zip file. Lite XL can be easily installed +-by unpacking the archive in any directory of your choice. ++Please refer to [lite-xl-build-box] for a working Linux build environment used to package official Lite XL releases. ++ ++On macOS, you must install bash via Brew, as the default bash version on macOS is antiquated ++and may not run the build script correctly. ++ ++### Building ++ ++You can use `scripts/build.sh` to set up Lite XL and build it. ++ ++```sh ++$ bash build.sh --help ++# Usage: scripts/build.sh ++# ++# Available options: ++# ++# -b --builddir DIRNAME Sets the name of the build directory (not path). ++# Default: 'build-x86_64-linux'. ++# --debug Debug this script. ++# -f --forcefallback Force to build dependencies statically. ++# -h --help Show this help and exit. ++# -d --debug-build Builds a debug build. ++# -p --prefix PREFIX Install directory prefix. Default: '/'. ++# -B --bundle Create an App bundle (macOS only) ++# -A --addons Add in addons ++# -P --portable Create a portable binary package. ++# -r --reconfigure Tries to reuse the meson build directory, if possible. ++# Default: Deletes the build directory and recreates it. ++# -O --pgo Use profile guided optimizations (pgo). ++# macOS: disabled when used with --bundle, ++# Windows: Implicit being the only option. ++# --cross-platform PLATFORM Cross compile for this platform. ++# The script will find the appropriate ++# cross file in 'resources/cross'. ++# --cross-arch ARCH Cross compile for this architecture. ++# The script will find the appropriate ++# cross file in 'resources/cross'. ++# --cross-file CROSS_FILE Cross compile with the given cross file. ++``` + +-Otherwise the following is an example of basic commands if you want to customize +-the build: ++Alternatively, you can use the following commands to customize the build: + + ```sh + meson setup --buildtype=release --prefix build +@@ -237,3 +303,4 @@ See the [licenses] file for details on licenses used by the required dependencie + [colors repository]: https://github.com/lite-xl/lite-xl-colors + [LICENSE]: LICENSE + [licenses]: licenses/licenses.md ++[lite-xl-build-box]: https://github.com/lite-xl/lite-xl-build-box +\ No newline at end of file +diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh +deleted file mode 100755 +index 41e4f7ae..00000000 +--- a/scripts/install-dependencies.sh ++++ /dev/null +@@ -1,55 +0,0 @@ +-#!/bin/bash +-set -ex +- +-if [ ! -e "src/api/api.h" ]; then +- echo "Please run this script from the root directory of Lite XL."; exit 1 +-fi +- +-show_help() { +- echo +- echo "Lite XL dependecies installer. Mainly used for CI but can also work on users systems." +- echo "USE IT AT YOUR OWN RISK!" +- echo +- echo "Usage: $0 " +- echo +- echo "Available options:" +- echo +- echo " --debug Debug this script." +- echo +-} +- +-main() { +- for i in "$@"; do +- case $i in +- -s|--lhelper) +- echo "error: support for lhelper has been deprecated" >> /dev/stderr +- exit 1 +- ;; +- --debug) +- set -x +- shift +- ;; +- *) +- # unknown option +- ;; +- esac +- done +- +- if [[ -n $1 ]]; then +- show_help +- exit 1 +- fi +- +- if [[ "$OSTYPE" == "linux"* ]]; then +- sudo apt-get install -qq libfuse2 ninja-build wayland-protocols libsdl2-dev libfreetype6 desktop-file-utils +- pip3 install meson +- elif [[ "$OSTYPE" == "darwin"* ]]; then +- brew install bash ninja sdl2 +- pip3 install meson dmgbuild +- elif [[ "$OSTYPE" == "msys" ]]; then +- pacman --noconfirm -S \ +- ${MINGW_PACKAGE_PREFIX}-{ca-certificates,gcc,meson,ninja,ntldd,pkg-config,mesa,freetype,pcre2,SDL2} unzip patch zip +- fi +-} +- +-main "$@" diff --git a/tasks/lite-xl__lite-xl-1950/tests/test.sh b/tasks/lite-xl__lite-xl-1950/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..419304db9210e53deba8d70b18bc3bcf7daa6067 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/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 7d457f8fc5ed44558bd2f8241c21f67a31ec14dd > "$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/lite-xl__lite-xl-1950/tests/verifier.py b/tasks/lite-xl__lite-xl-1950/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1950/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/lite-xl__lite-xl-1953/environment/Dockerfile b/tasks/lite-xl__lite-xl-1953/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2b5c007dd58485c54be74ecc6a07351a0eb8a3ee --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 75261a98a6723ce734360c0a3004c9e5cab04540 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 75261a98a6723ce734360c0a3004c9e5cab04540 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 75261a98a6723ce734360c0a3004c9e5cab04540 \ + && 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/lite-xl__lite-xl-1953/instruction.md b/tasks/lite-xl__lite-xl-1953/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02a9c9fe021c877580908387b2ba64f686c14e2b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** EmptyView no keybinding for commands bug + +## Description + +This PR is a rewrite of `EmptyView:draw()` + +issue #1952 +There was no error-handling for when one of the commands displayed on EmptyView did not have an associated keybinding. + +unfortunately, it was not as simple as adding a `if keybinding ~= nil` because the position of commands being displayed needs to change based on the number of commands in order for the logo to look balanced. + +Which means the rendering of the logo had to be dynamic based on the number of commands being displayed. + +Which means `:draw()` needs to be rewritten: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `75261a98a672`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1953/solution/patch.diff b/tasks/lite-xl__lite-xl-1953/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d7d14260a945accce22697f9a256bd8fdbbbf975 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/solution/patch.diff @@ -0,0 +1,95 @@ +diff --git a/data/core/emptyview.lua b/data/core/emptyview.lua +index 50e03b1f..64bfecf7 100644 +--- a/data/core/emptyview.lua ++++ b/data/core/emptyview.lua +@@ -17,47 +17,52 @@ function EmptyView:get_filename() + return "" + end + +-local function draw_text(x, y, color) +- local lines = { +- { fmt = "%s to run a command", cmd = "core:find-command" }, +- { fmt = "%s to open a file from the project", cmd = "core:find-file" }, +- { fmt = "%s to change project folder", cmd = "core:change-project-folder" }, +- { fmt = "%s to open a project folder", cmd = "core:open-project-folder" }, +- } +- local th = style.big_font:get_height() +- local dh = 2 * th + style.padding.y * 2 +- local x1, y1 = x, y + ((dh - th) / #lines) +- local xv = x1 +- local title = "Lite XL" +- local version = "version " .. VERSION +- local title_width = style.big_font:get_width(title) +- local version_width = style.font:get_width(version) +- if version_width > title_width then +- version = VERSION +- version_width = style.font:get_width(version) +- xv = x1 - (version_width - title_width) +- end +- x = renderer.draw_text(style.big_font, title, x1, y1, color) +- renderer.draw_text(style.font, version, xv, y1 + th, color) +- x = x + style.padding.x +- renderer.draw_rect(x, y, math.ceil(1 * SCALE), dh, color) +- th = style.font:get_height() +- y = y + (dh - (th + style.padding.y) * #lines) / 2 +- local w = 0 +- for _, line in ipairs(lines) do +- local text = string.format(line.fmt, keymap.get_binding(line.cmd)) +- w = math.max(w, renderer.draw_text(style.font, text, x + style.padding.x, y, color)) +- y = y + th + style.padding.y +- end +- return w, dh +-end ++EmptyView.commands = { ++ { fmt = "%s to run a command", cmd = "core:find-command" }, ++ { fmt = "%s to open a file from the project", cmd = "core:find-file" }, ++ { fmt = "%s to change project folder", cmd = "core:change-project-folder" }, ++ { fmt = "%s to open a project folder", cmd = "core:open-project-folder" }, ++} + + function EmptyView:draw() + self:draw_background(style.background) +- local w, h = draw_text(0, 0, { 0, 0, 0, 0 }) +- local x = self.position.x + math.max(style.padding.x, (self.size.x - w) / 2) +- local y = self.position.y + (self.size.y - h) / 2 +- draw_text(x, y, style.dim) ++ -- x,y center-point ++ local x = self.position.x + self.size.x / 2 ++ local y = self.position.y + self.size.y / 2 ++ local divider_w = math.ceil(1 * SCALE) ++ local cmds_x = x + math.ceil(divider_w /2) + style.padding.x ++ local logo_right_side = x - math.ceil(divider_w/2) - style.padding.x ++ ++ local displayed_cmds = {} ++ for _, command in ipairs(self.commands) do ++ local keybinding = keymap.get_binding(command.cmd) ++ if keybinding ~= nil then ++ table.insert(displayed_cmds,{ ++ fmt = command.fmt, ++ keybinding = keybinding ++ }) ++ end ++ end ++ local cmd_h = style.font:get_height() + style.padding.y ++ local cmds_y = y - ((cmd_h * #displayed_cmds)/2) ++ for i, cmd in ipairs(displayed_cmds) do ++ local cmd_text = string.format(cmd.fmt, cmd.keybinding) ++ renderer.draw_text(style.font, cmd_text, cmds_x, cmds_y + cmd_h*(i-1), style.dim) ++ end ++ ++ local title = "Lite XL" ++ local version = VERSION ++ local logo_h = style.big_font:get_height(title) ++ local logo_y = y - logo_h + logo_h/4 ++ local logo_x = logo_right_side - style.big_font:get_width(title) ++ local vers_x = logo_right_side - style.font:get_width(version) ++ local vers_y = y + logo_h/8 ++ renderer.draw_text(style.big_font, title, logo_x, logo_y, style.dim) ++ renderer.draw_text(style.font, version, vers_x, vers_y, style.dim) ++ ++ local divider_y = math.min(cmds_y, logo_y) - style.padding.y ++ local divider_h = (y - divider_y)*2 ++ renderer.draw_rect(x - divider_w/2, divider_y, divider_w, divider_h, style.dim) + end + + return EmptyView diff --git a/tasks/lite-xl__lite-xl-1953/solution/solve.sh b/tasks/lite-xl__lite-xl-1953/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/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/lite-xl__lite-xl-1953/task.toml b/tasks/lite-xl__lite-xl-1953/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97b23cff210398abc7005a635e27349f895d55c5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1953" +description = "EmptyView no keybinding for commands bug" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "75261a98a6723ce734360c0a3004c9e5cab04540" +reference = "https://github.com/lite-xl/lite-xl/pull/1953" +source_access = "auto" +built_at = "2026-11-16T16:09:56.150785+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:83e637709fd963d0ac326dda0b916814a7e0574b9d6a5c26270c0175a96af636" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-11-23T17:14:46Z" +diff_format = "unified" +context_files = [ + "data/core/emptyview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 81 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.311763+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f21368c21a152415950c5cd339f69eb05cbcfda5ea2a66524a17675d0a099206" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1953/tests/capture.py b/tasks/lite-xl__lite-xl-1953/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/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/lite-xl__lite-xl-1953/tests/instruction.md b/tasks/lite-xl__lite-xl-1953/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02a9c9fe021c877580908387b2ba64f686c14e2b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** EmptyView no keybinding for commands bug + +## Description + +This PR is a rewrite of `EmptyView:draw()` + +issue #1952 +There was no error-handling for when one of the commands displayed on EmptyView did not have an associated keybinding. + +unfortunately, it was not as simple as adding a `if keybinding ~= nil` because the position of commands being displayed needs to change based on the number of commands in order for the logo to look balanced. + +Which means the rendering of the logo had to be dynamic based on the number of commands being displayed. + +Which means `:draw()` needs to be rewritten: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `75261a98a672`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1953/tests/oracle.patch b/tasks/lite-xl__lite-xl-1953/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d7d14260a945accce22697f9a256bd8fdbbbf975 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/tests/oracle.patch @@ -0,0 +1,95 @@ +diff --git a/data/core/emptyview.lua b/data/core/emptyview.lua +index 50e03b1f..64bfecf7 100644 +--- a/data/core/emptyview.lua ++++ b/data/core/emptyview.lua +@@ -17,47 +17,52 @@ function EmptyView:get_filename() + return "" + end + +-local function draw_text(x, y, color) +- local lines = { +- { fmt = "%s to run a command", cmd = "core:find-command" }, +- { fmt = "%s to open a file from the project", cmd = "core:find-file" }, +- { fmt = "%s to change project folder", cmd = "core:change-project-folder" }, +- { fmt = "%s to open a project folder", cmd = "core:open-project-folder" }, +- } +- local th = style.big_font:get_height() +- local dh = 2 * th + style.padding.y * 2 +- local x1, y1 = x, y + ((dh - th) / #lines) +- local xv = x1 +- local title = "Lite XL" +- local version = "version " .. VERSION +- local title_width = style.big_font:get_width(title) +- local version_width = style.font:get_width(version) +- if version_width > title_width then +- version = VERSION +- version_width = style.font:get_width(version) +- xv = x1 - (version_width - title_width) +- end +- x = renderer.draw_text(style.big_font, title, x1, y1, color) +- renderer.draw_text(style.font, version, xv, y1 + th, color) +- x = x + style.padding.x +- renderer.draw_rect(x, y, math.ceil(1 * SCALE), dh, color) +- th = style.font:get_height() +- y = y + (dh - (th + style.padding.y) * #lines) / 2 +- local w = 0 +- for _, line in ipairs(lines) do +- local text = string.format(line.fmt, keymap.get_binding(line.cmd)) +- w = math.max(w, renderer.draw_text(style.font, text, x + style.padding.x, y, color)) +- y = y + th + style.padding.y +- end +- return w, dh +-end ++EmptyView.commands = { ++ { fmt = "%s to run a command", cmd = "core:find-command" }, ++ { fmt = "%s to open a file from the project", cmd = "core:find-file" }, ++ { fmt = "%s to change project folder", cmd = "core:change-project-folder" }, ++ { fmt = "%s to open a project folder", cmd = "core:open-project-folder" }, ++} + + function EmptyView:draw() + self:draw_background(style.background) +- local w, h = draw_text(0, 0, { 0, 0, 0, 0 }) +- local x = self.position.x + math.max(style.padding.x, (self.size.x - w) / 2) +- local y = self.position.y + (self.size.y - h) / 2 +- draw_text(x, y, style.dim) ++ -- x,y center-point ++ local x = self.position.x + self.size.x / 2 ++ local y = self.position.y + self.size.y / 2 ++ local divider_w = math.ceil(1 * SCALE) ++ local cmds_x = x + math.ceil(divider_w /2) + style.padding.x ++ local logo_right_side = x - math.ceil(divider_w/2) - style.padding.x ++ ++ local displayed_cmds = {} ++ for _, command in ipairs(self.commands) do ++ local keybinding = keymap.get_binding(command.cmd) ++ if keybinding ~= nil then ++ table.insert(displayed_cmds,{ ++ fmt = command.fmt, ++ keybinding = keybinding ++ }) ++ end ++ end ++ local cmd_h = style.font:get_height() + style.padding.y ++ local cmds_y = y - ((cmd_h * #displayed_cmds)/2) ++ for i, cmd in ipairs(displayed_cmds) do ++ local cmd_text = string.format(cmd.fmt, cmd.keybinding) ++ renderer.draw_text(style.font, cmd_text, cmds_x, cmds_y + cmd_h*(i-1), style.dim) ++ end ++ ++ local title = "Lite XL" ++ local version = VERSION ++ local logo_h = style.big_font:get_height(title) ++ local logo_y = y - logo_h + logo_h/4 ++ local logo_x = logo_right_side - style.big_font:get_width(title) ++ local vers_x = logo_right_side - style.font:get_width(version) ++ local vers_y = y + logo_h/8 ++ renderer.draw_text(style.big_font, title, logo_x, logo_y, style.dim) ++ renderer.draw_text(style.font, version, vers_x, vers_y, style.dim) ++ ++ local divider_y = math.min(cmds_y, logo_y) - style.padding.y ++ local divider_h = (y - divider_y)*2 ++ renderer.draw_rect(x - divider_w/2, divider_y, divider_w, divider_h, style.dim) + end + + return EmptyView diff --git a/tasks/lite-xl__lite-xl-1953/tests/test.sh b/tasks/lite-xl__lite-xl-1953/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..21709da644b8aacbee7588a57092c3813fe82000 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/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 75261a98a6723ce734360c0a3004c9e5cab04540 > "$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/lite-xl__lite-xl-1953/tests/verifier.py b/tasks/lite-xl__lite-xl-1953/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1953/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/lite-xl__lite-xl-1965/environment/Dockerfile b/tasks/lite-xl__lite-xl-1965/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4eaff8e957ff6f01c13134e27ca31b64f584f20b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3fe64609e70c98a6606968312d34827dc32f2ad4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3fe64609e70c98a6606968312d34827dc32f2ad4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3fe64609e70c98a6606968312d34827dc32f2ad4 \ + && 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/lite-xl__lite-xl-1965/instruction.md b/tasks/lite-xl__lite-xl-1965/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c46f979329dbc94925b9c2995a2d546c5a07a5bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** meson: reformat lua patch using git + +## Description + +meson tries to use `git apply` when `patch` isn't available, which is a way stricter patch implementation and will complain about the slightest inconsistency though generally ensures that you get the exact thing that you want + +I've applied the patch to a raw wrapdb lua download and reformatted it using it to apply cleanly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fe64609e70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1965/solution/patch.diff b/tasks/lite-xl__lite-xl-1965/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..53538e1e8e8ea152138f20296cb5bde700765e1b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/solution/patch.diff @@ -0,0 +1,119 @@ +diff --git a/subprojects/packagefiles/lua/lua-unicode.diff b/subprojects/packagefiles/lua/lua-unicode.diff +index f7dbc74e..7547bde2 100644 +--- a/subprojects/packagefiles/lua/lua-unicode.diff ++++ b/subprojects/packagefiles/lua/lua-unicode.diff +@@ -1,7 +1,24 @@ +-diff -ruN lua-5.4.6/meson.build lua-5.4.6-patched/meson.build +---- lua-5.4.6/meson.build Wed Feb 22 18:16:56 2023 +-+++ lua-5.4.6-patched/meson.build Wed Feb 22 04:10:01 2023 +-@@ -85,6 +85,7 @@ ++From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 ++From: Jan200101 ++Date: Fri, 29 Nov 2024 08:19:27 +0100 ++Subject: [PATCH] add utf8 wrapper ++ ++Signed-off-by: Jan200101 ++--- ++ meson.build | 1 + ++ src/Makefile | 2 +- ++ src/luaconf.h | 10 ++++ ++ src/utf8_wrappers.c | 129 ++++++++++++++++++++++++++++++++++++++++++++ ++ src/utf8_wrappers.h | 46 ++++++++++++++++ ++ 5 files changed, 187 insertions(+), 1 deletion(-) ++ create mode 100644 src/utf8_wrappers.c ++ create mode 100644 src/utf8_wrappers.h ++ ++diff --git a/meson.build b/meson.build ++index ffd115c..31efb31 100644 ++--- a/meson.build +++++ b/meson.build ++@@ -82,6 +82,7 @@ lua_lib = library( + 'src/lutf8lib.c', + 'src/lvm.c', + 'src/lzio.c', +@@ -9,13 +26,27 @@ diff -ruN lua-5.4.6/meson.build lua-5.4.6-patched/meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.6/src/luaconf.h lua-5.4.6-patched/src/luaconf.h +---- lua-5.4.6/src/luaconf.h Thu Jan 13 19:24:43 2022 +-+++ lua-5.4.6-patched/src/luaconf.h Wed Feb 22 04:10:02 2023 +-@@ -782,5 +782,15 @@ +- +- +- ++diff --git a/src/Makefile b/src/Makefile ++index b771196..6d3ff24 100644 ++--- a/src/Makefile +++++ b/src/Makefile ++@@ -33,7 +33,7 @@ CMCFLAGS= ++ PLATS= guess aix bsd c89 freebsd generic ios linux linux-readline macosx mingw posix solaris ++ ++ LUA_A= liblua.a ++-CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +++CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o ++ LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o ++ BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) ++ ++diff --git a/src/luaconf.h b/src/luaconf.h ++index 137103e..3cd0d53 100644 ++--- a/src/luaconf.h +++++ b/src/luaconf.h ++@@ -789,5 +789,15 @@ ++ ++ ++ + +#if defined(lua_c) || defined(luac_c) || (defined(LUA_LIB) && \ + + (defined(lauxlib_c) || defined(liolib_c) || \ + + defined(loadlib_c) || defined(loslib_c))) +@@ -27,22 +58,12 @@ diff -ruN lua-5.4.6/src/luaconf.h lua-5.4.6-patched/src/luaconf.h + + + + + #endif +- +-diff -ruN lua-5.4.6/src/Makefile lua-5.4.6-patched/src/Makefile +---- lua-5.4.6/src/Makefile Thu Jul 15 22:01:52 2021 +-+++ lua-5.4.6-patched/src/Makefile Wed Feb 22 04:10:02 2023 +-@@ -33,7 +33,7 @@ +- PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris +- +- LUA_A= liblua.a +--CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +-+CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o +- LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o +- BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) +- +-diff -ruN lua-5.4.6/src/utf8_wrappers.c lua-5.4.6-patched/src/utf8_wrappers.c +---- lua-5.4.6/src/utf8_wrappers.c Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.6-patched/src/utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++ ++diff --git a/src/utf8_wrappers.c b/src/utf8_wrappers.c ++new file mode 100644 ++index 0000000..5b9b1f6 ++--- /dev/null +++++ b/src/utf8_wrappers.c + @@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -173,9 +194,11 @@ diff -ruN lua-5.4.6/src/utf8_wrappers.c lua-5.4.6-patched/src/utf8_wrappers.c + + return env_value; + +} + +#endif +-diff -ruN lua-5.4.6/src/utf8_wrappers.h lua-5.4.6-patched/src/utf8_wrappers.h +---- lua-5.4.6/src/utf8_wrappers.h Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.6-patched/src/utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++diff --git a/src/utf8_wrappers.h b/src/utf8_wrappers.h ++new file mode 100644 ++index 0000000..22e853f ++--- /dev/null +++++ b/src/utf8_wrappers.h + @@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -223,3 +246,6 @@ diff -ruN lua-5.4.6/src/utf8_wrappers.h lua-5.4.6-patched/src/utf8_wrappers.h + +#define LoadLibraryExA LoadLibraryExA_utf8 + +#endif + +#endif ++-- ++2.47.0 ++ diff --git a/tasks/lite-xl__lite-xl-1965/solution/solve.sh b/tasks/lite-xl__lite-xl-1965/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/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/lite-xl__lite-xl-1965/task.toml b/tasks/lite-xl__lite-xl-1965/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..99193d1fa850d435494ec729309e0a40776e4ccb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1965" +description = "meson: reformat lua patch using git" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "3fe64609e70c98a6606968312d34827dc32f2ad4" +reference = "https://github.com/lite-xl/lite-xl/pull/1965" +source_access = "auto" +built_at = "2026-11-16T16:09:56.319861+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9c2b89e3d3c85b5e5d57521fd10bcf7570d5e34b008173cf9fffd99c1b2e6105" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-11-29T07:38:07Z" +diff_format = "unified" +context_files = [ + "subprojects/packagefiles/lua/lua-unicode.diff", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 86 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.312236+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6e54b49771a5975ee0238c2ffb7f850a57377b4eeca2efd37f8000032637c5ce" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1965/tests/capture.py b/tasks/lite-xl__lite-xl-1965/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/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/lite-xl__lite-xl-1965/tests/instruction.md b/tasks/lite-xl__lite-xl-1965/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c46f979329dbc94925b9c2995a2d546c5a07a5bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** meson: reformat lua patch using git + +## Description + +meson tries to use `git apply` when `patch` isn't available, which is a way stricter patch implementation and will complain about the slightest inconsistency though generally ensures that you get the exact thing that you want + +I've applied the patch to a raw wrapdb lua download and reformatted it using it to apply cleanly + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fe64609e70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1965/tests/oracle.patch b/tasks/lite-xl__lite-xl-1965/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..53538e1e8e8ea152138f20296cb5bde700765e1b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/tests/oracle.patch @@ -0,0 +1,119 @@ +diff --git a/subprojects/packagefiles/lua/lua-unicode.diff b/subprojects/packagefiles/lua/lua-unicode.diff +index f7dbc74e..7547bde2 100644 +--- a/subprojects/packagefiles/lua/lua-unicode.diff ++++ b/subprojects/packagefiles/lua/lua-unicode.diff +@@ -1,7 +1,24 @@ +-diff -ruN lua-5.4.6/meson.build lua-5.4.6-patched/meson.build +---- lua-5.4.6/meson.build Wed Feb 22 18:16:56 2023 +-+++ lua-5.4.6-patched/meson.build Wed Feb 22 04:10:01 2023 +-@@ -85,6 +85,7 @@ ++From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 ++From: Jan200101 ++Date: Fri, 29 Nov 2024 08:19:27 +0100 ++Subject: [PATCH] add utf8 wrapper ++ ++Signed-off-by: Jan200101 ++--- ++ meson.build | 1 + ++ src/Makefile | 2 +- ++ src/luaconf.h | 10 ++++ ++ src/utf8_wrappers.c | 129 ++++++++++++++++++++++++++++++++++++++++++++ ++ src/utf8_wrappers.h | 46 ++++++++++++++++ ++ 5 files changed, 187 insertions(+), 1 deletion(-) ++ create mode 100644 src/utf8_wrappers.c ++ create mode 100644 src/utf8_wrappers.h ++ ++diff --git a/meson.build b/meson.build ++index ffd115c..31efb31 100644 ++--- a/meson.build +++++ b/meson.build ++@@ -82,6 +82,7 @@ lua_lib = library( + 'src/lutf8lib.c', + 'src/lvm.c', + 'src/lzio.c', +@@ -9,13 +26,27 @@ diff -ruN lua-5.4.6/meson.build lua-5.4.6-patched/meson.build + dependencies: lua_lib_deps, + version: meson.project_version(), + soversion: lua_versions[0] + '.' + lua_versions[1], +-diff -ruN lua-5.4.6/src/luaconf.h lua-5.4.6-patched/src/luaconf.h +---- lua-5.4.6/src/luaconf.h Thu Jan 13 19:24:43 2022 +-+++ lua-5.4.6-patched/src/luaconf.h Wed Feb 22 04:10:02 2023 +-@@ -782,5 +782,15 @@ +- +- +- ++diff --git a/src/Makefile b/src/Makefile ++index b771196..6d3ff24 100644 ++--- a/src/Makefile +++++ b/src/Makefile ++@@ -33,7 +33,7 @@ CMCFLAGS= ++ PLATS= guess aix bsd c89 freebsd generic ios linux linux-readline macosx mingw posix solaris ++ ++ LUA_A= liblua.a ++-CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +++CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o ++ LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o ++ BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) ++ ++diff --git a/src/luaconf.h b/src/luaconf.h ++index 137103e..3cd0d53 100644 ++--- a/src/luaconf.h +++++ b/src/luaconf.h ++@@ -789,5 +789,15 @@ ++ ++ ++ + +#if defined(lua_c) || defined(luac_c) || (defined(LUA_LIB) && \ + + (defined(lauxlib_c) || defined(liolib_c) || \ + + defined(loadlib_c) || defined(loslib_c))) +@@ -27,22 +58,12 @@ diff -ruN lua-5.4.6/src/luaconf.h lua-5.4.6-patched/src/luaconf.h + + + + + #endif +- +-diff -ruN lua-5.4.6/src/Makefile lua-5.4.6-patched/src/Makefile +---- lua-5.4.6/src/Makefile Thu Jul 15 22:01:52 2021 +-+++ lua-5.4.6-patched/src/Makefile Wed Feb 22 04:10:02 2023 +-@@ -33,7 +33,7 @@ +- PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris +- +- LUA_A= liblua.a +--CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o +-+CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o utf8_wrappers.o +- LIB_O= lauxlib.o lbaselib.o lcorolib.o ldblib.o liolib.o lmathlib.o loadlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o linit.o +- BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS) +- +-diff -ruN lua-5.4.6/src/utf8_wrappers.c lua-5.4.6-patched/src/utf8_wrappers.c +---- lua-5.4.6/src/utf8_wrappers.c Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.6-patched/src/utf8_wrappers.c Wed Feb 22 18:13:45 2023 ++ ++diff --git a/src/utf8_wrappers.c b/src/utf8_wrappers.c ++new file mode 100644 ++index 0000000..5b9b1f6 ++--- /dev/null +++++ b/src/utf8_wrappers.c + @@ -0,0 +1,129 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -173,9 +194,11 @@ diff -ruN lua-5.4.6/src/utf8_wrappers.c lua-5.4.6-patched/src/utf8_wrappers.c + + return env_value; + +} + +#endif +-diff -ruN lua-5.4.6/src/utf8_wrappers.h lua-5.4.6-patched/src/utf8_wrappers.h +---- lua-5.4.6/src/utf8_wrappers.h Thu Jan 01 08:00:00 1970 +-+++ lua-5.4.6-patched/src/utf8_wrappers.h Wed Feb 22 18:09:48 2023 ++diff --git a/src/utf8_wrappers.h b/src/utf8_wrappers.h ++new file mode 100644 ++index 0000000..22e853f ++--- /dev/null +++++ b/src/utf8_wrappers.h + @@ -0,0 +1,46 @@ + +/** + + * Wrappers to provide Unicode (UTF-8) support on Windows. +@@ -223,3 +246,6 @@ diff -ruN lua-5.4.6/src/utf8_wrappers.h lua-5.4.6-patched/src/utf8_wrappers.h + +#define LoadLibraryExA LoadLibraryExA_utf8 + +#endif + +#endif ++-- ++2.47.0 ++ diff --git a/tasks/lite-xl__lite-xl-1965/tests/test.sh b/tasks/lite-xl__lite-xl-1965/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee216001a34603b41dbc01e93b6991f13d1a45e9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/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 3fe64609e70c98a6606968312d34827dc32f2ad4 > "$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/lite-xl__lite-xl-1965/tests/verifier.py b/tasks/lite-xl__lite-xl-1965/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1965/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/lite-xl__lite-xl-1969/environment/Dockerfile b/tasks/lite-xl__lite-xl-1969/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0209f6096db622a03ea91fa386fdb23d038f88 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fd5472356f4166a7aa145c80480b7c6e543d3194 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fd5472356f4166a7aa145c80480b7c6e543d3194 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fd5472356f4166a7aa145c80480b7c6e543d3194 \ + && 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/lite-xl__lite-xl-1969/instruction.md b/tasks/lite-xl__lite-xl-1969/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3cb9fd17167fb7ab0a0acd0b17fb0ead779aec09 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: scale font pixel size in `RENDERER` mode + +## 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 `fd5472356f41`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1969/solution/patch.diff b/tasks/lite-xl__lite-xl-1969/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..224b74997f1e98ad549c32f5a1ed62e86dcce8a2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 38ed486a..4aa5eb1e 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -396,7 +396,11 @@ static void font_file_close(FT_Stream stream) { + + static int font_set_face_metrics(RenFont *font, FT_Face face) { + FT_Error err; +- if ((err = FT_Set_Pixel_Sizes(face, 0, (int) font->size)) != 0) ++ float pixel_size = font->size; ++ #ifdef LITE_USE_SDL_RENDERER ++ pixel_size *= font->scale; ++ #endif ++ if ((err = FT_Set_Pixel_Sizes(face, 0, (int) pixel_size)) != 0) + return err; + + font->face = face; diff --git a/tasks/lite-xl__lite-xl-1969/solution/solve.sh b/tasks/lite-xl__lite-xl-1969/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/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/lite-xl__lite-xl-1969/task.toml b/tasks/lite-xl__lite-xl-1969/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0d0f86592b15c7e03082af448051bf7a76184f77 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1969" +description = "fix: scale font pixel size in `RENDERER` mode" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "fd5472356f4166a7aa145c80480b7c6e543d3194" +reference = "https://github.com/lite-xl/lite-xl/pull/1969" +source_access = "auto" +built_at = "2026-11-16T16:09:56.318518+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bfc07d6a704c86258cb471c622431d85e44ea65d674e35f890f16ab930fa489f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-02T07:19:28Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.312705+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e0878c4a3449fb744ae8bfdf62ad5e860f24eac7c00ed17a642bc41666488532" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1969/tests/capture.py b/tasks/lite-xl__lite-xl-1969/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/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/lite-xl__lite-xl-1969/tests/instruction.md b/tasks/lite-xl__lite-xl-1969/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3cb9fd17167fb7ab0a0acd0b17fb0ead779aec09 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: scale font pixel size in `RENDERER` mode + +## 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 `fd5472356f41`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1969/tests/oracle.patch b/tasks/lite-xl__lite-xl-1969/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..224b74997f1e98ad549c32f5a1ed62e86dcce8a2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/src/renderer.c b/src/renderer.c +index 38ed486a..4aa5eb1e 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -396,7 +396,11 @@ static void font_file_close(FT_Stream stream) { + + static int font_set_face_metrics(RenFont *font, FT_Face face) { + FT_Error err; +- if ((err = FT_Set_Pixel_Sizes(face, 0, (int) font->size)) != 0) ++ float pixel_size = font->size; ++ #ifdef LITE_USE_SDL_RENDERER ++ pixel_size *= font->scale; ++ #endif ++ if ((err = FT_Set_Pixel_Sizes(face, 0, (int) pixel_size)) != 0) + return err; + + font->face = face; diff --git a/tasks/lite-xl__lite-xl-1969/tests/test.sh b/tasks/lite-xl__lite-xl-1969/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..462b405bf8c3889e68e8e8f7c21a9ed753905a64 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/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 fd5472356f4166a7aa145c80480b7c6e543d3194 > "$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/lite-xl__lite-xl-1969/tests/verifier.py b/tasks/lite-xl__lite-xl-1969/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1969/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/lite-xl__lite-xl-1971/environment/Dockerfile b/tasks/lite-xl__lite-xl-1971/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb0209f6096db622a03ea91fa386fdb23d038f88 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fd5472356f4166a7aa145c80480b7c6e543d3194 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fd5472356f4166a7aa145c80480b7c6e543d3194 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fd5472356f4166a7aa145c80480b7c6e543d3194 \ + && 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/lite-xl__lite-xl-1971/instruction.md b/tasks/lite-xl__lite-xl-1971/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fbeb7f60572a20193b0e628b7dd1eec84fb789e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** docview: prevent overscroll when DocView size is less than lh * 2 + +## Description + +. + +This also fixes lite-xl-widgets when used with unbounded scroll. + +[Screencast_20241201_212608.webm](https://github.com/user-attachments/assets/8de4ffe4-d775-4961-9997-0b07531b9ccc) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fd5472356f41`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1971/solution/patch.diff b/tasks/lite-xl__lite-xl-1971/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..af0426da9c509352a18dfb763c3bc45f2cabfc2b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/data/core/docview.lua b/data/core/docview.lua +index 6ab86fc6..baf4b81f 100644 +--- a/data/core/docview.lua ++++ b/data/core/docview.lua +@@ -264,7 +264,8 @@ function DocView:scroll_to_make_visible(line, col) + local _, ly = self:get_line_screen_position(line, col) + local lh = self:get_line_height() + local _, _, _, scroll_h = self.h_scrollbar:get_track_rect() +- self.scroll.to.y = common.clamp(self.scroll.to.y, ly - oy - self.size.y + scroll_h + lh * 2, ly - oy - lh) ++ local overscroll = math.min(lh * 2, self.size.y) -- always show the previous / next line when possible ++ self.scroll.to.y = common.clamp(self.scroll.to.y, ly - oy - self.size.y + scroll_h + overscroll, ly - oy - lh) + local gw = self:get_gutter_width() + local xoffset = self:get_col_x_offset(line, col) + local xmargin = 3 * self:get_font():get_width(' ') diff --git a/tasks/lite-xl__lite-xl-1971/solution/solve.sh b/tasks/lite-xl__lite-xl-1971/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/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/lite-xl__lite-xl-1971/task.toml b/tasks/lite-xl__lite-xl-1971/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5638ec63c43542b4b3bb0a161c5112738eaefcb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1971" +description = "docview: prevent overscroll when DocView size is less than lh * 2" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "fd5472356f4166a7aa145c80480b7c6e543d3194" +reference = "https://github.com/lite-xl/lite-xl/pull/1971" +source_access = "auto" +built_at = "2026-11-16T16:09:56.194993+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fb5eb67bcd08ec0339ae22ac47550a410a829fff0c078da61fb54c969beddbd6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-02T22:45:27Z" +diff_format = "unified" +context_files = [ + "data/core/docview.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.313176+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e0878c4a3449fb744ae8bfdf62ad5e860f24eac7c00ed17a642bc41666488532" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1971/tests/capture.py b/tasks/lite-xl__lite-xl-1971/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/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/lite-xl__lite-xl-1971/tests/instruction.md b/tasks/lite-xl__lite-xl-1971/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fbeb7f60572a20193b0e628b7dd1eec84fb789e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** docview: prevent overscroll when DocView size is less than lh * 2 + +## Description + +. + +This also fixes lite-xl-widgets when used with unbounded scroll. + +[Screencast_20241201_212608.webm](https://github.com/user-attachments/assets/8de4ffe4-d775-4961-9997-0b07531b9ccc) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fd5472356f41`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1971/tests/oracle.patch b/tasks/lite-xl__lite-xl-1971/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..af0426da9c509352a18dfb763c3bc45f2cabfc2b --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/data/core/docview.lua b/data/core/docview.lua +index 6ab86fc6..baf4b81f 100644 +--- a/data/core/docview.lua ++++ b/data/core/docview.lua +@@ -264,7 +264,8 @@ function DocView:scroll_to_make_visible(line, col) + local _, ly = self:get_line_screen_position(line, col) + local lh = self:get_line_height() + local _, _, _, scroll_h = self.h_scrollbar:get_track_rect() +- self.scroll.to.y = common.clamp(self.scroll.to.y, ly - oy - self.size.y + scroll_h + lh * 2, ly - oy - lh) ++ local overscroll = math.min(lh * 2, self.size.y) -- always show the previous / next line when possible ++ self.scroll.to.y = common.clamp(self.scroll.to.y, ly - oy - self.size.y + scroll_h + overscroll, ly - oy - lh) + local gw = self:get_gutter_width() + local xoffset = self:get_col_x_offset(line, col) + local xmargin = 3 * self:get_font():get_width(' ') diff --git a/tasks/lite-xl__lite-xl-1971/tests/test.sh b/tasks/lite-xl__lite-xl-1971/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..462b405bf8c3889e68e8e8f7c21a9ed753905a64 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/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 fd5472356f4166a7aa145c80480b7c6e543d3194 > "$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/lite-xl__lite-xl-1971/tests/verifier.py b/tasks/lite-xl__lite-xl-1971/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1971/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/lite-xl__lite-xl-1973/environment/Dockerfile b/tasks/lite-xl__lite-xl-1973/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..10e0d614cb95fd425eed1f1fe21b0156e2ec52fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 36db156371ac702add371ffd20869f0a894c7865 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 36db156371ac702add371ffd20869f0a894c7865 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 36db156371ac702add371ffd20869f0a894c7865 \ + && 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/lite-xl__lite-xl-1973/instruction.md b/tasks/lite-xl__lite-xl-1973/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e217b9d8af1a96c0f6f84363ec382059db75f2c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** process: do not return nil until process exited + +## Description + +This is a very weird Windows-specific regression. +Currently, when we call read_stdout or read_stderr repeatedly, the function returns these three distinct results: + +1. `""`: We read something +2. `""`: There is no data available / stream is closed (EOF) +3. nil: An error occured or the process has exited and we hit EOF + +This is a weird status quo, but well, killing the process when stream closes is _not good_, and I am not here to rethink the design. + +On Windows, this is not the case due to how ReadFile and OVERLAPPED IO works. + +On Linux: +```c +read() == 2, errno == 0 // read 2 +read() == -1, errno == EAGAIN // stream has no data +read() == 2, errno == 0 // read 2 +read() == 0, errno == 0 // stream hits EOF +``` + +On Windows: +```c +(1) ReadFile() == true, dwBytesTransferred == 2, GetLastError() == ERROR_SUCCESS // read 2 +(2) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_IO_PENDING // stream has no data +(3) GetOverlappedResult() == true, dwBytesTransferred == 2, overlapped.Internal = ERROR_SUCCESS // read 2 +(4) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_IO_PENDING // stream has no data +(5) GetOverlappedResult() == true, dwBytesTransferred == 0, GetLastError() == ERROR_EOF_HANDLE // stream hits EOF +(6) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_HANDLE_EOF // stream hits EOF +``` + +The code is somewhat equivalent, but on Windows OVERLAPPED IO operates on **completion**, so one can think of GetOverlappedResult() and ReadFile() can be merged into a single operation here. For that reason, the synchronous read branch is not shown. + +The problem lies in (5) and (6). When (5) fails with ERROR_EOF_HANDLE, Lite XL ignores this error code and pretends that it does a 0-size read. That's fine. But when (6) comes around, Lite XL thought that some other error has occured and kills the program. This is not the case on Linux: + +https://github.com/lite-xl/lite-xl/blob/36db156371ac702add371ffd20869f0a894c7865/src/api/process.c#L631-L639 + +On Linux, we only kill the process if we hit an actual pipe error, we never kill the process because we hit EOF. When we hit EOF, we continue to return an empty string until the process dies. + +On Windows: + +https://github.com/lite-xl/lite-xl/blob/36db156371ac702add371ffd20869f0a894c7865/src/api/process.c#L609-L626 + +The Windows code is really terse and hard to read, but the takeaway is the code will kill the process no matter what happened, as long as it didn't read a thing, like EOF. The function also don't return an empty string until the process actually dies, it also doesn't call `poll_process()` which causes an edge case of calling `process:returncode()` right after `read_stdout()` fails to **not work**. + +This PR emulates the POSIX behavior of calling poll_process when we hit EOF. This will fix the aforementioned edge case, and returns an empty string until the process actually exits. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `36db156371ac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1973/solution/patch.diff b/tasks/lite-xl__lite-xl-1973/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f6c33cc5c1d2e213e8f12a8ae610f525ddaabfc7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 50fe6e22..497663e0 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -615,7 +615,8 @@ static int g_read(lua_State* L, int stream, unsigned long read_size) { + length = bytesTransferred; + memset(&self->overlapped[writable_stream_idx], 0, sizeof(self->overlapped[writable_stream_idx])); + } +- } else { ++ } else if (GetLastError() != ERROR_HANDLE_EOF || !poll_process(self, WAIT_NONE)) { ++ // emulate POSIX behavior in the code below by returning empty string until process exits + signal_process(self, SIGNAL_TERM); + return 0; + } diff --git a/tasks/lite-xl__lite-xl-1973/solution/solve.sh b/tasks/lite-xl__lite-xl-1973/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/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/lite-xl__lite-xl-1973/task.toml b/tasks/lite-xl__lite-xl-1973/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9b4976c8fd2d8d1d8dcc9a20cede80ccc06543bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1973" +description = "process: do not return nil until process exited" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "36db156371ac702add371ffd20869f0a894c7865" +reference = "https://github.com/lite-xl/lite-xl/pull/1973" +source_access = "auto" +built_at = "2026-11-16T16:09:56.193502+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6730f303a2375bc7a16e5fe2c65565617386397f8850e93c1437525cd9bf75f3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-03T14:47:59Z" +diff_format = "unified" +context_files = [ + "src/api/process.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.313617+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:308609b7ee319e02e592190abb195c8b169caa35262598c766216a572b7572b0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1973/tests/capture.py b/tasks/lite-xl__lite-xl-1973/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/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/lite-xl__lite-xl-1973/tests/instruction.md b/tasks/lite-xl__lite-xl-1973/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e217b9d8af1a96c0f6f84363ec382059db75f2c3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/tests/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** process: do not return nil until process exited + +## Description + +This is a very weird Windows-specific regression. +Currently, when we call read_stdout or read_stderr repeatedly, the function returns these three distinct results: + +1. `""`: We read something +2. `""`: There is no data available / stream is closed (EOF) +3. nil: An error occured or the process has exited and we hit EOF + +This is a weird status quo, but well, killing the process when stream closes is _not good_, and I am not here to rethink the design. + +On Windows, this is not the case due to how ReadFile and OVERLAPPED IO works. + +On Linux: +```c +read() == 2, errno == 0 // read 2 +read() == -1, errno == EAGAIN // stream has no data +read() == 2, errno == 0 // read 2 +read() == 0, errno == 0 // stream hits EOF +``` + +On Windows: +```c +(1) ReadFile() == true, dwBytesTransferred == 2, GetLastError() == ERROR_SUCCESS // read 2 +(2) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_IO_PENDING // stream has no data +(3) GetOverlappedResult() == true, dwBytesTransferred == 2, overlapped.Internal = ERROR_SUCCESS // read 2 +(4) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_IO_PENDING // stream has no data +(5) GetOverlappedResult() == true, dwBytesTransferred == 0, GetLastError() == ERROR_EOF_HANDLE // stream hits EOF +(6) ReadFile() == false, dwBytesTransferred == 0, GetLastError() == ERROR_HANDLE_EOF // stream hits EOF +``` + +The code is somewhat equivalent, but on Windows OVERLAPPED IO operates on **completion**, so one can think of GetOverlappedResult() and ReadFile() can be merged into a single operation here. For that reason, the synchronous read branch is not shown. + +The problem lies in (5) and (6). When (5) fails with ERROR_EOF_HANDLE, Lite XL ignores this error code and pretends that it does a 0-size read. That's fine. But when (6) comes around, Lite XL thought that some other error has occured and kills the program. This is not the case on Linux: + +https://github.com/lite-xl/lite-xl/blob/36db156371ac702add371ffd20869f0a894c7865/src/api/process.c#L631-L639 + +On Linux, we only kill the process if we hit an actual pipe error, we never kill the process because we hit EOF. When we hit EOF, we continue to return an empty string until the process dies. + +On Windows: + +https://github.com/lite-xl/lite-xl/blob/36db156371ac702add371ffd20869f0a894c7865/src/api/process.c#L609-L626 + +The Windows code is really terse and hard to read, but the takeaway is the code will kill the process no matter what happened, as long as it didn't read a thing, like EOF. The function also don't return an empty string until the process actually dies, it also doesn't call `poll_process()` which causes an edge case of calling `process:returncode()` right after `read_stdout()` fails to **not work**. + +This PR emulates the POSIX behavior of calling poll_process when we hit EOF. This will fix the aforementioned edge case, and returns an empty string until the process actually exits. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `36db156371ac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1973/tests/oracle.patch b/tasks/lite-xl__lite-xl-1973/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f6c33cc5c1d2e213e8f12a8ae610f525ddaabfc7 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/src/api/process.c b/src/api/process.c +index 50fe6e22..497663e0 100644 +--- a/src/api/process.c ++++ b/src/api/process.c +@@ -615,7 +615,8 @@ static int g_read(lua_State* L, int stream, unsigned long read_size) { + length = bytesTransferred; + memset(&self->overlapped[writable_stream_idx], 0, sizeof(self->overlapped[writable_stream_idx])); + } +- } else { ++ } else if (GetLastError() != ERROR_HANDLE_EOF || !poll_process(self, WAIT_NONE)) { ++ // emulate POSIX behavior in the code below by returning empty string until process exits + signal_process(self, SIGNAL_TERM); + return 0; + } diff --git a/tasks/lite-xl__lite-xl-1973/tests/test.sh b/tasks/lite-xl__lite-xl-1973/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77a95f0c265b5ff7bca257b6808788ea8f1f98d1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/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 36db156371ac702add371ffd20869f0a894c7865 > "$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/lite-xl__lite-xl-1973/tests/verifier.py b/tasks/lite-xl__lite-xl-1973/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1973/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/lite-xl__lite-xl-1976/environment/Dockerfile b/tasks/lite-xl__lite-xl-1976/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..10e0d614cb95fd425eed1f1fe21b0156e2ec52fb --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 36db156371ac702add371ffd20869f0a894c7865 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 36db156371ac702add371ffd20869f0a894c7865 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 36db156371ac702add371ffd20869f0a894c7865 \ + && 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/lite-xl__lite-xl-1976/instruction.md b/tasks/lite-xl__lite-xl-1976/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..54fb09f861d1d8a06bc4f39bd4c0e720787db0ff --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: only allow backslash as path separator in Windows in `common.path_suggest` + +## Description + +Follow up from #1875. + +Avoid considering backslash as pathsep on non-windows, as backslashes are allowed in names. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `36db156371ac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1976/solution/patch.diff b/tasks/lite-xl__lite-xl-1976/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6e8a176dd1774a503ecf2689986e5059fe974f56 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/data/core/common.lua b/data/core/common.lua +index 9e4ea1a9..1a89f23f 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -226,7 +226,12 @@ function common.path_suggest(text, root) + if root and root:sub(-1) ~= PATHSEP then + root = root .. PATHSEP + end +- local path, name = text:match("^(.-)([^"..PATHSEP.."/]*)$") ++ ++ local pathsep = PATHSEP ++ if PLATFORM == "Windows" then ++ pathsep = "\\/" ++ end ++ local path = text:match("^(.-)[^"..pathsep.."]*$") + local clean_dotslash = false + -- ignore root if path is absolute + local is_absolute = common.is_absolute_path(text) diff --git a/tasks/lite-xl__lite-xl-1976/solution/solve.sh b/tasks/lite-xl__lite-xl-1976/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/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/lite-xl__lite-xl-1976/task.toml b/tasks/lite-xl__lite-xl-1976/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..816eaaef43d795e9113b4d60603b307b82e17c18 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1976" +description = "fix: only allow backslash as path separator in Windows in `common.path_suggest`" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "36db156371ac702add371ffd20869f0a894c7865" +reference = "https://github.com/lite-xl/lite-xl/pull/1976" +source_access = "auto" +built_at = "2026-11-16T16:09:56.314790+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3d2900be31241d3f27a18a6bed44d1e2fb1ed82e213f7c895c91241ceb185503" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-03T23:55:35Z" +diff_format = "unified" +context_files = [ + "data/core/common.lua", +] +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:01.314053+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:308609b7ee319e02e592190abb195c8b169caa35262598c766216a572b7572b0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1976/tests/capture.py b/tasks/lite-xl__lite-xl-1976/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/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/lite-xl__lite-xl-1976/tests/instruction.md b/tasks/lite-xl__lite-xl-1976/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..54fb09f861d1d8a06bc4f39bd4c0e720787db0ff --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix: only allow backslash as path separator in Windows in `common.path_suggest` + +## Description + +Follow up from #1875. + +Avoid considering backslash as pathsep on non-windows, as backslashes are allowed in names. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `36db156371ac`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1976/tests/oracle.patch b/tasks/lite-xl__lite-xl-1976/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6e8a176dd1774a503ecf2689986e5059fe974f56 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/data/core/common.lua b/data/core/common.lua +index 9e4ea1a9..1a89f23f 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -226,7 +226,12 @@ function common.path_suggest(text, root) + if root and root:sub(-1) ~= PATHSEP then + root = root .. PATHSEP + end +- local path, name = text:match("^(.-)([^"..PATHSEP.."/]*)$") ++ ++ local pathsep = PATHSEP ++ if PLATFORM == "Windows" then ++ pathsep = "\\/" ++ end ++ local path = text:match("^(.-)[^"..pathsep.."]*$") + local clean_dotslash = false + -- ignore root if path is absolute + local is_absolute = common.is_absolute_path(text) diff --git a/tasks/lite-xl__lite-xl-1976/tests/test.sh b/tasks/lite-xl__lite-xl-1976/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77a95f0c265b5ff7bca257b6808788ea8f1f98d1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/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 36db156371ac702add371ffd20869f0a894c7865 > "$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/lite-xl__lite-xl-1976/tests/verifier.py b/tasks/lite-xl__lite-xl-1976/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1976/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/lite-xl__lite-xl-1977/environment/Dockerfile b/tasks/lite-xl__lite-xl-1977/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9aac7db93f4d258156a59b46ff8be06cdd0de74 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 081215f5750d807a6f395268c4028e9061e93d0d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 081215f5750d807a6f395268c4028e9061e93d0d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 081215f5750d807a6f395268c4028e9061e93d0d \ + && 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/lite-xl__lite-xl-1977/instruction.md b/tasks/lite-xl__lite-xl-1977/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5f66a4d5d50c2daef93fd9409f9e22470bb6b1e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** ci: use tag name as artifact name + +## Description + +. + +This PR labels the continuous release with `continuous` instead of the tag generated by `git describe`. I didn't remove the tag outright so that it _might_ be easier to parse. It is sort of implied that the version field is also the tag name, just like how the CI is written. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `081215f5750d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1977/solution/patch.diff b/tasks/lite-xl__lite-xl-1977/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b4dc7425d8556be0ede15660099348c008eed997 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 5c85811a..ef403b3c 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -39,21 +39,24 @@ jobs: + tag_name: ${{ github.event.inputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true ++ + - name: Check Release + id: check_release + run: | +- export REF=`git describe --match v[0-9]* HEAD --tags` ++ REF=$(git describe --exact-match --match v[0-9]* HEAD --tags 2>/dev/null) || REF=continuous ++ echo "ref=$REF" >> $GITHUB_OUTPUT + echo "Build Version: $REF" +- [[ "$REF" != "" ]] && echo "ref=$REF" >> $GITHUB_OUTPUT +- if [[ `git describe --exact-match --match v[0-9]* HEAD --tags` ]]; then ++ if [[ "$REF" != "continuous" ]]; then + echo "release=$REF" >> $GITHUB_OUTPUT + echo "Release Version: $REF" + fi +- ++ ++ + build_darwin: + name: Darwin + needs: [version] diff --git a/tasks/lite-xl__lite-xl-1977/solution/solve.sh b/tasks/lite-xl__lite-xl-1977/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/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/lite-xl__lite-xl-1977/task.toml b/tasks/lite-xl__lite-xl-1977/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ec1805a93b3b3fe577098ccc8b201c522782d19 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1977" +description = "ci: use tag name as artifact name" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "081215f5750d807a6f395268c4028e9061e93d0d" +reference = "https://github.com/lite-xl/lite-xl/pull/1977" +source_access = "auto" +built_at = "2026-11-16T16:09:56.192001+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e484e64b3cbf4114985726a9b6b17657aae162f6831ed3e6cbe5d9de530a2354" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-04T00:27:11Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.314503+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9e60f14244b97ff92399d19e9f1e2b2690218198e3b29a47b2112b024f9717f1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1977/tests/capture.py b/tasks/lite-xl__lite-xl-1977/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/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/lite-xl__lite-xl-1977/tests/instruction.md b/tasks/lite-xl__lite-xl-1977/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5f66a4d5d50c2daef93fd9409f9e22470bb6b1e --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** ci: use tag name as artifact name + +## Description + +. + +This PR labels the continuous release with `continuous` instead of the tag generated by `git describe`. I didn't remove the tag outright so that it _might_ be easier to parse. It is sort of implied that the version field is also the tag name, just like how the CI is written. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `081215f5750d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1977/tests/oracle.patch b/tasks/lite-xl__lite-xl-1977/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b4dc7425d8556be0ede15660099348c008eed997 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 5c85811a..ef403b3c 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -39,21 +39,24 @@ jobs: + tag_name: ${{ github.event.inputs.version }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ++ + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true ++ + - name: Check Release + id: check_release + run: | +- export REF=`git describe --match v[0-9]* HEAD --tags` ++ REF=$(git describe --exact-match --match v[0-9]* HEAD --tags 2>/dev/null) || REF=continuous ++ echo "ref=$REF" >> $GITHUB_OUTPUT + echo "Build Version: $REF" +- [[ "$REF" != "" ]] && echo "ref=$REF" >> $GITHUB_OUTPUT +- if [[ `git describe --exact-match --match v[0-9]* HEAD --tags` ]]; then ++ if [[ "$REF" != "continuous" ]]; then + echo "release=$REF" >> $GITHUB_OUTPUT + echo "Release Version: $REF" + fi +- ++ ++ + build_darwin: + name: Darwin + needs: [version] diff --git a/tasks/lite-xl__lite-xl-1977/tests/test.sh b/tasks/lite-xl__lite-xl-1977/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..78732113a739dc429cf3c7a94cb59a1cdd7319fd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/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 081215f5750d807a6f395268c4028e9061e93d0d > "$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/lite-xl__lite-xl-1977/tests/verifier.py b/tasks/lite-xl__lite-xl-1977/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1977/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/lite-xl__lite-xl-1983/environment/Dockerfile b/tasks/lite-xl__lite-xl-1983/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2fad1e49f8ae47d509ba5aa78e5c6cc2a351e58f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d116ec10426d907f2976169887d9d558a0d6a9e0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d116ec10426d907f2976169887d9d558a0d6a9e0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d116ec10426d907f2976169887d9d558a0d6a9e0 \ + && 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/lite-xl__lite-xl-1983/instruction.md b/tasks/lite-xl__lite-xl-1983/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5aa42d0536ad1b669d9c9b30909c2a4e039bd764 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** ci: add postrelease workflow to update docs and release winget packages + +## Description + +it does the thing + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d116ec10426d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1983/solution/patch.diff b/tasks/lite-xl__lite-xl-1983/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dddc3a552341164e6191dac74ff39d7568adc94f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/postrelease.yml b/.github/workflows/postrelease.yml +new file mode 100644 +index 00000000..d8246382 +--- /dev/null ++++ b/.github/workflows/postrelease.yml +@@ -0,0 +1,25 @@ ++name: Postrelease ++on: ++ release: ++ types: [released] ++ ++jobs: ++ postrelease: ++ if: ${{ github.repository == 'lite-xl/lite-xl' && startsWith(github.ref, 'refs/tags/v') }} ++ runs-on: windows-latest ++ steps: ++ - name: Update winget-pkgs repository ++ env: { GH_TOKEN: "${{ secrets.WINGET_TOKEN }}" } ++ run: gh repo sync lite-xl/winget-pkgs ++ ++ - name: Release to winget ++ uses: vedantmgoyal9/winget-releaser@main ++ with: ++ identifier: LiteXLTeam.LiteXL ++ installers-regex: '^lite-xl-v[0-9\.]+-x86_64-windows-setup\.exe$' ++ fork-user: 'lite-xl' ++ token: ${{ secrets.WINGET_TOKEN }} ++ ++ - name: Update documentation link ++ env: { GH_TOKEN: "${{ secrets.DOCS_TOKEN }}" } ++ run: gh -R lite-xl/docs workflow run deploy.yml diff --git a/tasks/lite-xl__lite-xl-1983/solution/solve.sh b/tasks/lite-xl__lite-xl-1983/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/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/lite-xl__lite-xl-1983/task.toml b/tasks/lite-xl__lite-xl-1983/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..22c2faebe47031dcc2d73f739f1165cd6767584a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1983" +description = "ci: add postrelease workflow to update docs and release winget packages" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d116ec10426d907f2976169887d9d558a0d6a9e0" +reference = "https://github.com/lite-xl/lite-xl/pull/1983" +source_access = "auto" +built_at = "2026-11-16T16:09:56.300532+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ae50738c9ba2c0dbc7bc0316ebc4ad585413197d223056359d61986c81e95b5b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T15:19:41Z" +diff_format = "unified" +context_files = [ + ".github/workflows/postrelease.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.314958+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dcf27ff49f6f4698b3569b62879514963b6cd9adf4a889463451081ff62c8fab" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1983/tests/capture.py b/tasks/lite-xl__lite-xl-1983/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/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/lite-xl__lite-xl-1983/tests/instruction.md b/tasks/lite-xl__lite-xl-1983/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5aa42d0536ad1b669d9c9b30909c2a4e039bd764 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** ci: add postrelease workflow to update docs and release winget packages + +## Description + +it does the thing + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d116ec10426d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1983/tests/oracle.patch b/tasks/lite-xl__lite-xl-1983/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dddc3a552341164e6191dac74ff39d7568adc94f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/postrelease.yml b/.github/workflows/postrelease.yml +new file mode 100644 +index 00000000..d8246382 +--- /dev/null ++++ b/.github/workflows/postrelease.yml +@@ -0,0 +1,25 @@ ++name: Postrelease ++on: ++ release: ++ types: [released] ++ ++jobs: ++ postrelease: ++ if: ${{ github.repository == 'lite-xl/lite-xl' && startsWith(github.ref, 'refs/tags/v') }} ++ runs-on: windows-latest ++ steps: ++ - name: Update winget-pkgs repository ++ env: { GH_TOKEN: "${{ secrets.WINGET_TOKEN }}" } ++ run: gh repo sync lite-xl/winget-pkgs ++ ++ - name: Release to winget ++ uses: vedantmgoyal9/winget-releaser@main ++ with: ++ identifier: LiteXLTeam.LiteXL ++ installers-regex: '^lite-xl-v[0-9\.]+-x86_64-windows-setup\.exe$' ++ fork-user: 'lite-xl' ++ token: ${{ secrets.WINGET_TOKEN }} ++ ++ - name: Update documentation link ++ env: { GH_TOKEN: "${{ secrets.DOCS_TOKEN }}" } ++ run: gh -R lite-xl/docs workflow run deploy.yml diff --git a/tasks/lite-xl__lite-xl-1983/tests/test.sh b/tasks/lite-xl__lite-xl-1983/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4e75079452cdd095201866787af424a368eafcd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/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 d116ec10426d907f2976169887d9d558a0d6a9e0 > "$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/lite-xl__lite-xl-1983/tests/verifier.py b/tasks/lite-xl__lite-xl-1983/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1983/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/lite-xl__lite-xl-1984/environment/Dockerfile b/tasks/lite-xl__lite-xl-1984/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2fad1e49f8ae47d509ba5aa78e5c6cc2a351e58f --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d116ec10426d907f2976169887d9d558a0d6a9e0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d116ec10426d907f2976169887d9d558a0d6a9e0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d116ec10426d907f2976169887d9d558a0d6a9e0 \ + && 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/lite-xl__lite-xl-1984/instruction.md b/tasks/lite-xl__lite-xl-1984/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcb3383762aef8615457beaaa8edc0d057ca112c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Release: v2.1.6 and v2.1.7 + +## Description + +Forgot to cherry-pick the changelogs and version for 2 versions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d116ec10426d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1984/solution/patch.diff b/tasks/lite-xl__lite-xl-1984/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a1611dbd4ae2b304c3cb4fca1db9e40de894ac84 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/solution/patch.diff @@ -0,0 +1,132 @@ +diff --git a/changelog.md b/changelog.md +index f4d22ba8..1d314d78 100644 +--- a/changelog.md ++++ b/changelog.md +@@ -1,5 +1,106 @@ + # Changes Log + ++## [2.1.7] - 2024-12-05 ++ ++This release fixes a bug related to scaling on macOS, ++the comment line / block functionality and an issue with overscrolling ++when the editor is too small. ++The TreeView now allows creating directories when a trailing slash is added, ++and the open file prompt now allows using both '/' and '\' as path separators. ++ ++### Features ++ ++* Allow `/` for path suggestions in Windows ++ ([#1875](https://github.com/lite-xl/lite-xl/pull/1875), ++ [#1976](https://github.com/lite-xl/lite-xl/pull/1976)) ++ ++* Check item type before creating input text in treeview ++ ([#1904](https://github.com/lite-xl/lite-xl/pull/1904)) ++ ++### Fixes ++ ++* Return state when tokenizing plaintext syntaxes ++ ++* Scale font pixel size in `RENDERER` mode ++ ([#1969](https://github.com/lite-xl/lite-xl/pull/1969)) ++ ++* Prevent overscroll when DocView size is less than lh * 2 ++ ([#1971](https://github.com/lite-xl/lite-xl/pull/1971)) ++ ++* Fix process:read_stdout() and process:read_stderr() not checking for process completion ++ ([#1973](https://github.com/lite-xl/lite-xl/pull/1973)) ++ ++* Call poll_process when calling process:returncode() ++ ([#1981](https://github.com/lite-xl/lite-xl/pull/1981)) ++ ++### Other Changes ++ ++* Add winget releaser workflow ++ ++## [2.1.6] - 2024-11-29 ++ ++This release introduces a new icon for macOS, improves the performance of the renderer, ++adds syntax highlighting support for CUDA as well as QOL fixes and improvements. ++ ++### Features ++ ++* Add CUDA syntax highlighting support ++ ([#1848](https://github.com/lite-xl/lite-xl/pull/1848)) ++ ++* Add macOS-specific application icon ++ ([#1844](https://github.com/lite-xl/lite-xl/pull/1844)) ++ ++* Add keyboard shortcut to tooltips in ToolbarView ++ ([#1880](https://github.com/lite-xl/lite-xl/pull/1880)) ++ ++* Improve projectsearch (status on the top, horizontal scrolling, elipsis) ++ ([#1876](https://github.com/lite-xl/lite-xl/pull/1876)) ++ ++### Fixes ++ ++* Correctly free SDL_Texture and SDL_Renderer ++ ([#1849](https://github.com/lite-xl/lite-xl/pull/1850)) ++ ++* Fixed minor typo from merge of #1854 for Windows builds ++ ++* Fix multi-type usage in delimited patterns ++ ([#1740](https://github.com/lite-xl/lite-xl/pull/1740)) ++ ++* Fix appimage cd error and use static appimage runtime ++ ([#1924](https://github.com/lite-xl/lite-xl/pull/1924)) ++ ++### Other Changes ++ ++* Rewrite glyph cache ++ ([#1845](https://github.com/lite-xl/lite-xl/pull/1845)) ++ ++* Use lite-xl-build-box-manylinux ++ ([#1877](https://github.com/lite-xl/lite-xl/pull/1877)) ++ ++* Remove unused calls to system.absolute_path() ++ ([#1895](https://github.com/lite-xl/lite-xl/pull/1895)) ++ ++* Remove lhelper script, build configuration and dependency support ++ ([#1906](https://github.com/lite-xl/lite-xl/pull/1906)) ++ ++* Refactor how arguments are handled in process.start() ++ ([#1854](https://github.com/lite-xl/lite-xl/pull/1854)) ++ ++* Add a proper name to EmptyView ++ ([#1569](https://github.com/lite-xl/lite-xl/pull/1569)) ++ ++* Format renderer font scale code to be actually readable ++ ([#1921](https://github.com/lite-xl/lite-xl/pull/1921)) ++ ++* Update PCRE2 wrap ++ ([#1927](https://github.com/lite-xl/lite-xl/pull/1927)) ++ ++* Use meson datadir as lite_datadir base ++ ([#1939](https://github.com/lite-xl/lite-xl/pull/1939)) ++ ++* Convert unix style paths literals into meson path segments ++ ([#1938](https://github.com/lite-xl/lite-xl/pull/1938)) ++ + ## [2.1.5] - 2024-06-29 + + This release addresses several bugs from upstream dependencies and +@@ -1587,6 +1688,8 @@ A new global variable `USERDIR` is exposed to point to the user's directory. + + - subpixel font rendering with gamma correction + ++[2.1.7]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.7 ++[2.1.6]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.6 + [2.1.5]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.5 + [2.1.4]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.4 + [2.1.3]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.3 +diff --git a/meson.build b/meson.build +index 883e4b78..9604ec03 100644 +--- a/meson.build ++++ b/meson.build +@@ -1,6 +1,6 @@ + project('lite-xl', + ['c'], +- version : '2.1.5', ++ version : '2.1.7', + license : 'MIT', + meson_version : '>= 0.63', + default_options : [ diff --git a/tasks/lite-xl__lite-xl-1984/solution/solve.sh b/tasks/lite-xl__lite-xl-1984/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/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/lite-xl__lite-xl-1984/task.toml b/tasks/lite-xl__lite-xl-1984/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2694647d0931864d1274dc62fe6eb634c63c0e89 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1984" +description = "Release: v2.1.6 and v2.1.7" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "d116ec10426d907f2976169887d9d558a0d6a9e0" +reference = "https://github.com/lite-xl/lite-xl/pull/1984" +source_access = "auto" +built_at = "2026-11-16T16:09:56.311898+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a8b666e6b194ccd55188d4ec6ec8c80af1e3723e97029cbba7a73dfac1bbc455" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-12-09T10:33:45Z" +diff_format = "unified" +context_files = [ + "changelog.md", + "meson.build", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 105 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.315390+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dcf27ff49f6f4698b3569b62879514963b6cd9adf4a889463451081ff62c8fab" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1984/tests/capture.py b/tasks/lite-xl__lite-xl-1984/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/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/lite-xl__lite-xl-1984/tests/instruction.md b/tasks/lite-xl__lite-xl-1984/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcb3383762aef8615457beaaa8edc0d057ca112c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Release: v2.1.6 and v2.1.7 + +## Description + +Forgot to cherry-pick the changelogs and version for 2 versions. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d116ec10426d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1984/tests/oracle.patch b/tasks/lite-xl__lite-xl-1984/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a1611dbd4ae2b304c3cb4fca1db9e40de894ac84 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/tests/oracle.patch @@ -0,0 +1,132 @@ +diff --git a/changelog.md b/changelog.md +index f4d22ba8..1d314d78 100644 +--- a/changelog.md ++++ b/changelog.md +@@ -1,5 +1,106 @@ + # Changes Log + ++## [2.1.7] - 2024-12-05 ++ ++This release fixes a bug related to scaling on macOS, ++the comment line / block functionality and an issue with overscrolling ++when the editor is too small. ++The TreeView now allows creating directories when a trailing slash is added, ++and the open file prompt now allows using both '/' and '\' as path separators. ++ ++### Features ++ ++* Allow `/` for path suggestions in Windows ++ ([#1875](https://github.com/lite-xl/lite-xl/pull/1875), ++ [#1976](https://github.com/lite-xl/lite-xl/pull/1976)) ++ ++* Check item type before creating input text in treeview ++ ([#1904](https://github.com/lite-xl/lite-xl/pull/1904)) ++ ++### Fixes ++ ++* Return state when tokenizing plaintext syntaxes ++ ++* Scale font pixel size in `RENDERER` mode ++ ([#1969](https://github.com/lite-xl/lite-xl/pull/1969)) ++ ++* Prevent overscroll when DocView size is less than lh * 2 ++ ([#1971](https://github.com/lite-xl/lite-xl/pull/1971)) ++ ++* Fix process:read_stdout() and process:read_stderr() not checking for process completion ++ ([#1973](https://github.com/lite-xl/lite-xl/pull/1973)) ++ ++* Call poll_process when calling process:returncode() ++ ([#1981](https://github.com/lite-xl/lite-xl/pull/1981)) ++ ++### Other Changes ++ ++* Add winget releaser workflow ++ ++## [2.1.6] - 2024-11-29 ++ ++This release introduces a new icon for macOS, improves the performance of the renderer, ++adds syntax highlighting support for CUDA as well as QOL fixes and improvements. ++ ++### Features ++ ++* Add CUDA syntax highlighting support ++ ([#1848](https://github.com/lite-xl/lite-xl/pull/1848)) ++ ++* Add macOS-specific application icon ++ ([#1844](https://github.com/lite-xl/lite-xl/pull/1844)) ++ ++* Add keyboard shortcut to tooltips in ToolbarView ++ ([#1880](https://github.com/lite-xl/lite-xl/pull/1880)) ++ ++* Improve projectsearch (status on the top, horizontal scrolling, elipsis) ++ ([#1876](https://github.com/lite-xl/lite-xl/pull/1876)) ++ ++### Fixes ++ ++* Correctly free SDL_Texture and SDL_Renderer ++ ([#1849](https://github.com/lite-xl/lite-xl/pull/1850)) ++ ++* Fixed minor typo from merge of #1854 for Windows builds ++ ++* Fix multi-type usage in delimited patterns ++ ([#1740](https://github.com/lite-xl/lite-xl/pull/1740)) ++ ++* Fix appimage cd error and use static appimage runtime ++ ([#1924](https://github.com/lite-xl/lite-xl/pull/1924)) ++ ++### Other Changes ++ ++* Rewrite glyph cache ++ ([#1845](https://github.com/lite-xl/lite-xl/pull/1845)) ++ ++* Use lite-xl-build-box-manylinux ++ ([#1877](https://github.com/lite-xl/lite-xl/pull/1877)) ++ ++* Remove unused calls to system.absolute_path() ++ ([#1895](https://github.com/lite-xl/lite-xl/pull/1895)) ++ ++* Remove lhelper script, build configuration and dependency support ++ ([#1906](https://github.com/lite-xl/lite-xl/pull/1906)) ++ ++* Refactor how arguments are handled in process.start() ++ ([#1854](https://github.com/lite-xl/lite-xl/pull/1854)) ++ ++* Add a proper name to EmptyView ++ ([#1569](https://github.com/lite-xl/lite-xl/pull/1569)) ++ ++* Format renderer font scale code to be actually readable ++ ([#1921](https://github.com/lite-xl/lite-xl/pull/1921)) ++ ++* Update PCRE2 wrap ++ ([#1927](https://github.com/lite-xl/lite-xl/pull/1927)) ++ ++* Use meson datadir as lite_datadir base ++ ([#1939](https://github.com/lite-xl/lite-xl/pull/1939)) ++ ++* Convert unix style paths literals into meson path segments ++ ([#1938](https://github.com/lite-xl/lite-xl/pull/1938)) ++ + ## [2.1.5] - 2024-06-29 + + This release addresses several bugs from upstream dependencies and +@@ -1587,6 +1688,8 @@ A new global variable `USERDIR` is exposed to point to the user's directory. + + - subpixel font rendering with gamma correction + ++[2.1.7]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.7 ++[2.1.6]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.6 + [2.1.5]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.5 + [2.1.4]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.4 + [2.1.3]: https://github.com/lite-xl/lite-xl/releases/tag/v2.1.3 +diff --git a/meson.build b/meson.build +index 883e4b78..9604ec03 100644 +--- a/meson.build ++++ b/meson.build +@@ -1,6 +1,6 @@ + project('lite-xl', + ['c'], +- version : '2.1.5', ++ version : '2.1.7', + license : 'MIT', + meson_version : '>= 0.63', + default_options : [ diff --git a/tasks/lite-xl__lite-xl-1984/tests/test.sh b/tasks/lite-xl__lite-xl-1984/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4e75079452cdd095201866787af424a368eafcd --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/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 d116ec10426d907f2976169887d9d558a0d6a9e0 > "$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/lite-xl__lite-xl-1984/tests/verifier.py b/tasks/lite-xl__lite-xl-1984/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1984/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/lite-xl__lite-xl-1991/environment/Dockerfile b/tasks/lite-xl__lite-xl-1991/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79f6aaffbbf5305249b71b69391ee9b034229a9a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 819fa9d30e2c0e737fad519fbff63ce2baff4456 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && 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/lite-xl__lite-xl-1991/instruction.md b/tasks/lite-xl__lite-xl-1991/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94938d075c22f9d176cead2f4e98699950403b04 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/instruction.md @@ -0,0 +1,85 @@ +# Issue + +**Title:** balance computed directory list, remove recursive function invocation + +## Description + +does what it says on the tin + +the previous behavior iterated through recursive function calls where as this new implementation avoids recursion + +here is the difference of the output when ran on the lite-xl src directory: + +before: +``` +src/api +src/api/dirmonitor +src/api/dirmonitor/dummy.c +src/api/dirmonitor/fsevents.c +src/api/dirmonitor/inodewatcher.cpp +src/api/dirmonitor/inotify.c +src/api/dirmonitor/kqueue.c +src/api/dirmonitor/win32.c +src/api/api.c +src/api/api.h +src/api/dirmonitor.c +src/api/process.c +src/api/regex.c +src/api/renderer.c +src/api/renwindow.c +src/api/system.c +src/api/utf8.c +src/arena_allocator.c +src/arena_allocator.h +src/bundle_open.m +src/main.c +src/meson.build +src/rencache.c +src/rencache.h +src/renderer.c +src/renderer.h +src/renwindow.c +src/renwindow.h +src/unidata.h +src/utfconv.h +``` + +after: +``` +src/rencache.h +src/unidata.h +src/meson.build +src/api +src/rencache.c +src/arena_allocator.h +src/arena_allocator.c +src/renderer.c +src/utfconv.h +src/renwindow.c +src/main.c +src/bundle_open.m +src/renwindow.h +src/renderer.h +src/api/api.h +src/api/utf8.c +src/api/dirmonitor.c +src/api/api.c +src/api/renderer.c +src/api/system.c +src/api/dirmonitor +src/api/renwindow.c +src/api/regex.c +src/api/process.c +src/api/dirmonitor/inotify.c +src/api/dirmonitor/dummy.c +src/api/dirmonitor/inodewatcher.cpp +src/api/dirmonitor/win32.c +src/api/dirmonitor/fsevents.c +src/api/dirmonitor/kqueue.c +``` + +the result is that it the iterations are balanced and no specific path is favored in any way and that larger directories won't exhaust the max project file count before smaller directories get their chance + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1991/solution/patch.diff b/tasks/lite-xl__lite-xl-1991/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0a38c58d82d5abbf9314f7bff8e5b2dbc3801035 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/data/core/project.lua b/data/core/project.lua +index 5036afad..68b93cad 100644 +--- a/data/core/project.lua ++++ b/data/core/project.lua +@@ -104,19 +104,27 @@ function Project:get_file_info(path) + return info + end + +- +-local function find_files_rec(project, path) ++local function get_dir_content(project, path, entries) + local all = system.list_dir(path) or {} + for _, file in ipairs(all) do + local file = path .. PATHSEP .. file + local info = project:get_file_info(file) + if info then + info.filename = file +- if info.type == "file" then +- coroutine.yield(project, info) +- elseif not common.match_pattern(common.basename(info.filename), config.ignore_files) and info.type then +- find_files_rec(project, file) +- end ++ table.insert(entries, info) ++ end ++ end ++end ++ ++local function find_files_rec(project, path) ++ local entries = {} ++ get_dir_content(project, path, entries) ++ ++ for _, info in ipairs(entries) do ++ if info.type == "file" then ++ coroutine.yield(project, info) ++ elseif not common.match_pattern(common.basename(info.filename), config.ignore_files) and info.type then ++ get_dir_content(project, info.filename, entries) + end + end + end diff --git a/tasks/lite-xl__lite-xl-1991/solution/solve.sh b/tasks/lite-xl__lite-xl-1991/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/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/lite-xl__lite-xl-1991/task.toml b/tasks/lite-xl__lite-xl-1991/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5291fd55afff6a4a195ad685f6c956c10223ff2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1991" +description = "balance computed directory list, remove recursive function invocation" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "819fa9d30e2c0e737fad519fbff63ce2baff4456" +reference = "https://github.com/lite-xl/lite-xl/pull/1991" +source_access = "auto" +built_at = "2026-11-16T16:09:56.294571+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0b1045ee95b417972441dadeb2a207224ffd574813875b1f21333d9694a4df2a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-16T16:14:43Z" +diff_format = "unified" +context_files = [ + "data/core/project.lua", +] +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:01.315820+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8157ccb850d65e11de5d9535f476f68f7af87fe114bfff9d7bfe590be94ed8a2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1991/tests/capture.py b/tasks/lite-xl__lite-xl-1991/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/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/lite-xl__lite-xl-1991/tests/instruction.md b/tasks/lite-xl__lite-xl-1991/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94938d075c22f9d176cead2f4e98699950403b04 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/tests/instruction.md @@ -0,0 +1,85 @@ +# Issue + +**Title:** balance computed directory list, remove recursive function invocation + +## Description + +does what it says on the tin + +the previous behavior iterated through recursive function calls where as this new implementation avoids recursion + +here is the difference of the output when ran on the lite-xl src directory: + +before: +``` +src/api +src/api/dirmonitor +src/api/dirmonitor/dummy.c +src/api/dirmonitor/fsevents.c +src/api/dirmonitor/inodewatcher.cpp +src/api/dirmonitor/inotify.c +src/api/dirmonitor/kqueue.c +src/api/dirmonitor/win32.c +src/api/api.c +src/api/api.h +src/api/dirmonitor.c +src/api/process.c +src/api/regex.c +src/api/renderer.c +src/api/renwindow.c +src/api/system.c +src/api/utf8.c +src/arena_allocator.c +src/arena_allocator.h +src/bundle_open.m +src/main.c +src/meson.build +src/rencache.c +src/rencache.h +src/renderer.c +src/renderer.h +src/renwindow.c +src/renwindow.h +src/unidata.h +src/utfconv.h +``` + +after: +``` +src/rencache.h +src/unidata.h +src/meson.build +src/api +src/rencache.c +src/arena_allocator.h +src/arena_allocator.c +src/renderer.c +src/utfconv.h +src/renwindow.c +src/main.c +src/bundle_open.m +src/renwindow.h +src/renderer.h +src/api/api.h +src/api/utf8.c +src/api/dirmonitor.c +src/api/api.c +src/api/renderer.c +src/api/system.c +src/api/dirmonitor +src/api/renwindow.c +src/api/regex.c +src/api/process.c +src/api/dirmonitor/inotify.c +src/api/dirmonitor/dummy.c +src/api/dirmonitor/inodewatcher.cpp +src/api/dirmonitor/win32.c +src/api/dirmonitor/fsevents.c +src/api/dirmonitor/kqueue.c +``` + +the result is that it the iterations are balanced and no specific path is favored in any way and that larger directories won't exhaust the max project file count before smaller directories get their chance + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1991/tests/oracle.patch b/tasks/lite-xl__lite-xl-1991/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0a38c58d82d5abbf9314f7bff8e5b2dbc3801035 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/data/core/project.lua b/data/core/project.lua +index 5036afad..68b93cad 100644 +--- a/data/core/project.lua ++++ b/data/core/project.lua +@@ -104,19 +104,27 @@ function Project:get_file_info(path) + return info + end + +- +-local function find_files_rec(project, path) ++local function get_dir_content(project, path, entries) + local all = system.list_dir(path) or {} + for _, file in ipairs(all) do + local file = path .. PATHSEP .. file + local info = project:get_file_info(file) + if info then + info.filename = file +- if info.type == "file" then +- coroutine.yield(project, info) +- elseif not common.match_pattern(common.basename(info.filename), config.ignore_files) and info.type then +- find_files_rec(project, file) +- end ++ table.insert(entries, info) ++ end ++ end ++end ++ ++local function find_files_rec(project, path) ++ local entries = {} ++ get_dir_content(project, path, entries) ++ ++ for _, info in ipairs(entries) do ++ if info.type == "file" then ++ coroutine.yield(project, info) ++ elseif not common.match_pattern(common.basename(info.filename), config.ignore_files) and info.type then ++ get_dir_content(project, info.filename, entries) + end + end + end diff --git a/tasks/lite-xl__lite-xl-1991/tests/test.sh b/tasks/lite-xl__lite-xl-1991/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b633fca4f9bab861c01a786a0068cc7c5aeb58d3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/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 819fa9d30e2c0e737fad519fbff63ce2baff4456 > "$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/lite-xl__lite-xl-1991/tests/verifier.py b/tasks/lite-xl__lite-xl-1991/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1991/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/lite-xl__lite-xl-1999/environment/Dockerfile b/tasks/lite-xl__lite-xl-1999/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42decb55c677b03f168b0a6c7e8681a0cbb3d074 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c73903f5bed82cb7cd6d19a3f7a846c78bb60283 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && 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/lite-xl__lite-xl-1999/instruction.md b/tasks/lite-xl__lite-xl-1999/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02c654c5952fa27933bcb309dce7f627f802d907 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: use correct charmap and glyphmap sizes + +## 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 `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1999/solution/patch.diff b/tasks/lite-xl__lite-xl-1999/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c6886fd895289c3a95b3982c77b3c44fdaa37e78 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/src/renderer.c b/src/renderer.c +index c53c9797..66450c63 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -44,13 +44,13 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + #define MAX_UNICODE 0x10FFFF + // number of rows and columns in the codepoint map + #define CHARMAP_ROW 128 +-#define CHARMAP_COL (MAX_UNICODE / CHARMAP_ROW) ++#define CHARMAP_COL ((unsigned int)ceil((float)MAX_UNICODE / CHARMAP_ROW)) + + // the maximum number of glyphs for OpenType + #define MAX_GLYPHS 65535 + // number of rows and columns in the glyph map + #define GLYPHMAP_ROW 128 +-#define GLYPHMAP_COL (MAX_GLYPHS / GLYPHMAP_ROW) ++#define GLYPHMAP_COL ((unsigned int)ceil((float)MAX_GLYPHS / GLYPHMAP_ROW)) + + // number of subpixel bitmaps + #define SUBPIXEL_BITMAPS_CACHED 3 diff --git a/tasks/lite-xl__lite-xl-1999/solution/solve.sh b/tasks/lite-xl__lite-xl-1999/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/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/lite-xl__lite-xl-1999/task.toml b/tasks/lite-xl__lite-xl-1999/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e492d6281fbc791b7656a946353ddfb66bee343 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-1999" +description = "fix: use correct charmap and glyphmap sizes" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c73903f5bed82cb7cd6d19a3f7a846c78bb60283" +reference = "https://github.com/lite-xl/lite-xl/pull/1999" +source_access = "auto" +built_at = "2026-11-16T16:09:56.299296+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:98574a92d52eaa940402a15700ee9f18fd6d1ee576db4ae1af9493c1ea5b2792" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T15:57:20Z" +diff_format = "unified" +context_files = [ + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.316271+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:307e40333615d4bf846fa75520b99d5c2172d2a222a0df827ccdb63a97af2fa7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-1999/tests/capture.py b/tasks/lite-xl__lite-xl-1999/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/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/lite-xl__lite-xl-1999/tests/instruction.md b/tasks/lite-xl__lite-xl-1999/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02c654c5952fa27933bcb309dce7f627f802d907 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix: use correct charmap and glyphmap sizes + +## 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 `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-1999/tests/oracle.patch b/tasks/lite-xl__lite-xl-1999/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c6886fd895289c3a95b3982c77b3c44fdaa37e78 --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/src/renderer.c b/src/renderer.c +index c53c9797..66450c63 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -44,13 +44,13 @@ static void* _check_alloc(void *ptr, const char *const file, size_t ln) { + #define MAX_UNICODE 0x10FFFF + // number of rows and columns in the codepoint map + #define CHARMAP_ROW 128 +-#define CHARMAP_COL (MAX_UNICODE / CHARMAP_ROW) ++#define CHARMAP_COL ((unsigned int)ceil((float)MAX_UNICODE / CHARMAP_ROW)) + + // the maximum number of glyphs for OpenType + #define MAX_GLYPHS 65535 + // number of rows and columns in the glyph map + #define GLYPHMAP_ROW 128 +-#define GLYPHMAP_COL (MAX_GLYPHS / GLYPHMAP_ROW) ++#define GLYPHMAP_COL ((unsigned int)ceil((float)MAX_GLYPHS / GLYPHMAP_ROW)) + + // number of subpixel bitmaps + #define SUBPIXEL_BITMAPS_CACHED 3 diff --git a/tasks/lite-xl__lite-xl-1999/tests/test.sh b/tasks/lite-xl__lite-xl-1999/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77c6082a3f191fe9ebf832c60dc54e430c7e538c --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/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 c73903f5bed82cb7cd6d19a3f7a846c78bb60283 > "$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/lite-xl__lite-xl-1999/tests/verifier.py b/tasks/lite-xl__lite-xl-1999/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-1999/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/lite-xl__lite-xl-2010/environment/Dockerfile b/tasks/lite-xl__lite-xl-2010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42decb55c677b03f168b0a6c7e8681a0cbb3d074 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c73903f5bed82cb7cd6d19a3f7a846c78bb60283 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && 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/lite-xl__lite-xl-2010/instruction.md b/tasks/lite-xl__lite-xl-2010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ff3ed8d16088f31ca261a1f34f1f6f96308f1f9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Update CSS plugin to support more units + +## Description + +The plugin know recognizes units such as `em`, `vw`, `in`, `cm`, `mm`, percentages, etc. +I also removed the pattern for comments starting with `//`, as it is not standardized in CSS. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2010/solution/patch.diff b/tasks/lite-xl__lite-xl-2010/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..846f3a778ab7e00a75ab60bfac9a115c9174cffd --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/data/plugins/language_css.lua b/data/plugins/language_css.lua +index 9e78cde5..a127dfac 100644 +--- a/data/plugins/language_css.lua ++++ b/data/plugins/language_css.lua +@@ -7,15 +7,40 @@ syntax.add { + block_comment = { "/*", "*/" }, + patterns = { + { pattern = "\\.", type = "normal" }, +- { pattern = "//.*", type = "comment" }, + { pattern = { "/%*", "%*/" }, type = "comment" }, + { pattern = { '"', '"', '\\' }, type = "string" }, + { pattern = { "'", "'", '\\' }, type = "string" }, + { pattern = "[%a][%w-]*%s*%f[:]", type = "keyword" }, + { pattern = "#%x%x%x%x%x%x%f[%W]",type = "string" }, + { pattern = "#%x%x%x%f[%W]", type = "string" }, +- { pattern = "-?%d+[%d%.]*p[xt]", type = "number" }, ++ { pattern = "-?%d+[%d%.]*p[xtc]", type = "number" }, + { pattern = "-?%d+[%d%.]*deg", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cm", type = "number" }, ++ { pattern = "-?%d+[%d%.]*mm", type = "number" }, ++ { pattern = "-?%d+[%d%.]*in", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ic", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?cap", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?em", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?lh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ch", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ex", type = "number" }, ++ { pattern = "-?%d+[%d%.]*m?s", type = "number" }, ++ { pattern = "-?%d+[%d%.]*hz", type = "number" }, ++ { pattern = "-?%d+[%d%.]*Hz", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vw", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vmin", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vmax", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vb", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vi", type = "number" }, ++ { pattern = "-?%d+[%d%.]*%%", type = "number" }, ++ { pattern = "-?%d+[%d%.]*Q", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqw", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqi", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqb", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqmin", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqmax", type = "number" }, + { pattern = "-?%d+[%d%.]*", type = "number" }, + { pattern = "[%a_][%w_]*", type = "symbol" }, + { pattern = "#[%a][%w_-]*", type = "keyword2" }, diff --git a/tasks/lite-xl__lite-xl-2010/solution/solve.sh b/tasks/lite-xl__lite-xl-2010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/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/lite-xl__lite-xl-2010/task.toml b/tasks/lite-xl__lite-xl-2010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b9f3689aa85c6aea7cf7db47462ce75d23d15b2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2010" +description = "Update CSS plugin to support more units" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c73903f5bed82cb7cd6d19a3f7a846c78bb60283" +reference = "https://github.com/lite-xl/lite-xl/pull/2010" +source_access = "auto" +built_at = "2026-11-16T16:09:56.308986+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:93803ea0d3641c4d0252d2056273a2154e1efbcc3521f37edfdef8f1037e4d7c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-01-28T15:47:00Z" +diff_format = "unified" +context_files = [ + "data/plugins/language_css.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.316713+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:307e40333615d4bf846fa75520b99d5c2172d2a222a0df827ccdb63a97af2fa7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2010/tests/capture.py b/tasks/lite-xl__lite-xl-2010/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/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/lite-xl__lite-xl-2010/tests/instruction.md b/tasks/lite-xl__lite-xl-2010/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ff3ed8d16088f31ca261a1f34f1f6f96308f1f9 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** Update CSS plugin to support more units + +## Description + +The plugin know recognizes units such as `em`, `vw`, `in`, `cm`, `mm`, percentages, etc. +I also removed the pattern for comments starting with `//`, as it is not standardized in CSS. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2010/tests/oracle.patch b/tasks/lite-xl__lite-xl-2010/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..846f3a778ab7e00a75ab60bfac9a115c9174cffd --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/data/plugins/language_css.lua b/data/plugins/language_css.lua +index 9e78cde5..a127dfac 100644 +--- a/data/plugins/language_css.lua ++++ b/data/plugins/language_css.lua +@@ -7,15 +7,40 @@ syntax.add { + block_comment = { "/*", "*/" }, + patterns = { + { pattern = "\\.", type = "normal" }, +- { pattern = "//.*", type = "comment" }, + { pattern = { "/%*", "%*/" }, type = "comment" }, + { pattern = { '"', '"', '\\' }, type = "string" }, + { pattern = { "'", "'", '\\' }, type = "string" }, + { pattern = "[%a][%w-]*%s*%f[:]", type = "keyword" }, + { pattern = "#%x%x%x%x%x%x%f[%W]",type = "string" }, + { pattern = "#%x%x%x%f[%W]", type = "string" }, +- { pattern = "-?%d+[%d%.]*p[xt]", type = "number" }, ++ { pattern = "-?%d+[%d%.]*p[xtc]", type = "number" }, + { pattern = "-?%d+[%d%.]*deg", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cm", type = "number" }, ++ { pattern = "-?%d+[%d%.]*mm", type = "number" }, ++ { pattern = "-?%d+[%d%.]*in", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ic", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?cap", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?em", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?lh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ch", type = "number" }, ++ { pattern = "-?%d+[%d%.]*r?ex", type = "number" }, ++ { pattern = "-?%d+[%d%.]*m?s", type = "number" }, ++ { pattern = "-?%d+[%d%.]*hz", type = "number" }, ++ { pattern = "-?%d+[%d%.]*Hz", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vw", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vmin", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vmax", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vb", type = "number" }, ++ { pattern = "-?%d+[%d%.]*vi", type = "number" }, ++ { pattern = "-?%d+[%d%.]*%%", type = "number" }, ++ { pattern = "-?%d+[%d%.]*Q", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqw", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqh", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqi", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqb", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqmin", type = "number" }, ++ { pattern = "-?%d+[%d%.]*cqmax", type = "number" }, + { pattern = "-?%d+[%d%.]*", type = "number" }, + { pattern = "[%a_][%w_]*", type = "symbol" }, + { pattern = "#[%a][%w_-]*", type = "keyword2" }, diff --git a/tasks/lite-xl__lite-xl-2010/tests/test.sh b/tasks/lite-xl__lite-xl-2010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77c6082a3f191fe9ebf832c60dc54e430c7e538c --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/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 c73903f5bed82cb7cd6d19a3f7a846c78bb60283 > "$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/lite-xl__lite-xl-2010/tests/verifier.py b/tasks/lite-xl__lite-xl-2010/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2010/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/lite-xl__lite-xl-2017/environment/Dockerfile b/tasks/lite-xl__lite-xl-2017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42decb55c677b03f168b0a6c7e8681a0cbb3d074 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c73903f5bed82cb7cd6d19a3f7a846c78bb60283 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c73903f5bed82cb7cd6d19a3f7a846c78bb60283 \ + && 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/lite-xl__lite-xl-2017/instruction.md b/tasks/lite-xl__lite-xl-2017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b92c8196dcf0e94e64540ec53354430c8d855b77 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add in missing #include. + +## Description + +As per #2014, we don't actually include the appropriate header for things like `system` and `free`; it's only transitively included implementation-dependently. + +This fixes that. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2017/solution/patch.diff b/tasks/lite-xl__lite-xl-2017/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ba432a5e45f65be50250280cf863d39e092661cf --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/src/api/renwindow.c b/src/api/renwindow.c +index 84687da4..c6d84c40 100644 +--- a/src/api/renwindow.c ++++ b/src/api/renwindow.c +@@ -2,6 +2,7 @@ + #include "../renwindow.h" + #include "lua.h" + #include ++#include + + static RenWindow *persistant_window = NULL; + +diff --git a/src/api/system.c b/src/api/system.c +index 958bab1b..bf291d61 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -1,6 +1,7 @@ + #include + #include + #include ++#include + #include + #include + #include +diff --git a/src/rencache.c b/src/rencache.c +index 51bfd570..b252f128 100644 +--- a/src/rencache.c ++++ b/src/rencache.c +@@ -2,6 +2,7 @@ + #include + #include + #include ++#include + #include + + #ifdef _MSC_VER +diff --git a/src/renderer.c b/src/renderer.c +index c53c9797..a09528ac 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -1,6 +1,7 @@ + #include + #include + #include ++#include + #include + #include + #include diff --git a/tasks/lite-xl__lite-xl-2017/solution/solve.sh b/tasks/lite-xl__lite-xl-2017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/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/lite-xl__lite-xl-2017/task.toml b/tasks/lite-xl__lite-xl-2017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cee74db193863267c7e343a7ae7a996350c7caac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2017" +description = "Add in missing #include." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "c73903f5bed82cb7cd6d19a3f7a846c78bb60283" +reference = "https://github.com/lite-xl/lite-xl/pull/2017" +source_access = "auto" +built_at = "2026-11-16T16:09:56.310316+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8ac33e76a9a2e2233d485dcc51f070fa808f9d823710fd264f5026152f2b2fe2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-01-28T20:12:04Z" +diff_format = "unified" +context_files = [ + "src/api/renwindow.c", + "src/api/system.c", + "src/rencache.c", + "src/renderer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.317172+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:307e40333615d4bf846fa75520b99d5c2172d2a222a0df827ccdb63a97af2fa7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2017/tests/capture.py b/tasks/lite-xl__lite-xl-2017/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/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/lite-xl__lite-xl-2017/tests/instruction.md b/tasks/lite-xl__lite-xl-2017/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b92c8196dcf0e94e64540ec53354430c8d855b77 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Add in missing #include. + +## Description + +As per #2014, we don't actually include the appropriate header for things like `system` and `free`; it's only transitively included implementation-dependently. + +This fixes that. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c73903f5bed8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2017/tests/oracle.patch b/tasks/lite-xl__lite-xl-2017/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ba432a5e45f65be50250280cf863d39e092661cf --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/src/api/renwindow.c b/src/api/renwindow.c +index 84687da4..c6d84c40 100644 +--- a/src/api/renwindow.c ++++ b/src/api/renwindow.c +@@ -2,6 +2,7 @@ + #include "../renwindow.h" + #include "lua.h" + #include ++#include + + static RenWindow *persistant_window = NULL; + +diff --git a/src/api/system.c b/src/api/system.c +index 958bab1b..bf291d61 100644 +--- a/src/api/system.c ++++ b/src/api/system.c +@@ -1,6 +1,7 @@ + #include + #include + #include ++#include + #include + #include + #include +diff --git a/src/rencache.c b/src/rencache.c +index 51bfd570..b252f128 100644 +--- a/src/rencache.c ++++ b/src/rencache.c +@@ -2,6 +2,7 @@ + #include + #include + #include ++#include + #include + + #ifdef _MSC_VER +diff --git a/src/renderer.c b/src/renderer.c +index c53c9797..a09528ac 100644 +--- a/src/renderer.c ++++ b/src/renderer.c +@@ -1,6 +1,7 @@ + #include + #include + #include ++#include + #include + #include + #include diff --git a/tasks/lite-xl__lite-xl-2017/tests/test.sh b/tasks/lite-xl__lite-xl-2017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..77c6082a3f191fe9ebf832c60dc54e430c7e538c --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/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 c73903f5bed82cb7cd6d19a3f7a846c78bb60283 > "$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/lite-xl__lite-xl-2017/tests/verifier.py b/tasks/lite-xl__lite-xl-2017/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2017/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/lite-xl__lite-xl-2026/environment/Dockerfile b/tasks/lite-xl__lite-xl-2026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94e6e356762c1e8bf64c307e94fd17146511acca --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f30214464c0613c281c91be192c2ef8360f3543e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f30214464c0613c281c91be192c2ef8360f3543e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f30214464c0613c281c91be192c2ef8360f3543e \ + && 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/lite-xl__lite-xl-2026/instruction.md b/tasks/lite-xl__lite-xl-2026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ab6962b4f91ebae6133379abc112c4c3d0e6c3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** language_cpp: add back digit separators + +## Description + +. + +There is an issue tho: things like `0x22'` would be valid, but they aren't supposed to be, as specified in [this thing](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf). +To do that, we'll probably need some lookahead / behind magic which I am not familiar with, and it will increase the complexity of the (imo already complex) regex. + +Before: + +![image](https://github.com/user-attachments/assets/01b57466-73d5-4bb8-a88b-64954dd476a9) + +After: + +![image](https://github.com/user-attachments/assets/ed090209-6b87-4dd9-a1d2-61b505443317) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f30214464c06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2026/solution/patch.diff b/tasks/lite-xl__lite-xl-2026/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..033bcc2d05553fe02b9bd27e63e3693d03968c47 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/data/plugins/language_c.lua b/data/plugins/language_c.lua +index 2804fb7b..f80cd47c 100644 +--- a/data/plugins/language_c.lua ++++ b/data/plugins/language_c.lua +@@ -5,6 +5,8 @@ local syntax = require "core.syntax" + local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] + -- float suffix combinations as a Lua pattern / regex + local fsuf = "[fFlL]?" ++-- number with digit separator as a regex non-capturing group ++local digitsep = [[(?:\d[\d']*)]] + + syntax.add { + name = "C", +@@ -12,21 +14,18 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, +- { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, +- { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+%.%d*"..fsuf, type = "number" }, +- { pattern = "%.%d+"..fsuf, type = "number" }, +- { regex = "\\d+"..isuf, type = "number" }, +- { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, +- { pattern = "##", type = "operator" }, +- { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { regex = "0x[0-9a-fA-F][0-9a-fA-F']*"..isuf, type = "number" }, ++ { regex = "0()[0-7][0-7']*"..isuf, type = { "keyword", "number" } }, ++ { regex = digitsep.."\\.?"..digitsep.."?(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { regex = "\\."..digitsep.."(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, ++ { pattern = "##", type = "operator" }, ++ { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, + -- static declarations + { pattern = "static()%s+()inline", + type = { "keyword", "normal", "keyword" } +diff --git a/data/plugins/language_cpp.lua b/data/plugins/language_cpp.lua +index 2bbc688e..7e604577 100644 +--- a/data/plugins/language_cpp.lua ++++ b/data/plugins/language_cpp.lua +@@ -5,6 +5,8 @@ local syntax = require "core.syntax" + local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] + -- float suffix combinations as a Lua pattern / regex + local fsuf = "[fFlL]?" ++-- number with digit separator as a regex non-capturing group ++local digitsep = [[(?:\d[\d']*)]] + + syntax.add { + name = "C++", +@@ -16,24 +18,21 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, +- { regex = "0b[01]+"..isuf, type = "number" }, +- { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, +- { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+%.%d*"..fsuf, type = "number" }, +- { pattern = "%.%d+"..fsuf, type = "number" }, +- { regex = "\\d+"..isuf, type = "number" }, +- { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, +- { pattern = "##", type = "operator" }, +- { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "class%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "namespace%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { regex = "0x[0-9a-fA-F][0-9a-fA-F']*"..isuf, type = "number" }, ++ { regex = "0b[01][01']*"..isuf, type = "number" }, ++ { regex = "0()[0-7][0-7']*"..isuf, type = { "keyword", "number" } }, ++ { regex = digitsep.."\\.?"..digitsep.."?(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { regex = "\\."..digitsep.."(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, ++ { pattern = "##", type = "operator" }, ++ { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "class%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "namespace%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, + -- static declarations + { pattern = "static()%s+()inline", + type = { "keyword", "normal", "keyword" } diff --git a/tasks/lite-xl__lite-xl-2026/solution/solve.sh b/tasks/lite-xl__lite-xl-2026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/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/lite-xl__lite-xl-2026/task.toml b/tasks/lite-xl__lite-xl-2026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea3b9dff478f7fe97b0ccc602b812d27150201bf --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2026" +description = "language_cpp: add back digit separators" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f30214464c0613c281c91be192c2ef8360f3543e" +reference = "https://github.com/lite-xl/lite-xl/pull/2026" +source_access = "auto" +built_at = "2026-11-16T16:09:56.297746+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d10a783adfec28f4186324739c300881d4bd739751f29f16e61dea7809066576" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T15:59:21Z" +diff_format = "unified" +context_files = [ + "data/plugins/language_c.lua", + "data/plugins/language_cpp.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 64 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.317625+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d563eb1b475a366408607c5569c9a14e2bc3d6ea03bab6df6cdc729a734eff0d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2026/tests/capture.py b/tasks/lite-xl__lite-xl-2026/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/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/lite-xl__lite-xl-2026/tests/instruction.md b/tasks/lite-xl__lite-xl-2026/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ab6962b4f91ebae6133379abc112c4c3d0e6c3d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** language_cpp: add back digit separators + +## Description + +. + +There is an issue tho: things like `0x22'` would be valid, but they aren't supposed to be, as specified in [this thing](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3781.pdf). +To do that, we'll probably need some lookahead / behind magic which I am not familiar with, and it will increase the complexity of the (imo already complex) regex. + +Before: + +![image](https://github.com/user-attachments/assets/01b57466-73d5-4bb8-a88b-64954dd476a9) + +After: + +![image](https://github.com/user-attachments/assets/ed090209-6b87-4dd9-a1d2-61b505443317) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f30214464c06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2026/tests/oracle.patch b/tasks/lite-xl__lite-xl-2026/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..033bcc2d05553fe02b9bd27e63e3693d03968c47 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/data/plugins/language_c.lua b/data/plugins/language_c.lua +index 2804fb7b..f80cd47c 100644 +--- a/data/plugins/language_c.lua ++++ b/data/plugins/language_c.lua +@@ -5,6 +5,8 @@ local syntax = require "core.syntax" + local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] + -- float suffix combinations as a Lua pattern / regex + local fsuf = "[fFlL]?" ++-- number with digit separator as a regex non-capturing group ++local digitsep = [[(?:\d[\d']*)]] + + syntax.add { + name = "C", +@@ -12,21 +14,18 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, +- { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, +- { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+%.%d*"..fsuf, type = "number" }, +- { pattern = "%.%d+"..fsuf, type = "number" }, +- { regex = "\\d+"..isuf, type = "number" }, +- { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, +- { pattern = "##", type = "operator" }, +- { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { regex = "0x[0-9a-fA-F][0-9a-fA-F']*"..isuf, type = "number" }, ++ { regex = "0()[0-7][0-7']*"..isuf, type = { "keyword", "number" } }, ++ { regex = digitsep.."\\.?"..digitsep.."?(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { regex = "\\."..digitsep.."(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { pattern = "[%+%-=/%*%^%%<>!~|&]", type = "operator" }, ++ { pattern = "##", type = "operator" }, ++ { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, + -- static declarations + { pattern = "static()%s+()inline", + type = { "keyword", "normal", "keyword" } +diff --git a/data/plugins/language_cpp.lua b/data/plugins/language_cpp.lua +index 2bbc688e..7e604577 100644 +--- a/data/plugins/language_cpp.lua ++++ b/data/plugins/language_cpp.lua +@@ -5,6 +5,8 @@ local syntax = require "core.syntax" + local isuf = [[(?:[lL][uU]|ll[uU]|LL[uU]|[uU][lL]\b|[uU]ll|[uU]LL|[uU]|[lL]\b|ll|LL)?]] + -- float suffix combinations as a Lua pattern / regex + local fsuf = "[fFlL]?" ++-- number with digit separator as a regex non-capturing group ++local digitsep = [[(?:\d[\d']*)]] + + syntax.add { + name = "C++", +@@ -16,24 +18,21 @@ syntax.add { + comment = "//", + block_comment = { "/*", "*/" }, + patterns = { +- { pattern = "//.*", type = "comment" }, +- { pattern = { "/%*", "%*/" }, type = "comment" }, +- { pattern = { '"', '"', '\\' }, type = "string" }, +- { pattern = { "'", "'", '\\' }, type = "string" }, +- { regex = "0x[0-9a-fA-f]+"..isuf, type = "number" }, +- { regex = "0b[01]+"..isuf, type = "number" }, +- { regex = "0()[0-7]+"..isuf, type = { "keyword", "number" } }, +- { pattern = "%d+%.%d*[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+[Ee]%d+"..fsuf, type = "number" }, +- { pattern = "%d+%.%d*"..fsuf, type = "number" }, +- { pattern = "%.%d+"..fsuf, type = "number" }, +- { regex = "\\d+"..isuf, type = "number" }, +- { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, +- { pattern = "##", type = "operator" }, +- { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "class%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, +- { pattern = "namespace%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "//.*", type = "comment" }, ++ { pattern = { "/%*", "%*/" }, type = "comment" }, ++ { pattern = { '"', '"', '\\' }, type = "string" }, ++ { pattern = { "'", "'", '\\' }, type = "string" }, ++ { regex = "0x[0-9a-fA-F][0-9a-fA-F']*"..isuf, type = "number" }, ++ { regex = "0b[01][01']*"..isuf, type = "number" }, ++ { regex = "0()[0-7][0-7']*"..isuf, type = { "keyword", "number" } }, ++ { regex = digitsep.."\\.?"..digitsep.."?(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { regex = "\\."..digitsep.."(?:[Ee][-+]?"..digitsep..")?"..fsuf, type = "number" }, ++ { pattern = "[%+%-=/%*%^%%<>!~|:&]", type = "operator" }, ++ { pattern = "##", type = "operator" }, ++ { pattern = "struct%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "class%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "union%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, ++ { pattern = "namespace%s()[%a_][%w_]*", type = {"keyword", "keyword2"} }, + -- static declarations + { pattern = "static()%s+()inline", + type = { "keyword", "normal", "keyword" } diff --git a/tasks/lite-xl__lite-xl-2026/tests/test.sh b/tasks/lite-xl__lite-xl-2026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..115f9a2dd9299482170a3b2a709a7b48d59a23d2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/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 f30214464c0613c281c91be192c2ef8360f3543e > "$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/lite-xl__lite-xl-2026/tests/verifier.py b/tasks/lite-xl__lite-xl-2026/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2026/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/lite-xl__lite-xl-2028/environment/Dockerfile b/tasks/lite-xl__lite-xl-2028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8a6442ad7589d43270a50b4bcad19ec84c5aa1a5 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9b70aec31de3d7c179fc8425d7af7babd96be2c5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9b70aec31de3d7c179fc8425d7af7babd96be2c5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9b70aec31de3d7c179fc8425d7af7babd96be2c5 \ + && 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/lite-xl__lite-xl-2028/instruction.md b/tasks/lite-xl__lite-xl-2028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..658d19ba532d80483ca47b9d5565e6c1b7e917ca --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** common.sh: support OSTYPE == cygwin for MSYS2 + +## Description + +and most CI builds. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b70aec31de3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2028/solution/patch.diff b/tasks/lite-xl__lite-xl-2028/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c164d1fcb3b6d933ba38d54b62b4f36547242bd4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/solution/patch.diff @@ -0,0 +1,22 @@ +diff --git a/scripts/common.sh b/scripts/common.sh +index 3cc6836d..45ad2847 100644 +--- a/scripts/common.sh ++++ b/scripts/common.sh +@@ -3,7 +3,7 @@ + set -e + + get_platform_name() { +- if [[ "$OSTYPE" == "msys" ]]; then ++ if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then + echo "windows" + elif [[ "$OSTYPE" == "darwin"* ]]; then + echo "darwin" +@@ -15,7 +15,7 @@ get_platform_name() { + } + + get_executable_extension() { +- if [[ "$OSTYPE" == "msys" ]]; then ++ if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then + echo ".exe" + else + echo "" diff --git a/tasks/lite-xl__lite-xl-2028/solution/solve.sh b/tasks/lite-xl__lite-xl-2028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/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/lite-xl__lite-xl-2028/task.toml b/tasks/lite-xl__lite-xl-2028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1009947074fa42649a6a3503d603afda17659b82 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2028" +description = "common.sh: support OSTYPE == cygwin for MSYS2" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "9b70aec31de3d7c179fc8425d7af7babd96be2c5" +reference = "https://github.com/lite-xl/lite-xl/pull/2028" +source_access = "auto" +built_at = "2026-11-16T16:09:56.307816+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7feaa50a20820cdabcfead49682ce99896de9f06e2f764930b9c29ee1b62e1d7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-01T17:23:57Z" +diff_format = "unified" +context_files = [ + "scripts/common.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.318064+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0091981cb1fe781b99b716faf4f9abb2d67e67acaf11b02768b77effe5cc96c3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2028/tests/capture.py b/tasks/lite-xl__lite-xl-2028/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/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/lite-xl__lite-xl-2028/tests/instruction.md b/tasks/lite-xl__lite-xl-2028/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..658d19ba532d80483ca47b9d5565e6c1b7e917ca --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** common.sh: support OSTYPE == cygwin for MSYS2 + +## Description + +and most CI builds. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b70aec31de3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2028/tests/oracle.patch b/tasks/lite-xl__lite-xl-2028/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c164d1fcb3b6d933ba38d54b62b4f36547242bd4 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/tests/oracle.patch @@ -0,0 +1,22 @@ +diff --git a/scripts/common.sh b/scripts/common.sh +index 3cc6836d..45ad2847 100644 +--- a/scripts/common.sh ++++ b/scripts/common.sh +@@ -3,7 +3,7 @@ + set -e + + get_platform_name() { +- if [[ "$OSTYPE" == "msys" ]]; then ++ if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then + echo "windows" + elif [[ "$OSTYPE" == "darwin"* ]]; then + echo "darwin" +@@ -15,7 +15,7 @@ get_platform_name() { + } + + get_executable_extension() { +- if [[ "$OSTYPE" == "msys" ]]; then ++ if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then + echo ".exe" + else + echo "" diff --git a/tasks/lite-xl__lite-xl-2028/tests/test.sh b/tasks/lite-xl__lite-xl-2028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ffa5a9fd20f854093d158c7e545b6812cc4bee2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/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 9b70aec31de3d7c179fc8425d7af7babd96be2c5 > "$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/lite-xl__lite-xl-2028/tests/verifier.py b/tasks/lite-xl__lite-xl-2028/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2028/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/lite-xl__lite-xl-2029/environment/Dockerfile b/tasks/lite-xl__lite-xl-2029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94e6e356762c1e8bf64c307e94fd17146511acca --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f30214464c0613c281c91be192c2ef8360f3543e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f30214464c0613c281c91be192c2ef8360f3543e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f30214464c0613c281c91be192c2ef8360f3543e \ + && 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/lite-xl__lite-xl-2029/instruction.md b/tasks/lite-xl__lite-xl-2029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8ac08e576c48b2e9206f2697e3303e72022f2627 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** syntax: warn against malformed patterns and disable them + +## Description + +Complements #1743. + +This PR introduces some runtime checks when loading syntaxes via `syntax.add()`. +Currently, when you put garbage pattern / regex into the syntax like `[`, it usually crashes the editor. + +This PR checks if the patterns / regexes can actually be compiled and run. +It also checks if the pattern / regex can match an empty string, which isn't supposed to happen based on #1743. + +Example malformed patterns: +```lua + { regex = "[", type = "number" }, + { pattern = "[", type = "number" }, + { regex = ".?", type = "number" }, + { pattern = ".?", type = "number" }, +``` + +Example output: +![image](https://github.com/user-attachments/assets/896ac05d-d473-43e0-80b2-edbae481c7f7) + +Performance: + +
+Pretty much no difference. + +Before: +![image](https://github.com/user-attachments/assets/e5ea936d-a43f-44e5-82dd-2e762b53f796) + +After: +![image](https://github.com/user-attachments/assets/cac72540-a039-4900-9e77-624981bac6f0) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f30214464c06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2029/solution/patch.diff b/tasks/lite-xl__lite-xl-2029/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..60298b19316f5db44ae3f5ce30a5b4fda6c5a66f --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/solution/patch.diff @@ -0,0 +1,80 @@ +diff --git a/data/core/syntax.lua b/data/core/syntax.lua +index 6555a17c..61b9af8e 100644 +--- a/data/core/syntax.lua ++++ b/data/core/syntax.lua +@@ -1,4 +1,5 @@ + local common = require "core.common" ++local core = require "core" + + local syntax = {} + syntax.items = {} +@@ -6,10 +7,57 @@ syntax.items = {} + syntax.plain_text_syntax = { name = "Plain Text", patterns = {}, symbols = {} } + + ++---Checks whether the pattern / regex compiles correctly and matches something. ++---A pattern / regex must not match an empty string. ++---@param pattern_type "regex"|"pattern" ++---@param pattern string ++---@return boolean ok ++---@return string? error ++local function check_pattern(pattern_type, pattern) ++ local ok, err, mstart, mend ++ if pattern_type == "regex" then ++ ok, err = regex.compile(pattern) ++ if ok then ++ mstart, mend = regex.find_offsets(ok, "") ++ if mstart and mstart > mend then ++ ok, err = false, "Regex matches an empty string" ++ end ++ end ++ else ++ ok, mstart, mend = pcall(string.ufind, "", pattern) ++ if ok and mstart and mstart > mend then ++ ok, err = false, "Pattern matches an empty string" ++ elseif not ok then ++ err = mstart --[[@as string]] ++ end ++ end ++ return ok --[[@as boolean]], err ++end ++ + function syntax.add(t) + if type(t.space_handling) ~= "boolean" then t.space_handling = true end + + if t.patterns then ++ -- do a sanity check on the patterns / regex to make sure they are actually correct ++ for i, pattern in ipairs(t.patterns) do ++ local p, ok, err, name = pattern.pattern or pattern.regex, nil, nil, nil ++ if type(p) == "table" then ++ for j = 1, 2 do ++ ok, err = check_pattern(pattern.pattern and "pattern" or "regex", p[j]) ++ if not ok then name = string.format("#%d:%d <%s>", i, j, p[j]) end ++ end ++ elseif type(p) == "string" then ++ ok, err = check_pattern(pattern.pattern and "pattern" or "regex", p) ++ if not ok then name = string.format("#%d <%s>", i, p) end ++ else ++ ok, err, name = false, "Missing pattern or regex", "#"..i ++ end ++ if not ok then ++ pattern.disabled = true ++ core.warn("Malformed pattern %s in %s language plugin: %s", name, t.name, err) ++ end ++ end ++ + -- the rule %s+ gives us a performance gain for the tokenizer in lines with + -- long amounts of consecutive spaces, can be disabled by plugins where it + -- causes conflicts by declaring the table property: space_handling = false +diff --git a/data/core/tokenizer.lua b/data/core/tokenizer.lua +index b8f0fe04..ca2339bd 100644 +--- a/data/core/tokenizer.lua ++++ b/data/core/tokenizer.lua +@@ -203,6 +203,7 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + local target, res = p.pattern or p.regex, { 1, offset - 1 } + local p_idx = close and 2 or 1 + local code = type(target) == "table" and target[p_idx] or target ++ if p.disabled then return end + + if p.whole_line == nil then p.whole_line = { } end + if p.whole_line[p_idx] == nil then diff --git a/tasks/lite-xl__lite-xl-2029/solution/solve.sh b/tasks/lite-xl__lite-xl-2029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/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/lite-xl__lite-xl-2029/task.toml b/tasks/lite-xl__lite-xl-2029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d1e4a3efafe4214ad65458d048e81870b0335ba --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2029" +description = "syntax: warn against malformed patterns and disable them" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "f30214464c0613c281c91be192c2ef8360f3543e" +reference = "https://github.com/lite-xl/lite-xl/pull/2029" +source_access = "auto" +built_at = "2026-11-16T16:09:56.296104+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0a6d3b63ebe8f77f19b55ba52d23207abb81b3b93a9413ee0afdbc377c948779" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-15T16:08:25Z" +diff_format = "unified" +context_files = [ + "data/core/syntax.lua", + "data/core/tokenizer.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.318511+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d563eb1b475a366408607c5569c9a14e2bc3d6ea03bab6df6cdc729a734eff0d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2029/tests/capture.py b/tasks/lite-xl__lite-xl-2029/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/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/lite-xl__lite-xl-2029/tests/instruction.md b/tasks/lite-xl__lite-xl-2029/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8ac08e576c48b2e9206f2697e3303e72022f2627 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/tests/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** syntax: warn against malformed patterns and disable them + +## Description + +Complements #1743. + +This PR introduces some runtime checks when loading syntaxes via `syntax.add()`. +Currently, when you put garbage pattern / regex into the syntax like `[`, it usually crashes the editor. + +This PR checks if the patterns / regexes can actually be compiled and run. +It also checks if the pattern / regex can match an empty string, which isn't supposed to happen based on #1743. + +Example malformed patterns: +```lua + { regex = "[", type = "number" }, + { pattern = "[", type = "number" }, + { regex = ".?", type = "number" }, + { pattern = ".?", type = "number" }, +``` + +Example output: +![image](https://github.com/user-attachments/assets/896ac05d-d473-43e0-80b2-edbae481c7f7) + +Performance: + +
+Pretty much no difference. + +Before: +![image](https://github.com/user-attachments/assets/e5ea936d-a43f-44e5-82dd-2e762b53f796) + +After: +![image](https://github.com/user-attachments/assets/cac72540-a039-4900-9e77-624981bac6f0) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f30214464c06`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2029/tests/oracle.patch b/tasks/lite-xl__lite-xl-2029/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..60298b19316f5db44ae3f5ce30a5b4fda6c5a66f --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/tests/oracle.patch @@ -0,0 +1,80 @@ +diff --git a/data/core/syntax.lua b/data/core/syntax.lua +index 6555a17c..61b9af8e 100644 +--- a/data/core/syntax.lua ++++ b/data/core/syntax.lua +@@ -1,4 +1,5 @@ + local common = require "core.common" ++local core = require "core" + + local syntax = {} + syntax.items = {} +@@ -6,10 +7,57 @@ syntax.items = {} + syntax.plain_text_syntax = { name = "Plain Text", patterns = {}, symbols = {} } + + ++---Checks whether the pattern / regex compiles correctly and matches something. ++---A pattern / regex must not match an empty string. ++---@param pattern_type "regex"|"pattern" ++---@param pattern string ++---@return boolean ok ++---@return string? error ++local function check_pattern(pattern_type, pattern) ++ local ok, err, mstart, mend ++ if pattern_type == "regex" then ++ ok, err = regex.compile(pattern) ++ if ok then ++ mstart, mend = regex.find_offsets(ok, "") ++ if mstart and mstart > mend then ++ ok, err = false, "Regex matches an empty string" ++ end ++ end ++ else ++ ok, mstart, mend = pcall(string.ufind, "", pattern) ++ if ok and mstart and mstart > mend then ++ ok, err = false, "Pattern matches an empty string" ++ elseif not ok then ++ err = mstart --[[@as string]] ++ end ++ end ++ return ok --[[@as boolean]], err ++end ++ + function syntax.add(t) + if type(t.space_handling) ~= "boolean" then t.space_handling = true end + + if t.patterns then ++ -- do a sanity check on the patterns / regex to make sure they are actually correct ++ for i, pattern in ipairs(t.patterns) do ++ local p, ok, err, name = pattern.pattern or pattern.regex, nil, nil, nil ++ if type(p) == "table" then ++ for j = 1, 2 do ++ ok, err = check_pattern(pattern.pattern and "pattern" or "regex", p[j]) ++ if not ok then name = string.format("#%d:%d <%s>", i, j, p[j]) end ++ end ++ elseif type(p) == "string" then ++ ok, err = check_pattern(pattern.pattern and "pattern" or "regex", p) ++ if not ok then name = string.format("#%d <%s>", i, p) end ++ else ++ ok, err, name = false, "Missing pattern or regex", "#"..i ++ end ++ if not ok then ++ pattern.disabled = true ++ core.warn("Malformed pattern %s in %s language plugin: %s", name, t.name, err) ++ end ++ end ++ + -- the rule %s+ gives us a performance gain for the tokenizer in lines with + -- long amounts of consecutive spaces, can be disabled by plugins where it + -- causes conflicts by declaring the table property: space_handling = false +diff --git a/data/core/tokenizer.lua b/data/core/tokenizer.lua +index b8f0fe04..ca2339bd 100644 +--- a/data/core/tokenizer.lua ++++ b/data/core/tokenizer.lua +@@ -203,6 +203,7 @@ function tokenizer.tokenize(incoming_syntax, text, state, resume) + local target, res = p.pattern or p.regex, { 1, offset - 1 } + local p_idx = close and 2 or 1 + local code = type(target) == "table" and target[p_idx] or target ++ if p.disabled then return end + + if p.whole_line == nil then p.whole_line = { } end + if p.whole_line[p_idx] == nil then diff --git a/tasks/lite-xl__lite-xl-2029/tests/test.sh b/tasks/lite-xl__lite-xl-2029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..115f9a2dd9299482170a3b2a709a7b48d59a23d2 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/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 f30214464c0613c281c91be192c2ef8360f3543e > "$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/lite-xl__lite-xl-2029/tests/verifier.py b/tasks/lite-xl__lite-xl-2029/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2029/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/lite-xl__lite-xl-2039/environment/Dockerfile b/tasks/lite-xl__lite-xl-2039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79f6aaffbbf5305249b71b69391ee9b034229a9a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 819fa9d30e2c0e737fad519fbff63ce2baff4456 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 819fa9d30e2c0e737fad519fbff63ce2baff4456 \ + && 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/lite-xl__lite-xl-2039/instruction.md b/tasks/lite-xl__lite-xl-2039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8574e9c9c9b087357cbc488f722071d2129c015d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Made findfile update suggestions as more results come in. + +## Description + +This is the simplest way to fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2039/solution/patch.diff b/tasks/lite-xl__lite-xl-2039/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c9671febae1cfae6e5a78f9508ec5a5c578019e8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/solution/patch.diff @@ -0,0 +1,155 @@ +diff --git a/data/core/commandview.lua b/data/core/commandview.lua +index 9b1b7fce..eac4fc26 100644 +--- a/data/core/commandview.lua ++++ b/data/core/commandview.lua +@@ -58,6 +58,8 @@ function CommandView:new() + self.suggestions_height = 0 + self.last_change_id = 0 + self.last_text = "" ++ self.user_supplied_text = "" ++ self.last_change = "text" + self.gutter_width = 0 + self.gutter_text_brightness = 0 + self.selection_offset = 0 +@@ -150,6 +152,7 @@ function CommandView:move_suggestion_idx(dir) + return self.suggestions_offset + end + ++ self.last_change = "suggestion" + if self.state.show_suggestions then + local n = self.suggestion_idx + dir + self.suggestion_idx = overflow_suggestion_idx(n, #self.suggestions) +@@ -275,7 +278,8 @@ end + + + function CommandView:update_suggestions() +- local t = self.state.suggest(self:get_text()) or {} ++ local text = self:get_text() ++ local t = self.state.suggest(self.last_change == "suggestion" and self.user_supplied_text or text) or {} + local res = {} + for i, item in ipairs(t) do + if type(item) == "string" then +@@ -283,9 +287,22 @@ function CommandView:update_suggestions() + end + res[i] = item + end ++ if self.suggestions and self.last_change == "suggestion" then ++ local new_suggestion_idx ++ for i, v in ipairs(res) do ++ if v.text == self.suggestions[self.suggestion_idx].text then ++ new_suggestion_idx = i ++ break ++ end ++ end ++ self.suggestion_idx = new_suggestion_idx ++ -- This preserves the suggestion_offset and realigns it with the new table. ++ self:move_suggestion_idx(0) ++ else ++ self.suggestion_idx = 1 ++ self.suggestions_offset = 1 ++ end + self.suggestions = res +- self.suggestion_idx = 1 +- self.suggestions_offset = 1 + end + + +@@ -298,6 +315,8 @@ function CommandView:update() + + -- update suggestions if text has changed + if self.last_change_id ~= self.doc:get_change_id() then ++ self.last_change = "text" ++ self.user_supplied_text = self:get_text() + self:update_suggestions() + if self.state.typeahead and self.suggestions[self.suggestion_idx] then + local current_text = self:get_text() +diff --git a/data/core/common.lua b/data/core/common.lua +index 167e5b0e..50ff0233 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -152,6 +152,9 @@ end + + + local function compare_score(a, b) ++ if a.score == b.score then ++ return a.text < b.text ++ end + return a.score > b.score + end + +diff --git a/data/plugins/findfile.lua b/data/plugins/findfile.lua +index 1b201362..4eb6ff9b 100644 +--- a/data/plugins/findfile.lua ++++ b/data/plugins/findfile.lua +@@ -7,31 +7,52 @@ local config = require "core.config" + local keymap = require "core.keymap" + + config.plugins.findfile = common.merge({ ++ -- how many files from the project we store in a list before we stop + file_limit = 20000, +- max_search_time = 2.0 ++ -- the maximum amount of time we spend gathering files before stopping ++ max_search_time = 10.0, ++ -- the amount of time we wait between loops of gathering files ++ interval = 0, ++ -- the amount of time we spend in a single loop (by default, half a frame) ++ max_loop_time = 0.5 / config.fps + }, config.plugins.findfile) + + + command.add(nil, { + ["core:find-file"] = function() + local files, complete = {}, false +- local k = core.add_thread(function() ++ local refresh = coroutine.wrap(function() + local start, total = system.get_time(), 0 + for i, project in ipairs(core.projects) do + for project, item in project:files() do +- if complete or #files > config.plugins.findfile.file_limit then return end ++ if complete then return end ++ if #files > config.plugins.findfile.file_limit then ++ core.command_view:update_suggestions() ++ return ++ end + table.insert(files, i == 1 and item.filename:sub(#project.path + 2) or common.home_encode(item.filename)) + local diff = system.get_time() - start +- if diff > 2 / config.fps then ++ if diff > config.plugins.findfile.max_loop_time then ++ core.command_view:update_suggestions() + total = total + diff + if total > config.plugins.findfile.max_search_time then return end +- coroutine.yield(0.1) ++ coroutine.yield(config.plugins.findfile.interval) + start = system.get_time() + end + end + end + end) +- coroutine.resume(core.threads[k].cr) ++ ++ local wait = refresh() ++ if wait then ++ core.add_thread(function() ++ while wait do ++ wait = refresh() ++ coroutine.yield(wait) ++ end ++ end) ++ end ++ local original_files + core.command_view:enter("Open File From Project", { + submit = function(text, item) + text = item and item.text or text +@@ -39,7 +60,11 @@ command.add(nil, { + complete = true + end, + suggest = function(text) +- return common.fuzzy_match_with_recents(files, core.visited_files, text) ++ if original_files and text == "" then ++ return original_files ++ end ++ original_files = common.fuzzy_match_with_recents(files, core.visited_files, text) ++ return original_files + end, + cancel = function() + complete = true diff --git a/tasks/lite-xl__lite-xl-2039/solution/solve.sh b/tasks/lite-xl__lite-xl-2039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/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/lite-xl__lite-xl-2039/task.toml b/tasks/lite-xl__lite-xl-2039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f7c634a398485be77df3fbef98bb16c68110e5c --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2039" +description = "Made findfile update suggestions as more results come in." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "819fa9d30e2c0e737fad519fbff63ce2baff4456" +reference = "https://github.com/lite-xl/lite-xl/pull/2039" +source_access = "auto" +built_at = "2026-11-16T16:09:56.180601+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bd0749d830a23a39d37a2671c8c3b69a3322c88ddef7d5974b3003a958c21494" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-06-14T01:49:39Z" +diff_format = "unified" +context_files = [ + "data/core/commandview.lua", + "data/core/common.lua", + "data/plugins/findfile.lua", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 67 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.318954+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8157ccb850d65e11de5d9535f476f68f7af87fe114bfff9d7bfe590be94ed8a2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2039/tests/capture.py b/tasks/lite-xl__lite-xl-2039/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/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/lite-xl__lite-xl-2039/tests/instruction.md b/tasks/lite-xl__lite-xl-2039/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8574e9c9c9b087357cbc488f722071d2129c015d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Made findfile update suggestions as more results come in. + +## Description + +This is the simplest way to fix. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `819fa9d30e2c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2039/tests/oracle.patch b/tasks/lite-xl__lite-xl-2039/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c9671febae1cfae6e5a78f9508ec5a5c578019e8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/tests/oracle.patch @@ -0,0 +1,155 @@ +diff --git a/data/core/commandview.lua b/data/core/commandview.lua +index 9b1b7fce..eac4fc26 100644 +--- a/data/core/commandview.lua ++++ b/data/core/commandview.lua +@@ -58,6 +58,8 @@ function CommandView:new() + self.suggestions_height = 0 + self.last_change_id = 0 + self.last_text = "" ++ self.user_supplied_text = "" ++ self.last_change = "text" + self.gutter_width = 0 + self.gutter_text_brightness = 0 + self.selection_offset = 0 +@@ -150,6 +152,7 @@ function CommandView:move_suggestion_idx(dir) + return self.suggestions_offset + end + ++ self.last_change = "suggestion" + if self.state.show_suggestions then + local n = self.suggestion_idx + dir + self.suggestion_idx = overflow_suggestion_idx(n, #self.suggestions) +@@ -275,7 +278,8 @@ end + + + function CommandView:update_suggestions() +- local t = self.state.suggest(self:get_text()) or {} ++ local text = self:get_text() ++ local t = self.state.suggest(self.last_change == "suggestion" and self.user_supplied_text or text) or {} + local res = {} + for i, item in ipairs(t) do + if type(item) == "string" then +@@ -283,9 +287,22 @@ function CommandView:update_suggestions() + end + res[i] = item + end ++ if self.suggestions and self.last_change == "suggestion" then ++ local new_suggestion_idx ++ for i, v in ipairs(res) do ++ if v.text == self.suggestions[self.suggestion_idx].text then ++ new_suggestion_idx = i ++ break ++ end ++ end ++ self.suggestion_idx = new_suggestion_idx ++ -- This preserves the suggestion_offset and realigns it with the new table. ++ self:move_suggestion_idx(0) ++ else ++ self.suggestion_idx = 1 ++ self.suggestions_offset = 1 ++ end + self.suggestions = res +- self.suggestion_idx = 1 +- self.suggestions_offset = 1 + end + + +@@ -298,6 +315,8 @@ function CommandView:update() + + -- update suggestions if text has changed + if self.last_change_id ~= self.doc:get_change_id() then ++ self.last_change = "text" ++ self.user_supplied_text = self:get_text() + self:update_suggestions() + if self.state.typeahead and self.suggestions[self.suggestion_idx] then + local current_text = self:get_text() +diff --git a/data/core/common.lua b/data/core/common.lua +index 167e5b0e..50ff0233 100644 +--- a/data/core/common.lua ++++ b/data/core/common.lua +@@ -152,6 +152,9 @@ end + + + local function compare_score(a, b) ++ if a.score == b.score then ++ return a.text < b.text ++ end + return a.score > b.score + end + +diff --git a/data/plugins/findfile.lua b/data/plugins/findfile.lua +index 1b201362..4eb6ff9b 100644 +--- a/data/plugins/findfile.lua ++++ b/data/plugins/findfile.lua +@@ -7,31 +7,52 @@ local config = require "core.config" + local keymap = require "core.keymap" + + config.plugins.findfile = common.merge({ ++ -- how many files from the project we store in a list before we stop + file_limit = 20000, +- max_search_time = 2.0 ++ -- the maximum amount of time we spend gathering files before stopping ++ max_search_time = 10.0, ++ -- the amount of time we wait between loops of gathering files ++ interval = 0, ++ -- the amount of time we spend in a single loop (by default, half a frame) ++ max_loop_time = 0.5 / config.fps + }, config.plugins.findfile) + + + command.add(nil, { + ["core:find-file"] = function() + local files, complete = {}, false +- local k = core.add_thread(function() ++ local refresh = coroutine.wrap(function() + local start, total = system.get_time(), 0 + for i, project in ipairs(core.projects) do + for project, item in project:files() do +- if complete or #files > config.plugins.findfile.file_limit then return end ++ if complete then return end ++ if #files > config.plugins.findfile.file_limit then ++ core.command_view:update_suggestions() ++ return ++ end + table.insert(files, i == 1 and item.filename:sub(#project.path + 2) or common.home_encode(item.filename)) + local diff = system.get_time() - start +- if diff > 2 / config.fps then ++ if diff > config.plugins.findfile.max_loop_time then ++ core.command_view:update_suggestions() + total = total + diff + if total > config.plugins.findfile.max_search_time then return end +- coroutine.yield(0.1) ++ coroutine.yield(config.plugins.findfile.interval) + start = system.get_time() + end + end + end + end) +- coroutine.resume(core.threads[k].cr) ++ ++ local wait = refresh() ++ if wait then ++ core.add_thread(function() ++ while wait do ++ wait = refresh() ++ coroutine.yield(wait) ++ end ++ end) ++ end ++ local original_files + core.command_view:enter("Open File From Project", { + submit = function(text, item) + text = item and item.text or text +@@ -39,7 +60,11 @@ command.add(nil, { + complete = true + end, + suggest = function(text) +- return common.fuzzy_match_with_recents(files, core.visited_files, text) ++ if original_files and text == "" then ++ return original_files ++ end ++ original_files = common.fuzzy_match_with_recents(files, core.visited_files, text) ++ return original_files + end, + cancel = function() + complete = true diff --git a/tasks/lite-xl__lite-xl-2039/tests/test.sh b/tasks/lite-xl__lite-xl-2039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b633fca4f9bab861c01a786a0068cc7c5aeb58d3 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/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 819fa9d30e2c0e737fad519fbff63ce2baff4456 > "$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/lite-xl__lite-xl-2039/tests/verifier.py b/tasks/lite-xl__lite-xl-2039/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2039/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/lite-xl__lite-xl-2043/environment/Dockerfile b/tasks/lite-xl__lite-xl-2043/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5623605c97dc8d4c3ce430f2c8811e77e0ff4e6c --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin beb9c58084ea60eadc9b72184088e6a2325e66cf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && 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/lite-xl__lite-xl-2043/instruction.md b/tasks/lite-xl__lite-xl-2043/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d972954f05dfb2cc032119a5625fbda903c0346 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Added a manifest.json. + +## Description + +Once I add this repo to `lite-xl-plugin-manager`'s init, you should be able to start just pulling lite-xls based off this repo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2043/solution/patch.diff b/tasks/lite-xl__lite-xl-2043/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cbcd561f9c48c92af7882527a85135ff0c0eafc8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/manifest.json b/manifest.json +new file mode 100644 +index 00000000..1df0c5c2 +--- /dev/null ++++ b/manifest.json +@@ -0,0 +1,61 @@ ++{ ++ "lite-xls": [ ++ { ++ "files": [ ++ { ++ "arch": [ ++ "x86_64-darwin", ++ "aarch64-darwin" ++ ], ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-universal-darwin-portable.tar.gz" ++ }, ++ { ++ "arch": "x86_64-linux", ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-x86_64-linux-portable.tar.gz" ++ }, ++ { ++ "arch": "x86_64-windows", ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-x86_64-windows-portable.zip" ++ } ++ ], ++ "mod_version": "4", ++ "version": "3.0-continuous" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "430afb894801200c3fcf4123e3bb17006b369c25bc59c39bf04b4bcafeb96ee6", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.7/lite-xl-v2.1.7-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.7" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "13523ff6713dc839338fd306263f714d13a062a4a718a01df12f0d3fd98a187f", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.6/lite-xl-v2.1.6-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.6" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "ae1ad1a5fa5820a812f83e0624d1198b349f55045f3ec045e292fcefa542eab0", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.5/lite-xl-v2.1.5-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.5" ++ } ++ ] ++} diff --git a/tasks/lite-xl__lite-xl-2043/solution/solve.sh b/tasks/lite-xl__lite-xl-2043/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/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/lite-xl__lite-xl-2043/task.toml b/tasks/lite-xl__lite-xl-2043/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0dcfa7f3bb5cb12c8545448c8453ff8b7b341ee0 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2043" +description = "Added a manifest.json." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "beb9c58084ea60eadc9b72184088e6a2325e66cf" +reference = "https://github.com/lite-xl/lite-xl/pull/2043" +source_access = "auto" +built_at = "2026-11-16T16:09:56.181984+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5a2c462717f16242aaa9dd0b6831531c4948813ff2c8855d275bdc0a4639ac20" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-18T14:06:29Z" +diff_format = "unified" +context_files = [ + "manifest.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 61 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.319419+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:41289b24a16f7e138a7bcddb2669c2b475a76295db329b260eb1f05eb3d8be9f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2043/tests/capture.py b/tasks/lite-xl__lite-xl-2043/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/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/lite-xl__lite-xl-2043/tests/instruction.md b/tasks/lite-xl__lite-xl-2043/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d972954f05dfb2cc032119a5625fbda903c0346 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Added a manifest.json. + +## Description + +Once I add this repo to `lite-xl-plugin-manager`'s init, you should be able to start just pulling lite-xls based off this repo. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2043/tests/oracle.patch b/tasks/lite-xl__lite-xl-2043/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cbcd561f9c48c92af7882527a85135ff0c0eafc8 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/manifest.json b/manifest.json +new file mode 100644 +index 00000000..1df0c5c2 +--- /dev/null ++++ b/manifest.json +@@ -0,0 +1,61 @@ ++{ ++ "lite-xls": [ ++ { ++ "files": [ ++ { ++ "arch": [ ++ "x86_64-darwin", ++ "aarch64-darwin" ++ ], ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-universal-darwin-portable.tar.gz" ++ }, ++ { ++ "arch": "x86_64-linux", ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-x86_64-linux-portable.tar.gz" ++ }, ++ { ++ "arch": "x86_64-windows", ++ "checksum": "SKIP", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/continuous/lite-xl-continuous-x86_64-windows-portable.zip" ++ } ++ ], ++ "mod_version": "4", ++ "version": "3.0-continuous" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "430afb894801200c3fcf4123e3bb17006b369c25bc59c39bf04b4bcafeb96ee6", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.7/lite-xl-v2.1.7-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.7" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "13523ff6713dc839338fd306263f714d13a062a4a718a01df12f0d3fd98a187f", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.6/lite-xl-v2.1.6-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.6" ++ }, ++ { ++ "files": [ ++ { ++ "arch": "linux-x86_64", ++ "checksum": "ae1ad1a5fa5820a812f83e0624d1198b349f55045f3ec045e292fcefa542eab0", ++ "url": "https://github.com/lite-xl/lite-xl/releases/download/v2.1.5/lite-xl-v2.1.5-linux-x86_64-portable.tar.gz" ++ } ++ ], ++ "mod_version": "3.0.0", ++ "version": "2.1.5" ++ } ++ ] ++} diff --git a/tasks/lite-xl__lite-xl-2043/tests/test.sh b/tasks/lite-xl__lite-xl-2043/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aaaad4268f194f343f357f481b99487d38a2f6bc --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/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 beb9c58084ea60eadc9b72184088e6a2325e66cf > "$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/lite-xl__lite-xl-2043/tests/verifier.py b/tasks/lite-xl__lite-xl-2043/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2043/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/lite-xl__lite-xl-2044/environment/Dockerfile b/tasks/lite-xl__lite-xl-2044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5623605c97dc8d4c3ce430f2c8811e77e0ff4e6c --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin beb9c58084ea60eadc9b72184088e6a2325e66cf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base beb9c58084ea60eadc9b72184088e6a2325e66cf \ + && 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/lite-xl__lite-xl-2044/instruction.md b/tasks/lite-xl__lite-xl-2044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d6139f00c93cd76dbeadcde5877c758283d2e50 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Dirmonitor Fix: IN_IGNORE. + +## Description + +The IN_IGNORED event is generated when a watch is dropped. If we add and remove a watch due to document visibility changes, this leads to a feedback loop of constantly watching and unwatching the same file, and leading to like 45% CPU usage. + +Better to simply ignore this event, I think. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2044/solution/patch.diff b/tasks/lite-xl__lite-xl-2044/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..93ec6f075dc9298e73fd6dac258bb05db8bcd06b --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/solution/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/api/dirmonitor/inotify.c b/src/api/dirmonitor/inotify.c +index 4d2f8458..117e7286 100644 +--- a/src/api/dirmonitor/inotify.c ++++ b/src/api/dirmonitor/inotify.c +@@ -37,8 +37,10 @@ int get_changes_dirmonitor(struct dirmonitor_internal* monitor, char* buffer, in + + + int translate_changes_dirmonitor(struct dirmonitor_internal* monitor, char* buffer, int length, int (*change_callback)(int, const char*, void*), void* data) { +- for (struct inotify_event* info = (struct inotify_event*)buffer; (char*)info < buffer + length; info = (struct inotify_event*)((char*)info + sizeof(struct inotify_event))) +- change_callback(info->wd, NULL, data); ++ for (struct inotify_event* info = (struct inotify_event*)buffer; (char*)info < buffer + length; info = (struct inotify_event*)((char*)info + sizeof(struct inotify_event))) { ++ if ((info->mask & (~IN_IGNORED)) > 0) ++ change_callback(info->wd, NULL, data); ++ } + return 0; + } + diff --git a/tasks/lite-xl__lite-xl-2044/solution/solve.sh b/tasks/lite-xl__lite-xl-2044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/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/lite-xl__lite-xl-2044/task.toml b/tasks/lite-xl__lite-xl-2044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f7973ea9b7ca4e512bb6eda71007048f4b58868 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2044" +description = "Dirmonitor Fix: IN_IGNORE." + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "beb9c58084ea60eadc9b72184088e6a2325e66cf" +reference = "https://github.com/lite-xl/lite-xl/pull/2044" +source_access = "auto" +built_at = "2026-11-16T16:09:56.183419+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fde7150940606836224a3e73b9c9c6df55d6a1b895124e9161193207f6ee09c4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-05-18T14:05:56Z" +diff_format = "unified" +context_files = [ + "src/api/dirmonitor/inotify.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.319886+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:41289b24a16f7e138a7bcddb2669c2b475a76295db329b260eb1f05eb3d8be9f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2044/tests/capture.py b/tasks/lite-xl__lite-xl-2044/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/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/lite-xl__lite-xl-2044/tests/instruction.md b/tasks/lite-xl__lite-xl-2044/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d6139f00c93cd76dbeadcde5877c758283d2e50 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Dirmonitor Fix: IN_IGNORE. + +## Description + +The IN_IGNORED event is generated when a watch is dropped. If we add and remove a watch due to document visibility changes, this leads to a feedback loop of constantly watching and unwatching the same file, and leading to like 45% CPU usage. + +Better to simply ignore this event, I think. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `beb9c58084ea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2044/tests/oracle.patch b/tasks/lite-xl__lite-xl-2044/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..93ec6f075dc9298e73fd6dac258bb05db8bcd06b --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/tests/oracle.patch @@ -0,0 +1,17 @@ +diff --git a/src/api/dirmonitor/inotify.c b/src/api/dirmonitor/inotify.c +index 4d2f8458..117e7286 100644 +--- a/src/api/dirmonitor/inotify.c ++++ b/src/api/dirmonitor/inotify.c +@@ -37,8 +37,10 @@ int get_changes_dirmonitor(struct dirmonitor_internal* monitor, char* buffer, in + + + int translate_changes_dirmonitor(struct dirmonitor_internal* monitor, char* buffer, int length, int (*change_callback)(int, const char*, void*), void* data) { +- for (struct inotify_event* info = (struct inotify_event*)buffer; (char*)info < buffer + length; info = (struct inotify_event*)((char*)info + sizeof(struct inotify_event))) +- change_callback(info->wd, NULL, data); ++ for (struct inotify_event* info = (struct inotify_event*)buffer; (char*)info < buffer + length; info = (struct inotify_event*)((char*)info + sizeof(struct inotify_event))) { ++ if ((info->mask & (~IN_IGNORED)) > 0) ++ change_callback(info->wd, NULL, data); ++ } + return 0; + } + diff --git a/tasks/lite-xl__lite-xl-2044/tests/test.sh b/tasks/lite-xl__lite-xl-2044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..aaaad4268f194f343f357f481b99487d38a2f6bc --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/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 beb9c58084ea60eadc9b72184088e6a2325e66cf > "$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/lite-xl__lite-xl-2044/tests/verifier.py b/tasks/lite-xl__lite-xl-2044/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2044/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/lite-xl__lite-xl-2049/environment/Dockerfile b/tasks/lite-xl__lite-xl-2049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..07ae94301f239f7ef1992e72661bf5c11331abaa --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/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/lite-xl/lite-xl.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/lite-xl/lite-xl.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/lite-xl/lite-xl.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 79d3871e8e1e24d2289c472bfc7231b025589fcb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 79d3871e8e1e24d2289c472bfc7231b025589fcb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 79d3871e8e1e24d2289c472bfc7231b025589fcb \ + && 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/lite-xl__lite-xl-2049/instruction.md b/tasks/lite-xl__lite-xl-2049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47bfaa9fe640016688d66b95a924565a99800474 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/instruction.md @@ -0,0 +1,113 @@ +# Issue + +**Title:** LTO + +## Description + +We should use LTO for all (at least Linux) builds. +LTO generally comes in two flavors - thin and full LTO, where thinLTO is currently available on LLVM (clang) only. + +All examples here are compiled with clang and lld (v19.1.7) on 6.13.7-3-cachyos. + +### Highlights + +| Criteria | Non-LTO (Base) | Full LTO | thinLTO +| -------- | -------------- | -------- | ------- +| Tokenizer | 22743.91964 tok/sec | 25716.07018 tok/sec (+13.07%) | 25572.93249 tok/sec (+12.44%) +| Draw | 0.00675 ms/frame | 0.00470 ms/frame (-30.37%) | 0.00358 ms/frame (-46.96%) +| Binary Size | 3875520 Bytes | 3772728 Bytes (-2.65%) | 4012640 Bytes (+3.54%) + +
+Benchmarks of non-LTO, LTO and thinLTO builds + +Benchmark tests tokenizing [sqlite.c](https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip), as well as rendering text for 1000 frames. + +Benchmark code here: +[bootstrap.zip](https://github.com/user-attachments/files/19402579/bootstrap.zip) + +Run with: + +```sh +$ LDFLAGS='-fuse-ld=lld' CC=clang CXX=clang++ bash scripts/build.sh -P --forcefallback --lto && ln -s ../../../data/bootstrap.lua build-x86_64-linux/lite-xl/data/bootstrap.lua && LITE_XL_RUNTIME=bootstrap build-x86_64-linux/lite-xl/lite-xl tokenizer +$ LDFLAGS='-fuse-ld=lld' CC=clang CXX=clang++ bash scripts/build.sh -P --forcefallback --lto && ln -s ../../../data/bootstrap.lua build-x86_64-linux/lite-xl/data/bootstrap.lua && LITE_XL_RUNTIME=bootstrap build-x86_64-linux/lite-xl/lite-xl draw +``` + +## Tokenizer + +### Non-LTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: .......................Interrupted (more than 10s) +Tokenized sqlite.c with 230000 tokens in 10112.59289 ms, 22743.91964 tok/sec +``` + +### Full LTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: ...........................Interrupted (more than 10s) +Tokenized sqlite.c with 270000 tokens in 10499.27139 ms, 25716.07018 tok/sec +``` + +### ThinLTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: ..........................Interrupted (more than 10s) +Tokenized sqlite.c with 260000 tokens in 10166.99982 ms, 25572.93249 tok/sec +``` + +## Draw + +### Non-LTO +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00675 ms +``` + +### Full LTO + +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00470 ms +``` + +### ThinLTO + +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00358 ms +``` + +
+ +
+Binary sizes of non-LTO, LTO and thinLTO binaries on Linux + +### Non-LTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 3875520 Blocks: 7576 IO Block: 4096 regular file +``` + +### Full LTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 3772728 Blocks: 7376 IO Block: 4096 regular file +``` + +### ThinLTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 4012640 Blocks: 7840 IO Block: 4096 regular file +``` + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `79d3871e8e1e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2049/solution/patch.diff b/tasks/lite-xl__lite-xl-2049/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0ca0c079603ee3b21f97bf189fd8a2ac502a9ff1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/solution/patch.diff @@ -0,0 +1,177 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 95e71315..1868f67b 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -90,28 +90,28 @@ jobs: + bash --version + gcc -v + xcodebuild -version +- ++ + - uses: actions/checkout@v4 +- ++ + - name: Python Setup + uses: actions/setup-python@v5 + with: { python-version: "3.11" } +- ++ + - name: Install Dependencies + run: | + brew install bash + pip3 install meson ninja +- ++ + - name: Build & Package Mac (Bundle) + run: | +- scripts/build.sh --addons --debug --forcefallback --reconfigure --bundle --mode ${{ needs.version.outputs.buildtype }} -b build ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --lto --bundle --mode ${{ needs.version.outputs.buildtype }} -b build + tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-bundle.tar.gz "Lite XL.app" + + - name: Build & Package Mac (Portable) + run: | +- scripts/build.sh --addons --debug --forcefallback --reconfigure --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build + tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-portable.tar.gz lite-xl +- ++ + - name: Upload (Intermediate) + uses: actions/upload-artifact@v4 + with: +@@ -124,7 +124,7 @@ jobs: + name: Darwin (Universal) + needs: [version, build_darwin] + runs-on: macos-14 +- steps: ++ steps: + - uses: actions/checkout@v4 + + - name: Python Setup +@@ -135,7 +135,7 @@ jobs: + run: | + brew install bash + pip3 install dmgbuild +- ++ + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: +@@ -159,7 +159,7 @@ jobs: + dmgbuild -s resources/macos/lite-xl-dmg.py \ + -D "app_path=lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-bundle/Lite XL.app" \ + "Lite XL" "lite-xl-${{ needs.version.outputs.ref }}-universal-darwin.dmg" +- ++ + - name: Package Darwin (Universal Portable) + run: tar -C lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable -zcvf lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable.tar.gz . + +@@ -178,13 +178,13 @@ jobs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 +- ++ + - name: Build + uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v4 + with: + entrypoint: /entrypoint.sh +- args: bash scripts/build.sh --addons --debug --forcefallback --portable --mode ${{ needs.version.outputs.buildtype }} -b build +- ++ args: bash scripts/build.sh --addons --debug --forcefallback --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ + - name: Package Linux (Portable) + run: tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl + +@@ -192,8 +192,8 @@ jobs: + uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v4 + with: + entrypoint: /entrypoint.sh +- run: bash scripts/package-appimage.sh --debug --reconfigure --version ${{ needs.version.outputs.ref }} --mode ${{ needs.version.outputs.buildtype }} -b build +- ++ run: bash scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build ++ + - name: Upload (Release) + uses: actions/upload-artifact@v4 + with: +@@ -201,12 +201,12 @@ jobs: + path: | + *.tar.gz + *.AppImage +- ++ + + build_windows: + name: Windows (x86_64) (MSYS) + runs-on: windows-2019 +- defaults: ++ defaults: + run: + shell: msys2 {0} + needs: [version] +@@ -226,16 +226,16 @@ jobs: + pkg-config:p + + - uses: actions/checkout@v4 +- ++ + - name: Build +- run: bash scripts/build.sh --addons --debug --forcefallback --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ run: bash scripts/build.sh --addons --debug --forcefallback --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build + + - name: Package Windows (Portable) + run: cd build && zip -r ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows-portable.zip lite-xl && cd .. +- ++ + - name: Package Windows (InnoSetup) + run: bash scripts/package-innosetup.sh --debug --version ${{ needs.version.outputs.ref }} -b build +- ++ + - name: Upload (Release) + uses: actions/upload-artifact@v4 + with: +diff --git a/scripts/build.sh b/scripts/build.sh +index 395ee132..23093d73 100755 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -33,6 +33,8 @@ show_help() { + echo "-O --pgo Use profile guided optimizations (pgo)." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." ++ echo "-L --lto [MODE] Enables Link-Time Optimization (LTO)." ++ echo " MODE: [default],thin" + echo " --cross-platform PLATFORM Cross compile for this platform." + echo " The script will find the appropriate" + echo " cross file in 'resources/cross'." +@@ -54,6 +56,8 @@ main() { + local bundle="-Dbundle=false" + local portable="-Dportable=false" + local pgo ++ local lto ++ local lto_mode + local cross + local cross_platform + local cross_arch +@@ -122,6 +126,14 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; ++ -L|--lto) ++ lto="-Db_lto=true" ++ if [[ -n $2 ]] && [[ $2 != -* ]]; then ++ lto_mode="-Db_lto_mode=$2" ++ shift ++ fi ++ shift ++ ;; + --cross-arch) + cross="true" + cross_arch="$2" +@@ -225,6 +237,8 @@ main() { + $bundle \ + $portable \ + $pgo \ ++ $lto \ ++ $lto_mode \ + $plugins \ + $reconfigure + diff --git a/tasks/lite-xl__lite-xl-2049/solution/solve.sh b/tasks/lite-xl__lite-xl-2049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/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/lite-xl__lite-xl-2049/task.toml b/tasks/lite-xl__lite-xl-2049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..55675bd1e579cd904a2f4025c70774762806c80d --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/lite-xl__lite-xl-2049" +description = "LTO" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "lite-xl", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "lite-xl/lite-xl" +ref = "79d3871e8e1e24d2289c472bfc7231b025589fcb" +reference = "https://github.com/lite-xl/lite-xl/pull/2049" +source_access = "auto" +built_at = "2026-11-16T16:09:56.187700+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:92f9ee93d4c99cb6fa6dbfcea33a969669a2199364722d587122af81ea265fbe" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-31T18:34:32Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build.yml", + "scripts/build.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 56 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.320319+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6606180bd7539f2c7f22795ce949ecf073a0120c02a2d2a614db22015681dcde" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/lite-xl__lite-xl-2049/tests/capture.py b/tasks/lite-xl__lite-xl-2049/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/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/lite-xl__lite-xl-2049/tests/instruction.md b/tasks/lite-xl__lite-xl-2049/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47bfaa9fe640016688d66b95a924565a99800474 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/tests/instruction.md @@ -0,0 +1,113 @@ +# Issue + +**Title:** LTO + +## Description + +We should use LTO for all (at least Linux) builds. +LTO generally comes in two flavors - thin and full LTO, where thinLTO is currently available on LLVM (clang) only. + +All examples here are compiled with clang and lld (v19.1.7) on 6.13.7-3-cachyos. + +### Highlights + +| Criteria | Non-LTO (Base) | Full LTO | thinLTO +| -------- | -------------- | -------- | ------- +| Tokenizer | 22743.91964 tok/sec | 25716.07018 tok/sec (+13.07%) | 25572.93249 tok/sec (+12.44%) +| Draw | 0.00675 ms/frame | 0.00470 ms/frame (-30.37%) | 0.00358 ms/frame (-46.96%) +| Binary Size | 3875520 Bytes | 3772728 Bytes (-2.65%) | 4012640 Bytes (+3.54%) + +
+Benchmarks of non-LTO, LTO and thinLTO builds + +Benchmark tests tokenizing [sqlite.c](https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip), as well as rendering text for 1000 frames. + +Benchmark code here: +[bootstrap.zip](https://github.com/user-attachments/files/19402579/bootstrap.zip) + +Run with: + +```sh +$ LDFLAGS='-fuse-ld=lld' CC=clang CXX=clang++ bash scripts/build.sh -P --forcefallback --lto && ln -s ../../../data/bootstrap.lua build-x86_64-linux/lite-xl/data/bootstrap.lua && LITE_XL_RUNTIME=bootstrap build-x86_64-linux/lite-xl/lite-xl tokenizer +$ LDFLAGS='-fuse-ld=lld' CC=clang CXX=clang++ bash scripts/build.sh -P --forcefallback --lto && ln -s ../../../data/bootstrap.lua build-x86_64-linux/lite-xl/data/bootstrap.lua && LITE_XL_RUNTIME=bootstrap build-x86_64-linux/lite-xl/lite-xl draw +``` + +## Tokenizer + +### Non-LTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: .......................Interrupted (more than 10s) +Tokenized sqlite.c with 230000 tokens in 10112.59289 ms, 22743.91964 tok/sec +``` + +### Full LTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: ...........................Interrupted (more than 10s) +Tokenized sqlite.c with 270000 tokens in 10499.27139 ms, 25716.07018 tok/sec +``` + +### ThinLTO + +``` +Sleeping 10 seconds for CPU to calm down... +Tokenizing sqlite3.c: ..........................Interrupted (more than 10s) +Tokenized sqlite.c with 260000 tokens in 10166.99982 ms, 25572.93249 tok/sec +``` + +## Draw + +### Non-LTO +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00675 ms +``` + +### Full LTO + +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00470 ms +``` + +### ThinLTO + +``` +Sleeping 10 seconds for CPU to calm down... +average frames over 10000 frames: 0.00358 ms +``` + +
+ +
+Binary sizes of non-LTO, LTO and thinLTO binaries on Linux + +### Non-LTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 3875520 Blocks: 7576 IO Block: 4096 regular file +``` + +### Full LTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 3772728 Blocks: 7376 IO Block: 4096 regular file +``` + +### ThinLTO + +``` + File: build-x86_64-linux/lite-xl/lite-xl + Size: 4012640 Blocks: 7840 IO Block: 4096 regular file +``` + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `79d3871e8e1e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/lite-xl__lite-xl-2049/tests/oracle.patch b/tasks/lite-xl__lite-xl-2049/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0ca0c079603ee3b21f97bf189fd8a2ac502a9ff1 --- /dev/null +++ b/tasks/lite-xl__lite-xl-2049/tests/oracle.patch @@ -0,0 +1,177 @@ +diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml +index 95e71315..1868f67b 100644 +--- a/.github/workflows/build.yml ++++ b/.github/workflows/build.yml +@@ -90,28 +90,28 @@ jobs: + bash --version + gcc -v + xcodebuild -version +- ++ + - uses: actions/checkout@v4 +- ++ + - name: Python Setup + uses: actions/setup-python@v5 + with: { python-version: "3.11" } +- ++ + - name: Install Dependencies + run: | + brew install bash + pip3 install meson ninja +- ++ + - name: Build & Package Mac (Bundle) + run: | +- scripts/build.sh --addons --debug --forcefallback --reconfigure --bundle --mode ${{ needs.version.outputs.buildtype }} -b build ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --lto --bundle --mode ${{ needs.version.outputs.buildtype }} -b build + tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-bundle.tar.gz "Lite XL.app" + + - name: Build & Package Mac (Portable) + run: | +- scripts/build.sh --addons --debug --forcefallback --reconfigure --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ scripts/build.sh --addons --debug --forcefallback --reconfigure --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build + tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-${{ matrix.config.arch }}-portable.tar.gz lite-xl +- ++ + - name: Upload (Intermediate) + uses: actions/upload-artifact@v4 + with: +@@ -124,7 +124,7 @@ jobs: + name: Darwin (Universal) + needs: [version, build_darwin] + runs-on: macos-14 +- steps: ++ steps: + - uses: actions/checkout@v4 + + - name: Python Setup +@@ -135,7 +135,7 @@ jobs: + run: | + brew install bash + pip3 install dmgbuild +- ++ + - name: Download Artifacts + uses: actions/download-artifact@v4 + with: +@@ -159,7 +159,7 @@ jobs: + dmgbuild -s resources/macos/lite-xl-dmg.py \ + -D "app_path=lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-bundle/Lite XL.app" \ + "Lite XL" "lite-xl-${{ needs.version.outputs.ref }}-universal-darwin.dmg" +- ++ + - name: Package Darwin (Universal Portable) + run: tar -C lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable -zcvf lite-xl-${{ needs.version.outputs.ref }}-universal-darwin-portable.tar.gz . + +@@ -178,13 +178,13 @@ jobs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 +- ++ + - name: Build + uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v4 + with: + entrypoint: /entrypoint.sh +- args: bash scripts/build.sh --addons --debug --forcefallback --portable --mode ${{ needs.version.outputs.buildtype }} -b build +- ++ args: bash scripts/build.sh --addons --debug --forcefallback --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ + - name: Package Linux (Portable) + run: tar -C build -czvf lite-xl-${{ needs.version.outputs.ref }}-x86_64-linux-portable.tar.gz lite-xl + +@@ -192,8 +192,8 @@ jobs: + uses: docker://ghcr.io/lite-xl/lite-xl-build-box-manylinux:v4 + with: + entrypoint: /entrypoint.sh +- run: bash scripts/package-appimage.sh --debug --reconfigure --version ${{ needs.version.outputs.ref }} --mode ${{ needs.version.outputs.buildtype }} -b build +- ++ run: bash scripts/package-appimage.sh --debug --version ${{ needs.version.outputs.ref }} -b build ++ + - name: Upload (Release) + uses: actions/upload-artifact@v4 + with: +@@ -201,12 +201,12 @@ jobs: + path: | + *.tar.gz + *.AppImage +- ++ + + build_windows: + name: Windows (x86_64) (MSYS) + runs-on: windows-2019 +- defaults: ++ defaults: + run: + shell: msys2 {0} + needs: [version] +@@ -226,16 +226,16 @@ jobs: + pkg-config:p + + - uses: actions/checkout@v4 +- ++ + - name: Build +- run: bash scripts/build.sh --addons --debug --forcefallback --portable --mode ${{ needs.version.outputs.buildtype }} -b build ++ run: bash scripts/build.sh --addons --debug --forcefallback --lto --portable --mode ${{ needs.version.outputs.buildtype }} -b build + + - name: Package Windows (Portable) + run: cd build && zip -r ../lite-xl-${{ needs.version.outputs.ref }}-x86_64-windows-portable.zip lite-xl && cd .. +- ++ + - name: Package Windows (InnoSetup) + run: bash scripts/package-innosetup.sh --debug --version ${{ needs.version.outputs.ref }} -b build +- ++ + - name: Upload (Release) + uses: actions/upload-artifact@v4 + with: +diff --git a/scripts/build.sh b/scripts/build.sh +index 395ee132..23093d73 100755 +--- a/scripts/build.sh ++++ b/scripts/build.sh +@@ -33,6 +33,8 @@ show_help() { + echo "-O --pgo Use profile guided optimizations (pgo)." + echo " macOS: disabled when used with --bundle," + echo " Windows: Implicit being the only option." ++ echo "-L --lto [MODE] Enables Link-Time Optimization (LTO)." ++ echo " MODE: [default],thin" + echo " --cross-platform PLATFORM Cross compile for this platform." + echo " The script will find the appropriate" + echo " cross file in 'resources/cross'." +@@ -54,6 +56,8 @@ main() { + local bundle="-Dbundle=false" + local portable="-Dportable=false" + local pgo ++ local lto ++ local lto_mode + local cross + local cross_platform + local cross_arch +@@ -122,6 +126,14 @@ main() { + pgo="-Db_pgo=generate" + shift + ;; ++ -L|--lto) ++ lto="-Db_lto=true" ++ if [[ -n $2 ]] && [[ $2 != -* ]]; then ++ lto_mode="-Db_lto_mode=$2" ++ shift ++ fi ++ shift ++ ;; + --cross-arch) + cross="true" + cross_arch="$2" +@@ -225,6 +237,8 @@ main() { + $bundle \ + $portable \ + $pgo \ ++ $lto \ ++ $lto_mode \ + $plugins \ + $reconfigure +